Arya Akhavein
Arya Akhavein

Reputation: 355

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);
        }
    }
}

Upvotes: 4

Views: 770

Answers (1)

rustyBucketBay
rustyBucketBay

Reputation: 4561

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.

Upvotes: 3

Related Questions