Search code examples
c#unity-game-enginegameobjectinspectorprefab

I can't drag gameObject into prefab public variable


I have a bullet prefab in 2D unity and I want to drag a gameObject into a public variable so I can deal damage but it won't work. Here is my code, the gameObject I want to drag in is called EnemyAI and there is a script called EnemyAI.

public EnemyAI EnemyHealth;

    void OnCollisionEnter2D(Collision2D coll)
    {
        print("Collided");
        if (coll.gameObject.tag == "Wall") //Change tag
            Destroy(gameObject);
        if (coll.gameObject.tag == "Enemy") //Change tag
            Destroy(gameObject);
            EnemyHealth.TakeDamage(10);
    }

I wanted it to be able to drag the game object in but it didn't let me. I have done this exact same thing before but where the enemy hurts the player, please help.


Solution

  • You cannot assign an object from a scene or other file in the project to a prefab unless it is one of its children. This problem of yours has a logical root and also a logical solution. For example, if you could insert an object, if this bullet hits any enemy, it would reduce the life of the specified object, which does not seem logical. So better remove EnemyAI from public variable and get it from collider.

    void OnCollisionEnter2D(Collision2D coll)
    {
        print("Collided");
        if (coll.gameObject.tag == "Wall") //Change tag
            Destroy(gameObject);
        if (coll.gameObject.tag == "Enemy") //Change tag
        {
            coll.gameObject.GetComponent<EnemyAI>().TakeDamage(10); // it will take EnemyAI from collider that has Enemy Tag
            Destroy(gameObject);
        }
    }