Hi.
I’m having a problem with my script trying to access the renderer but the renderer is in the child (CModel - Transform, Mesh Filter, Mesh Renderer components) and not the parent (Character - Transform, Collider, Rigidbody, movement script, material switch script) so I’m getting this error:
MissingComponentException: There is no ‘Renderer’ attached to the “Character” game object, but a script is trying to access it.
You probably need to add a Renderer to the game object “Character”. Or your script needs to check if the component is attached before using it.
Below is the script attached to the parent, trying to access the renderer (it switches between 2 materials on a mouse click):
public Material[] materials;
int index = 0;
// Use this for initialization
void Awake ()
{
renderer.material = materials[index];
}
// Update is called once per frame
void Update ()
{
CheckMouseInput ();
playerShift ();
}
void CheckMouseInput ()
{
if (Input.GetMouseButtonDown (0)) //if left mouse button (0) is clicked
{
//code to check that player touch a specified area using ray casting. Line drawn from camera, if it hits our collider run the code.
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); //creates a screen position when mouse button clicked down, ray goes there
RaycastHit hitInfo; //holds info from ray cast
if(Physics.Raycast (ray, out hitInfo))//if Physics ray hits, push out hit info
{
index++;
if(index >= materials.Length)
index = 0;
renderer.material = materials[index];
}
}
}
void CheckTouchInput()
{
if (Input.touchCount > 0)
{
if (Input.touches [0].phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay (Input.touches [0].position); //creates a screen position when mouse button clicked down, ray goes there
RaycastHit hitInfo; //holds info from ray cast
if (Physics.Raycast (ray, out hitInfo)) //if Physics ray hits, push out hit info
{
index++;
if(index >= materials.Length)
index = 0;
renderer.material = materials[index];
}
}
}
}
void OnMouseDown()
{
index++;
if(index >= materials.Length)
index = 0;
renderer.material = materials[index];
}
I’ve tried using GetComponentsInChildren but not sure where to put it so I still get the same error.
Tried adding a renderer component to the parent but that stops the material switching.
What am I missing?