Static variables

Hi!

I was wondering if you could use other things than static variables in your script.

I’m trying to call a function from one script to another, and for that I’m using static.
I’ve heard that you should avoid them, so do any of you guy sknow what I can use instead?

Hello,

You just have to keep a reference of your class in other scripts. Here is an example:

public class firstClass : MonoBehaviour{


    public  void SayHello(){
        Debug.Log("Hello !");
    }

}

Then reference the firstClass in your second class by assigning it from the inspector.

 public class secondClass{
    
        public firstClass firstClassRef;
    
        void Start(){
           firstClassRef.SayHello();
        }
    
    }

Or reference it by script if you want to keep it private.

 public class secondClass : MonoBehaviour{
    
        firstClass firstClassRef ;
    
        void Start(){

           if( gameObject.GetComponent("firstClass") as firstClass  == null)
              firstClassRef = gameObject.AddComponent("firstClass") as firstClass ;
               
           firstClassRef.SayHello();
        }
    
    }

In this second case we check if the firstClass script is attached to the same gameObject as secondClass if not we add it.

regards