Z
Z
Z_programmer2021-08-24 22:57:42
Unity
Z_programmer, 2021-08-24 22:57:42

Why doesn't SetActive() work in Unity?

Hello, I have a problem: The fact is that on my character there is a Playerattack script, and it looks like this:

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

public class Playerattack : MonoBehaviour
{
    public float attackTime;
    public float startTimeAttack;

    public GameObject attack;

    private void Start()
    {
        attack.gameObject.SetActive(false);
    }

    void Update()
    {
        if(attackTime <= 0)
        {
            if(Input.GetKeyDown(KeyCode.E))
            {
                Debug.Log("start time");
                attack.gameObject.SetActive(true);
                attackTime = startTimeAttack;
            }
        }
        else if(attackTime > 0)
        {
            attackTime -= Time.deltaTime;
            Debug.Log("stop time");
            attack.gameObject.SetActive(false);
        }
      
    }
}

When the value of the attackTime variable is less than or exactly zero, then when the E button is pressed, a message should be written to the console "start time" and the object in the attack variable should be included, this variable contains the child center object. Script in the object itself:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackScript : MonoBehaviour
{
    public void OnTriggerStay2D(Collider2D other)
    {
        if(other.tag == "enemy")
        {
            Debug.Log("Damage was dealt!");
        }
    }
}

That is, when it is activated and touches an object with the "enemy" tag, it should write "Damage was dealt!" to the console.

But the fact is that when you press E, "start time" is written to the console, but the center object itself is not included. But the center object itself, when touched with an object with the "enemy" tag, prints "Damage was dealt!" to the console, that is, it works.
I do not understand why both scripts are supposed to work fine, but the center object is not included

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Sokolov, 2021-08-25
@NikS42

Update is not called on a disabled object. As well as collision, physics and animator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question