Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For some reason GameObject.Find().SetActive(true) doesn't work and I am unsure why

In my game my player has 2 weapons and in this level I want to make it so that once the player runs out of ammo the shotgun deactivates and the axe activates. Both weapons are child's of the player but this script is attached to the player. The shotgun deactivates but the axe doesn't activate and I don't know why. Thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ammo : MonoBehaviour
{
    public int ammo = 165; 

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(ammo == 0)
        {            
            GameObject.Find("wp_shotgun").SetActive(false);
            GameObject.Find("wp_axe").SetActive(true);
        }
    }
}
like image 360
Arya Akhavein Avatar asked Oct 29 '25 13:10

Arya Akhavein


1 Answers

Take into account that a GameObject may be inactive because a parent is not active. In that case, calling SetActive will not activate it, but only set the local state of the GameObject, which you can check using GameObject.activeSelf. Unity can then use this state when all parents become active. Check the documentation.

What I would do is check the hierarchy in case there is some gameobject messing with the desired GO activation, and second check if there is any error in the console in case the GameObject.Find() could throw a nullreference exeption.

like image 180
rustyBucketBay Avatar answered Oct 31 '25 12:10

rustyBucketBay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!