Spawning & Despawning Character With Same Key Not Working

hi all, (beginner level)

I’m trying to spawn a character with button press e and despawn it with the same key by checking if it exists in scene or not. If it does not exist in scene and e is pressed, it should spawn the characer, if it does exist in scene and e is pressed it should despawn the character.

I’m having trouble with the check if in scene part. Spawning works if I remove the game object find part, but it does not spawn at all with the check in place in the if statement. (the object is not present in the scene/hierarchy by default, so that should not be the problem).

How do I go about fixing this? Thks!

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

public class CharController001 : MonoBehaviour

{

    public GameObject PlayerChar001;

    void Update()
    {
        
       if (Input.GetKeyDown(KeyCode.E) && GameObject.Find("PlayerChar001") != null)

        {
            Instantiate(PlayerChar001, GameObject.Find("UtilitySpawnChar001").transform.position, Quaternion.identity);
        }

    }
}

Right now your if statement is saying: If E is pressed down and we can find PlayerChar001 in the scene, spawn PlayerChar001. So that’s definitely not what you want. You’re also relying on the name, which after instantiation will become “PlayerChar001 (Clone)”, so your logic wouldn’t quite work anyways.

Instantiate() returns the object that it creates. Hold on to that reference and use that, rather than relying on the name, in deciding on if you’re going to spawn or despawn your character.

public GameObject PlayerChar001_Prefab;

private GameObject PlayerChar001_Instance;

void Update()
{
   if(Input.GetKeyCode(KeyCode.E) == true)
   {
       if(PlayerChar001_Instance != null) // we already spawned it
       {
           Destroy(PlayerChar001_Instance);

           PlayerChar001_Instance = null;
       }
       else // we need to spawn them
       {
           PlayerChar001_Instance = Instantiate(PlayerChar001_Prefab, GameObject.Find("UtilitySpawnChar001").transform.position, Quaternion.identity);
       }
   
   }
}
1 Like

thks so much for the info!