- Home /
 
Null Reference after finding object already
well i have a problem with a script using a function of another script and coming up with null reference after i already got a debug.log to tell me that it found the object.to test the script i have it call a function from the other script both in the start and the update functions. and the function works fine for the start but when it gets to the update the script lost its reference and changed it to null. here is the script:
 private PlayerScript playerscript;
     PlayerScript playerz;    
     
     
     void Start () {        
         PlayerScript playerz = FindObjectOfType<PlayerScript>();
 //        
         playerz.DEDE();
     }
     
     // Update is called once per frame
     void Update () {
         playerz.DEDE();
     }
 
               this is the error i get 
and all the other script say to do is this function:
 public class PlayerScript : MonoBehaviour {
 
 public void DEDE(){
         Debug.Log ("Found Player");
     }
 }
 
               so if anyone could please answer me why this is happening i would be so appreciative. Please and thank you.
Answer by gjf · Jan 31, 2015 at 12:57 PM
you haven't set up playerz properly so when you reference it in Update() it'll throw the null reference...
you're probably thinking that you did, but you're wrong ;) in Start() when you do this:
 PlayerScript playerz = FindObjectOfType<PlayerScript>();
 
               you're only setting a local variable, also called playerz. change it to 
 playerz = FindObjectOfType<PlayerScript>();
 
               and it should work...
Your answer
 
             Follow this Question
Related Questions
Multiple FindObjectOfType to the same object, best practice 1 Answer
Will FindObjectsOfType always return the same array for a static Hierarchy? 0 Answers
FindObjectOfType and derived classes doesn't seem, to work. 1 Answer
how to Find Objects Of Type<> but with But with an exception 2 Answers
Converting object into script 1 Answer