Accessing another script from a script

I’m currently attempting to reference another script attached to a separate GameObject. However, it appears as though I can’t use the drag-and-drop method, because I can’t figure out what variable type would accept a script component reference. Anyone have any suggestions? Thanks in advance.

Drag-and-drop thing might happen with almost all components. Your problem is that you don’t see the variable in the inspector? Maybe you forgot to declare it as a public variable?

Of course, the best thing you can do now is to give the scripts.

You need to make a public GameObject variable and then you can drag and drop your other object to it. From here you can reference its components including scripts.

Well, the type of the script would work:

public class ReferenceScript
{
    public string Name { get; set; }
   
    private void Awake()
    {
        Name = "Sample";
    }
}

public class CallingScript
{
    [SerializeField]
    private ReferenceScript reference;
   
    private void Start()
    {
        if(reference != null)
        {
            Debug.Log(reference.Name);
        }
    }
}

If you now would drag the gameObject that has the ReferenceScript component on that field of the CallingScript, then you’ll have access to it’s referenceScript component.

1 Like

Thanks alot; this really helped!