- Home /
Can't Get .enabled to Work for Children Sprites
So I have an object with a few children. I want to be able to disable/enable 2 of them via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below:
public bool isAiming = false;
Animator playerAnim;
GameObject arm;
GameObject weapon;
SpriteRenderer armRenderer;
SpriteRenderer weaponRenderer;
void Start()
{
playerAnim = gameObject.GetComponent<Animator>();
arm = GameObject.FindGameObjectWithTag("Arm");
weapon = GameObject.FindGameObjectWithTag("EquippedWeapon");
armRenderer = arm.GetComponent<SpriteRenderer>();
weaponRenderer = weapon.GetComponent<SpriteRenderer>();
}
void Update()
{
CheckIfAiming();
}
void CheckIfAiming()
{
if (Input.GetButton("Fire2")) // Holding right click
{
isAiming = true;
armRenderer.enabled = true;
weaponRenderer.enabled = true;
playerAnim.SetBool("isAiming", isAiming);
}
else
{
isAiming = false;
armRenderer.enabled = false;
weaponRenderer.enabled = false;
playerAnim.SetBool("isAiming", isAiming);
}
}
What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false/true) is not an option as I still want code to affect them while they're not visible.
Am I just trying to access the SpriteRenderers incorrectly?
Answer by ToastandBananas · Jun 22, 2018 at 04:16 PM
Finally figured it out!
Here's what I used:
Renderer[] renderChildren = GetComponentsInChildren<Renderer>();
int i;
for(i = 1; i < renderChildren.Length; ++i)
{
renderChildren[i].renderer.enabled = true;
}
And then when I wanted the SpriteRenderers to be disabled I did the same thing, except I set it to false. I started i equal to 1 so that it would skip the parent object's renderer and only change the children.
Answer by LeeroyLin · Jun 22, 2018 at 04:09 AM
You mean your weapon is an object has many children? If you want to show or hide children of that object, you have to enable or disable the SpriteRenderer component on every child. So what you do is to use a loop like this:
foreach (Transform child in weapon.transform){
child.GetComponent<SpriteRenderer>().enabled = false;
}
I'm not sure if this is what you mean, hope this can help you. Any question can reply, good day.
Nope, the weapon and the arms are the children. The characters body is the parent. I figured it out though, thanks!
Your answer
Follow this Question
Related Questions
What are the best practices when importing 2D pixel sprites 1 Answer
How do I change Raycast's direction based on movement input? 1 Answer
How do I select a group full of sprites, between two points? 1 Answer
Unity Game View won't refresh my sprites 1 Answer
Teleport Not Working in Unity 2D 1 Answer