Search Unity

Object reference not set to an Instance of an object

Discussion in 'Getting Started' started by edubrider, Jul 22, 2018.

  1. edubrider

    edubrider

    Joined:
    Jul 22, 2018
    Posts:
    3
    Hi,

    I have two scripts (for practice) Script A should handle key inputs and depending on the pressed key it should call a function from another script B. For example if I press R the keyhandler script (A) should call a function of script B and the function in script B should change the color of the gameobject.

    //Keyhandler
    Code (CSharp):
    1. public class A : MonoBehaviour {
    2.  
    3.  
    4.     public B b;
    5.     // Use this for initialization
    6.     void Start () {
    7.        
    8.     }
    9.    
    10.     // Update is called once per frame
    11.     void Update () {
    12.  
    13.         if (Input.GetKeyDown(KeyCode.R))
    14.         {
    15.            
    16.            b.setRed();
    17.         }
    18.         if (Input.GetKeyDown(KeyCode.B))
    19.         {
    20.             b.setBlue();
    21.         }
    22.  
    23.        
    24.  
    25.     }
    26. }
    //ColorChanger
    Code (CSharp):
    1. public class B : MonoBehaviour {
    2.    
    3.     public GameObject cube;
    4.  
    5.     // Use this for initialization
    6.     void Start () {
    7.      
    8.     }
    9.    
    10.     // Update is called once per frame
    11.     void Update () {
    12.  
    13.     }
    14.  
    15.     public void setBlue()
    16.     {
    17.        
    18.         cube.GetComponent<Renderer>().material.color = Color.blue;
    19.     }
    20.  
    21.     public void setRed()
    22.     {
    23.         cube.GetComponent<Renderer>().material.color = Color.red;
    24.     }
    25.    
    26. }
    I also linked my cube to the B Script.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    But did you link your B script to the A script?
     
    edubrider likes this.
  3. edubrider

    edubrider

    Joined:
    Jul 22, 2018
    Posts:
    3
    Im a stupid idiot I forgot to add the B script to the A script in the Inspector....
     
  4. edubrider

    edubrider

    Joined:
    Jul 22, 2018
    Posts:
    3
    I could punch myself ....
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Everybody does that now and then. :)