In my Unity 4.3 all work well, but after Upgrade to 5 I have a problem with GetComponent. To test a new deprecable GetComponent I have use the official tutorial
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public GameObject otherGameObject;
private AnotherScript anotherScript;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
}
void Update ()
{
Debug.Log("The player's score is " + anotherScript.playerScore);
}
}
And the second script
using UnityEngine;
using System.Collections;
public class AnotherScript : MonoBehaviour {
public int playerScore = 9001;
}
This is only for test,
i've used the same example of the unity tutorial https://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
After that I've associated the two object in the editor But the run report is:
NullReferenceException: Object reference not set to an instance of an object test.Update () (at Assets/test.cs:22)
in unity 4.3 work well.
You should try getting the reference in the Start method. Make sure that both test
and AnotherScript
scripts are attached to the-same GameObject in the Editor, then the code below should work.
using UnityEngine;
using System.Collections;
public class test: MonoBehaviour
{
public int playerScore;
void Start()
{
anotherScript = gameObject.GetComponent<AnotherScript>();
}
void Update ()
{
Debug.Log("The player's score is " + anotherScript.playerScore);
}
}
If both Scripts are not attached to the-same GameObject then use:
anotherScript = GameObject.Find("Name of GameObject AnotherScript is Attched To").GetComponent<AnotherScript>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With