Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can i access a monobehaviour script from within a non monobehaviour script?

Discussion in 'Scripting' started by Zaine7673, May 1, 2019.

  1. Zaine7673

    Zaine7673

    Joined:
    Feb 15, 2018
    Posts:
    238
    The two classes need to stay as they are as changing them will break a lot of functionality so i cant create an instance and cant attach to a gameobject to drag and drop

    Any ideas how i can get around this little issue?

    Code (CSharp):
    1. public class myClass1 : monoBehaviour
    2. {
    3.   public String text = "hello";
    4. }
    5.  
    6. public class myClass2
    7. {
    8.   private myClass1 monoClass = new myClass1();
    9.  
    10.   private void Start()
    11.   {
    12.     Debug.Log(monoClass.text);
    13.   }
    14. }
    15. //THIS DOES NOT WORK
     
  2. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    You can absolutly use a reference to a mono behaviour from anywhere (well, you can't operate on it from a different thread etc so there are constraints). But you must let Unity hook it up. So you can not instance it yourself like you have done.

    You can add it to a empty gameobject from your code though.
     
  3. Zaine7673

    Zaine7673

    Joined:
    Feb 15, 2018
    Posts:
    238
    Got it!! Worked perfectly thanks :)