Renderer.materials not working in void update()
this is my code and i get this error every frame
NullReferenceException: Object reference not set to an instance of an object wheelThreeScript.Start () (at Assets/Scripts/wheelScripts/wheelThreeScript.cs:20)
using UnityEngine; using System.Collections;
public class wheelThreeScript : MonoBehaviour {
 public int wheelSymbol;
 Renderer rend;
 SymbolPicker symbolPicker;
 public Material coin, coins, damage, heart, skull, jackpot;
 // Use this for initialization
 void Start () {
     Renderer renderer = GetComponent<Renderer> ();
     GameObject slotMachine = GameObject.FindGameObjectWithTag ("slotMachine");
     symbolPicker = slotMachine.GetComponent<SymbolPicker> ();
     rend.material = coin;
 }
 // Update is called once per frame
 void Update () {
     wheelSymbol = symbolPicker.wheelThreeSymbol;
     if (wheelSymbol == 1)
         rend.material = coin;
     if (wheelSymbol == 2)
         rend.material = coins;
     if (wheelSymbol == 3)
         rend.material = heart;
     if (wheelSymbol == 4)
         rend.material = damage;
     if (wheelSymbol == 5)
         rend.material = skull;
     if (wheelSymbol == 6)
         rend.material = jackpot;
 }
 
               }
Answer by Bunny83 · Jul 15, 2017 at 07:55 AM
You defined a private class member variable "rend":
 Renderer rend;
 
               However you never initialize it. In start you have this line:
 Renderer renderer = GetComponent<Renderer> ();
 
               which defines a local variable inside start which is initialized to the Renderer component of that gameobject, but you never use that local variable. I think you want to do
 rend = GetComponent<Renderer> ();
 
              Answer by tanoshimi · Jul 15, 2017 at 08:50 AM
You've not pasted the code correctly which it makes the line numbers tricky to follow, but I believe the line in question is:
 wheelSymbol = symbolPicker.wheelThreeSymbol;
 
               which suggests that the following line is returning null:
 symbolPicker = slotMachine.GetComponent<SymbolPicker> ();
 
               which suggests that the GO you're assigning to the symbolPicker variable doesn't have a SymbolPicker component.
Your answer
 
             Follow this Question
Related Questions
Randomly set an integer as positive or negative? 1 Answer
What is the correct way to learn unity scripting ? 2 Answers
Why does this C# doesnt Work? it seems to be right. 0 Answers
Ambient Emitter inside a BoxCollider - Rotation not recognized 0 Answers
I need help with code for audio file. 0 Answers