Ben
Ben

Reputation: 9

Enabling/Disabling Script in C# failing to work

So I've been developing a 2D platformer game in C# and Unity and as a part of the game I have been developing powerups. One of these in invincibility, so when the player collides with the game object they cannot be killed for a period of time. I am relatively new to Unity and C# and read that I can use '.enabled' to enable/disable an external script that is attached to the same object. However, when I activate the powerup the object is destroyed but if I collide with an enemy or object I still die. Can anyone see why this is happening.

Below is the script that I have developed.

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

public class InvincibilityPowerup : MonoBehaviour
{
    public int Duration = 15;

    void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Shield")
        {
            Destroy(GameObject.Find("Invincibility"));

            StartCoroutine("Invincible");
        }
    }
    IEnumerator Invincible()
    {
        Collision pIn = gameObject.GetComponent<Collision>();
        pIn.enabled = false;

        yield return new WaitForSeconds(Duration);

        pIn.enabled = true;

    }
}

Upvotes: 0

Views: 260

Answers (1)

1) GameObject.Find is completely unnecessary here. You already know which object is the invincibility powerup: its the one this script is attached to

2) Collision pIn = gameObject.GetComponent<Collision>(); both a) doesn't do what you want it to (you want to get the OTHER game object!) b) doesn't work anyway (Collision is not a component, Collider is)

3) you're destroying this before starting the coroutine, meaning your coroutine is being destroyed too.

Upvotes: 1

Related Questions