Are you getting any errors? FindGameObjectOfType “Returns the first active loaded object of Type type.” according to the documentation:
If these are not active your code will not be finding these objects to begin with. The fact that you’re trying to set them active afterward tells me they might not be active.
Does your player gameobject have a tag of “Player”?
Does your UFO gameobject have a collider component with IsTrigger checked?
I’ve also refactored your code because the update function seemed completely unnecessary from my understanding.
Take a look at what I’ve done and let me know if it achieves the same goal. This majorly reduces the complexity:
I also added in a few code comments.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UFO : MonoBehaviour
{
public GameObject UFO_player;
public Transform SpawnPoint;
public GameObject AstronautPly;
public GameObject playerAIPly;
public GameObject PCam;
GameManager gameManager;
Collider2D UFOColl;
Animator anim;
bool HasPlayer;
bool TakeOffEnd;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
//Return the player and ai if they're active
Player Astronaut = FindObjectOfType<Player>();
PlayerAI playerAI = FindObjectOfType<PlayerAI>();
UFOColl = GetComponent<BoxCollider2D>();
//If they weren't active, they wouldn't be returned by FindObjectOfType, so this wont do anything unless we change how we're retrieving them
AstronautPly.SetActive(true);
playerAIPly.SetActive(true);
//This is ok, assuming it's assigned in the inspector
PCam.SetActive(true);
}
public void OnTriggerEnter2D(Collider2D other)
{
UFOColl = GetComponent<BoxCollider2D>();
if (other.gameObject.CompareTag("Player"))
{
Debug.Log("hit ufo");
StartCoroutine(TakeOff());
}
}
public IEnumerator TakeOff()
{
yield return new WaitForSeconds(2);
anim.SetBool("HasPlayer", HasPlayer = true);
yield return new WaitForSeconds(2);
//Destroy the player and ai gameobjects
PCam.SetActive(false);
Destroy(AstronautPly);
Destroy(playerAIPly);
yield return new WaitForSeconds(2);
anim.SetBool("TakeOffEnd", TakeOffEnd = true);
Destroy(gameObject);
Instantiate(UFO_player, SpawnPoint.position, SpawnPoint.rotation);
}
}
By the way, TakeOffEnd and HasPlayer aren’t set true anywhere, so your animator bools will always be false.
I don’t know how your animator is set up so I can’t really give any advice on this.