Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetComponent upgrade from 4 to 5 not work

Tags:

c#

unity3d

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.

like image 388
fabrizioofabrizio Avatar asked Dec 15 '22 07:12

fabrizioofabrizio


1 Answers

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>();
like image 54
Alfie Goodacre Avatar answered Jan 03 '23 23:01

Alfie Goodacre