unity c#, unable to acces a variable form another script

1.8k Views Asked by At

I would like to acces a variable called cooldown from another script called BulletScript and i cant figure out what's wrong with my codes. Here are my codes: 1st:

using UnityEngine;

public class gunMechanic : MonoBehaviour
{
    private BulletScript bulletScript;

    private void Awake() {
        bulletScript = GameObject.FindObjectOfType<BulletScript>();
        Debug.Log(bulletScript.cooldown);
    }
}

2nd:


using UnityEngine;

public class BulletScript : MonoBehaviour
{
  public float cooldown = 1;
}
2

There are 2 best solutions below

4
Arcueid D'athemon On BEST ANSWER

Here are lots of different possible reasons for your issue. Try adding [SerializeField] before private BulletScript bulletScript; and directly serialize object with your script.

It's possible that you:

  1. don't add this script to object on your scene;
  2. has those scripts in two different additively loaded scenes;
  3. instancing object with second script after Awake() and/or Start();
  4. forget to instantiate object with the second script.

If you can provide any logs or more information about your project startup.

0
Francesco - FL On

First of all I think you should declare the variable as static, if you want the value to be that of the script you are looking for it in.

Don't declare the class and then look for the variable, call it directly with BulletScript.cooldown