Find Renderer Attached To Parent Object Runtime
Hi guys,
I have hit a wall trying to find the renderer to my other player.
Im developing a multiplayer game and need to access the other players mesh renderer then swap the shader. I have tried a number of things but non seem to work i keep getting renderer is null unless i manually drag the renderer in at runtime..
The renderer sits on the players mesh in the parent.
Here is what i have so far.
using UnityEngine;
using System.Collections;
public class KeepShader : MonoBehaviour {
public Shader shader;
public Renderer rend;
public GameObject remotePlayer;
void Update() {
remotePlayer = GameObject.FindGameObjectWithTag("Player");
remotePlayer.GetComponentInParent<Renderer>();
rend.material.shader = shader;
}
}
I know the rend reference to the renderer is obviously null in this example but i just can not work out how to access it in the parent at runtime and assign the rend, Any help appreciated guys.
I have read multiple examples and the unity documents but nothing seems to work.
rend = transform.parent.GetComponent<Renderer>();
this returns the renderer of the parent of the gameobject holding your $$anonymous$$eepShader-script. dunno if this is exactly what you want. if you try to access the remotePlayer's parent's renderer it would be
rend = remotePlayer.transform.parent.GetComponent<Renderer>();
also i would suggest you do not swap the shaders in your update function, since this will probably result in a flashy stroboscope effect. rather check in update for a condition that triggers a function containing your shader swap.
void Update(){
if (condition)
SwapShaders();
}
void SwapShaders(){
//swapCode
}
Thanks for the answer that seems to work, Next problem is that finds the "body" gameobject the mesh sits as a child to that how do you access that?
you can access the child of a gameobject by using:
GameObject child = body.transform.GetChild(0).gameObject;
this returns the first child of the body-gameobject.
you can also iterate through all childs of this body object by using
foreach(Transform child in body.transform)
(if child.name == "name from hierarchy")
// -> whatever you wanna do to the child
Answer by MRxBIGxSTUFF · Oct 21, 2016 at 09:46 PM
Thanks andzq for the initial answer which helped me solve the question which i just needed to adjust to my needs. i did the following to find the mesh within the parent.. rend = remotePlayer.transform.parent.GetComponentInChildren();
Your answer
Follow this Question
Related Questions
how to make a cube change color by clicking a button? 0 Answers
Make shader from Blender nodes 0 Answers
LineRenderer with Animation curve distorting texture? 0 Answers
Gameobject Renderer not working. 1 Answer