Unity3D can't Destroy instantiate - unity3d

public class SpawnerAI : MonoBehaviour
{
//Aha Permintaan
public GameObject[] Ahaprefab;
GameObject Ahaprefabclone1,Ahaprefabclone2,Ahaprefabclone3,Ahaprefabclone4,Ahaprefabclone5;
public Transform[] dupliposition;
//artoolkit
public GameObject ArtoolkitAc;
GameObject au,ax,artoolkitAC;
// Pergantian Permunculan AI
public Camera[] cameras;
public GameObject[] canvasall;
public GameObject[] Aishown;
public Transform[] aiposition;
GameObject peopleclone1;
GameObject peopleclone2;
GameObject peopleclone3;
GameObject peopleclone4;
GameObject peopleclone5;
private bool beingHandled = false;
public bool pos1 = false;
public bool pos2 = false;
public bool pos3 = false;
public bool pos4 = false;
public bool pos5 = false;
Animator Animdoor;
public Vector3 Gcenter;
public Vector3 TPosisi;
RaycastHit hit;
public bool touchedCh = false;
void Start()
{
cameras [0].enabled = true;
cameras [1].enabled = false;
canvasall [0].SetActive(true);
canvasall [1].SetActive(false);
Animdoor = GetComponent<Animator> ();
}
void Update () {
if (/*some case */ !beingHandled)
{
StartCoroutine (HandleIt ());
}
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit))
{
peopleclone1= hit.collider.gameObject;
Gcenter = peopleclone1.transform.position;
peopleclone2= hit.collider.gameObject;
Gcenter = peopleclone2.transform.position;
peopleclone3= hit.collider.gameObject;
Gcenter = peopleclone3.transform.position;
peopleclone4= hit.collider.gameObject;
Gcenter = peopleclone4.transform.position;
peopleclone5= hit.collider.gameObject;
Gcenter = peopleclone5.transform.position;
TPosisi = Camera.main.ScreenToWorldPoint (Input.mousePosition);
touchedCh = true;
}
}
if (Input.GetMouseButton (0)) {
if (touchedCh) {
TPosisi = Camera.main.ScreenToWorldPoint (Input.mousePosition);
cameras [0].enabled = false;
cameras [1].enabled = true;
canvasall [0].SetActive(false);
canvasall [1].SetActive(true);
//artoolkitAC.SetActive (true);
if (pos1==true) {
//pos1 = false;
Destroy(peopleclone1);
Destroy(GameObject.FindWithTag("Aha1"));
Debug.Log ("Posisi kesatu Kosong");
}
else if (pos2==true) {
//pos2 = false;
Destroy(peopleclone2);
Destroy(GameObject.FindWithTag("Aha2"));
Debug.Log ("Posisi kedua Kosong");
}
else if (pos3==true) {
//pos3 = false;
Destroy(peopleclone3);
Destroy(GameObject.FindWithTag("Aha3"));
Debug.Log ("Posisi ketiga Kosong");
}
else if (pos4==true) {
//pos4 = false;
Destroy(peopleclone4);
Destroy(GameObject.FindWithTag("Aha4"));
}
else if (pos5==true) {
//pos5 = false;
Destroy(peopleclone5);
Destroy(GameObject.FindWithTag("Aha5"));
Debug.Log ("Posisi kelima Kosong");
}
}
}
if(Input.GetMouseButtonUp(0)){
touchedCh= false;
}
//StartCoroutine(InfiniteLoop());
}
private IEnumerator HandleIt()
{
// AI
beingHandled = true;
int indAi = Random.Range (0, Aishown.Length);
// process pre-yield
Animdoor.SetInteger ("StateOP", 0);
yield return new WaitForSeconds( 3.0f );
if (pos1 == false) {
// process post-yield
yield return new WaitForSeconds( 8.0f );
Animdoor.SetInteger ("StateOP", 1);
GameObject.Find ("Bell").GetComponent<AudioSource> ().Play ();
GameObject.Find ("doorclose").GetComponent<AudioSource>().Play ();
peopleclone1 = Instantiate (Aishown [indAi], aiposition [0].position, Aishown [indAi].transform.rotation) as GameObject;
yield return new WaitForSeconds( 2.0f );
Ahaprefabclone1 = Instantiate (Ahaprefab[0], dupliposition [0].position, Quaternion.identity)as GameObject;
beingHandled = false;
pos1 = true;
Debug.Log ("Posisi Pertama telah diisi");
}
else if (pos2 == false) {
// process post-yield
yield return new WaitForSeconds( 8.0f );
Animdoor.SetInteger ("StateOP", 1);
GameObject.Find ("Bell").GetComponent<AudioSource> ().Play ();
GameObject.Find ("doorclose").GetComponent<AudioSource>().Play ();
peopleclone2 = Instantiate (Aishown [indAi], aiposition [1].position, Aishown [indAi].transform.rotation) as GameObject;
yield return new WaitForSeconds( 2.0f );
Ahaprefabclone2 = Instantiate (Ahaprefab[1], dupliposition [1].position, Quaternion.identity)as GameObject;
beingHandled = false;
pos2 = true;
Debug.Log ("Posisi Kedua telah diisi");
}
else if (pos3 == false) {
// process post-yield
yield return new WaitForSeconds( 8.0f );
Animdoor.SetInteger ("StateOP", 1);
GameObject.Find ("Bell").GetComponent<AudioSource> ().Play ();
GameObject.Find ("doorclose").GetComponent<AudioSource>().Play ();
peopleclone3 = Instantiate (Aishown [indAi], aiposition [2].position, Aishown [indAi].transform.rotation) as GameObject;
yield return new WaitForSeconds( 2.0f );
Ahaprefabclone3 = Instantiate (Ahaprefab[2], dupliposition [2].position,Quaternion.identity)as GameObject;
beingHandled = false;
pos3 = true;
Debug.Log ("Posisi Ketiga telah diisi");
}
else if (pos4 == false) {
// process post-yield
yield return new WaitForSeconds( 8.0f );
Animdoor.SetInteger ("StateOP", 1);
GameObject.Find ("Bell").GetComponent<AudioSource> ().Play ();
GameObject.Find ("doorclose").GetComponent<AudioSource>().Play ();
peopleclone4 = Instantiate (Aishown [indAi], aiposition [3].position, Aishown [indAi].transform.rotation) as GameObject;
yield return new WaitForSeconds( 2.0f );
Ahaprefabclone4 = Instantiate (Ahaprefab[3], dupliposition [3].position, Quaternion.identity)as GameObject;
beingHandled = false;
pos4 = true;
Debug.Log ("Posisi Keempat telah diisi");
}
else if (pos5 == false) {
// process post-yield
yield return new WaitForSeconds( 8.0f );
Animdoor.SetInteger ("StateOP", 1);
GameObject.Find ("Bell").GetComponent<AudioSource> ().Play ();
GameObject.Find ("doorclose").GetComponent<AudioSource>().Play ();
peopleclone5 = Instantiate (Aishown [indAi], aiposition [4].position, Aishown [indAi].transform.rotation) as GameObject;
yield return new WaitForSeconds( 2.0f );
Ahaprefabclone5 = Instantiate (Ahaprefab[4], dupliposition [4].position, Quaternion.identity)as GameObject;
beingHandled = false;
pos5 = true;
Debug.Log ("Posisi Kelima telah diisi");
}
//artoolkitAC = Instantiate (ArtoolkitAc) as GameObject;
//artoolkitAC.SetActive (false);
}
public void BacktoGameShop()
{
cameras [0].enabled = true;
cameras [1].enabled = false;
canvasall [0].SetActive(true);
canvasall [1].SetActive(false);
}
// End Of code
}
I tried many methods to destroy an instance object, but it does not get destroyed.
first I tried it with:
Destroy(ahaprefab1);
second I tried it with tag:
Destroy(GameObject.FindWithTag("Aha1"));
It still does not destroy the instance. But when i use it for Spawner Ai. Destroy(peopleclone1) does destroy the instance.
I'm stuck in this code.

well , would advice to first check if you object are not just null Debug.Log(peopleclone1)
if it's not null , try to use DestroyImmediate(peopleclone1)since the reason the gameobject is not destroy may be because he still actioning some stuff
if even DestroyImmediate don't work , then I don't realy know what to do :/

Related

I have a problem programming with unity to paste the image of footsteps on the ground when the player moves

public class FootPaint : MonoBehaviour
{
#region --- helpers --
public enum enumFoot
{
Left,
Right,
}
#endregion
public GameObject LeftPrefab;
public GameObject RightPrefab;
public float FootprintSpacer = 1.0f;
private Vector3 LastFootprint;
private enumFoot WhichFoot;
public GameObject[] intdexPos;
private void Start()
{
LastFootprint = this.transform.position;
}
private void Update()
{
FootPaints();
}
public void FootPaints()
{
if (CheckPaintItem.instance.isPaint == true && gameObject.name == "PlayerSeek")
{
float DistanceSinceLastFootprint = Vector3.Distance(transform.position, LastFootprint);
if (DistanceSinceLastFootprint >= FootprintSpacer)
{
LastFootprint = this.transform.position;
if (WhichFoot == enumFoot.Left)
{
SpawnFootDecal(LeftPrefab);
WhichFoot = enumFoot.Right;
}
else if (WhichFoot == enumFoot.Right)
{
SpawnFootDecal(RightPrefab);
WhichFoot = enumFoot.Left;
}
LastFootprint = new Vector3(this.transform.position.x, this.transform.position.y + 1f, this.transform.position.z);
}
}
}
public void SpawnFootDecal(GameObject prefab)
{
int index = Random.Range(0, intdexPos.Length);
//where the ray hits the ground we will place a footprint
GameObject decal = Instantiate(prefab);
decal.transform.position = intdexPos[index].transform.position;
decal.transform.Rotate(Vector3.forward, intdexPos[index].transform.eulerAngles.y);
//turn the footprint to match the direction the player is facing
}
}
public class CheckPaintItem : MonoBehaviour
{
public static CheckPaintItem instance;
#region boolPaint
[HideInInspector]
public bool isPaint = false;
[HideInInspector]
public bool isPaintYellow = false;
[HideInInspector]
public bool isPaintRed = false;
[HideInInspector]
public bool isPaintBlue = false;
[HideInInspector]
public bool isPaintGreen = false;
#endregion
private float currentMoveSpeed;
private void Awake()
{
instance = this;
}
private void Start()
{
currentMoveSpeed = 2.5f;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PaintsYellow")
{
Debug.Log("Yellow");
isPaint = true;
isPaintYellow = true;
StartCoroutine(timePaint());
}
else if (other.gameObject.tag == "PaintsRed")
{
isPaint = true;
isPaintRed = true;
StartCoroutine(timePaint());
}
else if (other.gameObject.tag == "PaintsBlue")
{
isPaint = true;
isPaintBlue = true;
StartCoroutine(timePaint());
}
else if (other.gameObject.tag == "PaintsGreen")
{
isPaint = true;
isPaintGreen = true;
StartCoroutine(timePaint());
}
else
{
isPaint = false;
isPaintYellow = false;
isPaintRed = false;
isPaintBlue = false;
isPaintGreen = false;
}
if (other.gameObject.tag == "PaintsGlue")
{
StartCoroutine(changeMoveSpeedSlow());
}
if (other.gameObject.tag == "Speed")
{
StartCoroutine(changeMoveSpeedFast());
Destroy(other.gameObject);
}
}
IEnumerator changeMoveSpeedSlow()
{
PlayerController.instance._moveSpeed = PlayerController.instance._moveSpeed / 2 + 0.2f;
yield return new WaitForSeconds(5f);
PlayerController.instance._moveSpeed = currentMoveSpeed;
}
IEnumerator changeMoveSpeedFast()
{
PlayerController.instance._moveSpeed = PlayerController.instance._moveSpeed + 1f;
yield return new WaitForSeconds(5f);
PlayerController.instance._moveSpeed = currentMoveSpeed;
}
IEnumerator timePaint()
{
yield return new WaitForSeconds(15f);
isPaint = false;
}
}
I want to code the game "hide and seek", but I had a problem when the character stepped into a puddle of paint.
My game has 1 character finding and 5 moving AIs, I want whether the AI or the player steps into the puddle, it will leave footprints. But I have problem with above scripts tag, I add script tag with all characters.
So one character walks in, all the other characters show their footsteps. I don't know if my direction is correct. If anyone wants to understand more about the game I'm coding, you can go to youtube and type hide and seek and it will come out.
Thank you.
It seems to me, that the problem lies within CheckPaintItem.instance.isPaint. I don't know what that script is exactly, but it's probably a singleton pattern as there is an instance call. If that's the case, then you're checking if any CheckPaintItem is true globally as it's fields are pretty much static. So make changes to CheckPaintItem or show us what it does exactly.

Unity 5 Inventory system not working

Hello programmers all around the world. I have made myself an inventory system for my game. Only problem is that when I click on item and then drag it to and empty slot it doesn't move and I kinda don't see the error which I am having and I have tried to debug it but without success any help? Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Inventory : MonoBehaviour {
private RectTransform inventoryRect;
private float inventoryWidth;
private float inventoryHeight;
public int slots;
public int rows;
public float slotPaddingLeft;
public float slotPaddingTop;
public float slotSize;
public GameObject slotPrefab;
private static Slot from;
private static Slot to;
private List<GameObject> allslots;
public GameObject iconPrefab;
private static GameObject hoverObject;
private static int emptySlots;
public Canvas canvas;
private float hoverYOffset;
private bool isPressed;
public EventSystem eventSystem;
public static int EmptySlots{
get{ return emptySlots;}
set{ emptySlots = value;}
}
// Use this for initialization
void Start () {
CreateLayout ();
canvas.enabled = false;
isPressed = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.I)) {
if (Input.GetKeyDown (KeyCode.I)) {
canvas.enabled = false;
}
canvas.enabled = true;
}
if (Input.GetMouseButtonUp (0)) {
if (!eventSystem.IsPointerOverGameObject (-1) && from != null) {
from.GetComponent<Image> ().color = Color.white;
from.ClearSlot ();
Destroy (GameObject.Find ("Hover"));
to = null;
from = null;
hoverObject = null;
}
}
if (hoverObject != null) {
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle (canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
position.Set (position.x, position.y - hoverYOffset);
hoverObject.transform.position = canvas.transform.TransformPoint (position);
}
}
private void CreateLayout(){
allslots = new List<GameObject> ();
hoverYOffset = slotSize * 0.01f;
emptySlots = slots;
inventoryWidth = (slots / rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
inventoryHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
inventoryRect = GetComponent<RectTransform> ();
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, inventoryWidth);
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, inventoryHeight);
int colums = slots / rows;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < colums; x++) {
GameObject newSlot = (GameObject)Instantiate (slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform> ();
newSlot.name = "Slot";
newSlot.transform.SetParent (this.transform.parent);
slotRect.localPosition = inventoryRect.localPosition + new Vector3 (slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, slotSize);
allslots.Add (newSlot);
}
}
}
public bool AddItem(Item item){
if (item.maxSize == 1) {
PlaceEmpty (item);
return true;
}
else {
foreach (GameObject slot in allslots) {
Slot temporary = slot.GetComponent<Slot> ();
if (!temporary.IsEmpty) {
if (temporary.CurrentItem.type == item.type && temporary.IsAvailable) {
temporary.AddItem (item);
return true;
}
}
}
if (emptySlots > 0) {
PlaceEmpty (item);
}
}
return false;
}
private bool PlaceEmpty(Item item){
if (emptySlots > 0) {
foreach (GameObject slot in allslots) {
Slot temporary = slot.GetComponent<Slot> ();
if (temporary.IsEmpty) {
temporary.AddItem (item);
emptySlots--;
return true;
}
}
}
return false;
}
public void MoveItem(GameObject clicked){
if (from == null) {
if (!clicked.GetComponent<Slot> ().IsEmpty) {
from = clicked.GetComponent<Slot> ();
from.GetComponent<Image> ().color = Color.gray;
hoverObject = (GameObject)Instantiate (iconPrefab);
hoverObject.GetComponent<Image> ().sprite = clicked.GetComponent<Image> ().sprite;
hoverObject.name = "Hover";
RectTransform hoverTransform = hoverObject.GetComponent<RectTransform> ();
RectTransform clickedTransform = clicked.GetComponent<RectTransform> ();
hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, clickedTransform.sizeDelta.x);
hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, clickedTransform.sizeDelta.y);
hoverObject.transform.SetParent (GameObject.Find ("Canvas").transform, true);
hoverObject.transform.localScale = from.gameObject.transform.localScale;
}
}
else if (to = null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
if (to != null && from != null) {
Stack<Item> tmpTo = new Stack<Item> (to.Items);
to.AddItems (from.Items);
if (tmpTo.Count == 0) {
from.ClearSlot ();
}
else {
from.AddItems (tmpTo);
}
from.GetComponent<Image> ().color = Color.white;
to = null;
from = null;
hoverObject = null;
}
}
}
The method which is causing the problem is the MoveItem() sadly it is not a nullreference or nullpointer and I simply am out of ideas been strugling with it for a couple of days... Any advice on how to fix this would be helpfull and much welcomed indeed. Thanks in advance!
I haven't taken a long look at your code but right away I saw this issue:
else if (to = null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
This is causing the end location to be set to null. To fix this, change to double equals like so:
else if (to == null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
If this does not solve your problem, let me know and I'll look at your code harder.

How do i limit the amount of objects are instantiated?

I've looked through the code and tried different approaches multiple times, but i just can't seem to get it to work.
It works properly twice, then its stops working properly the third time.
I want 1 object to be instantiated each time, but instead on the third time it spawns 30, which is bad.
I want it to spawn 1 object each time.
So i used this script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attack : MonoBehaviour {
public Transform playerPos = null;
private float playerDist;
private GameObject projectileEnemyClone;
public GameObject projectileEnemyPrefab;
private float kickBack = 10;
private Rigidbody rb;
private int bulletCount = 0;
private bool canshoot = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Shoot()
{
if (canshoot == true)
{
projectileEnemyClone = Instantiate(projectileEnemyPrefab, transform.position, Quaternion.identity) as GameObject;
canshoot = false;
}
}
private void Respawn()
{
canshoot = true; ;
}
private void ShootLeft()
{
Shoot();
projectileEnemyClone.transform.position = new Vector3(transform.position.x - 1, transform.position.y, transform.position.z);
projectileEnemyClone.GetComponent<Rigidbody>().AddForce(transform.right * -10);
kickBack *= -1;
rb.AddForce(transform.right * kickBack);
Destroy(projectileEnemyClone, 1);
if (!canshoot)
{
Invoke("Respawn", 2);
}
}
private void ShootRight()
{
Shoot();
projectileEnemyClone.transform.position = new Vector3(transform.position.x + 1, transform.position.y, transform.position.z);
projectileEnemyClone.GetComponent<Rigidbody>().AddForce(transform.right * 10);
rb.AddForce(transform.right * kickBack);
Destroy(projectileEnemyClone, 1);
Invoke("Respawn", 2);
}
void Update () {
playerDist = playerPos.position.x - transform.position.x;
if (playerDist <= (3) && playerDist >= (-3))
{
if (playerDist < (0))
{
Invoke("ShootLeft", 1);
}
else
{
Invoke("ShootRight", 1);
}
}
}
}
Don't use Invoke(), you should create a timer that controls your Shoot() function.
float shootCooldown = 0.1f;
float shootTimer = 0;
bool justShot = false;
void Update()
{
if(!canShoot)
{
shootTimer += Time.deltaTime;
if(shootTimer >= shootCooldown)
{
shootTimer = 0;
canShoot = true;
}
}
}
void Shoot()
{
if(canShoot)
{
Shoot();
canShoot = false;
}
}

Unity player freezing due to script but without error

My unity player keeps on freezing after a while, I know what script is causing it (if it is indeed a script that is causing it). since there's only one script I've edited when it started freezing. But I can't figure out WHY it is freezing!
Here is the script that is causing it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
//public GameObject allPlayersPrefab;
public GameObject allPlayers;
public Transform playerRed;
public Transform playerGreen;
//public Transform playerPurple;
//public Transform playerYellow;
//Tail redTail;
//Tail greenTail;
//Tail purpleTail;
//Tail yellowTail;
public float secondsBetweenGaps = 2f;
public float secondsToGap = .25f;
public float snakeSpeed = 3f;
public float turnSpeed = 200f;
public int biggerPickupDuration = 3;
public int smallerPickupDuration = 3;
public int speedPickupDuration = 2;
public int invinciblePickupDuration = 3;
public int maxPickups = 3;
public int spawnPickupThreshold = 5;
private GameObject[] currPickups;
public GameObject[] pickupTypes;
public Transform pickupsParent;
public int players = 2;
[HideInInspector]
public int alive;
public bool enableKeys = false;
public GameObject prefabTail;
public GameObject settingsMenu;
public GameObject startingPanel;
public Text scoreText;
public Text radiusText;
public Text speedText;
public Text winText;
private bool hasEnded = false;
[HideInInspector]
public bool playerWon = false;
public bool running;
public Snake[] snakes;
ButtonManager buttonManager;
Pickup[] pickups;
void Start() {
//InstantiateNewPlayers();
playerRed = allPlayers.transform.FindChild("Red");
playerGreen = allPlayers.transform.FindChild("Green");
snakes = allPlayers.GetComponentsInChildren<Snake>(true);
alive = players;
//redTail = playerRed.GetComponentInChildren<Tail>();
//greenTail = playerGreen.GetComponentInChildren<Tail>();
//purpleTail = playerPurple.GetComponentInChildren<Tail>();
//yellowTail = playerYellow.GetComponentInChildren<Tail>();
buttonManager = FindObjectOfType<ButtonManager>();
pickups = FindObjectsOfType<Pickup>();
playerRed.gameObject.SetActive(false);
playerGreen.gameObject.SetActive(false);
//playerPurple.gameObject.SetActive(false);
//playerYellow.gameObject.SetActive(false);
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
void Update() {
if(Input.GetKey(KeyCode.Escape)) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
buttonManager.anima.Play("BackToSettings");
playerWon = true;
ResetGame();
buttonManager.restartButt.gameObject.SetActive(false);
buttonManager.StopAllCoroutines();
buttonManager.countDownText.enabled = false;
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
if(alive == 1 && !hasEnded) {
Transform lastPlayer;
foreach(Snake child in snakes) {
if(!child.dead) {
lastPlayer = child.transform.parent;
if(child.score >= int.Parse(scoreText.text)) {
Win(lastPlayer.name);
AllPlayersDead();
} else
AllPlayersDead();
break;
}
}
}
if(alive == 0) {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
foreach(Snake child in snakes) {
if(child.score >= int.Parse(scoreText.text)) {
AllPlayersDead();
Win(child.transform.parent.name);
}
}
}
public void AllPlayersDead() {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
void Win(string winningPlayer) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
Debug.Log("Win got called");
winText.gameObject.SetActive(true);
winText.enabled = true;
winText.text = winningPlayer + " wins!";
playerWon = true;
running = false;
}
public void PlayerDied() {
foreach(Snake child in snakes) {
if(!child.dead) {
child.score += 1;
}
}
}
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
}
}
}
public void ResetGame() {
Debug.Log("Resetting everything...");
for(int i = 0; i < players; i++) {
Transform currPlayer = allPlayers.transform.GetChild(i);
currPlayer.GetComponentInChildren<Tail>().points.Clear();
currPlayer.GetComponentInChildren<Snake>().dead = false;
currPlayer.GetComponentInChildren<Snake>().invincible = false;
currPlayer.GetComponentInChildren<Snake>().posInformer.position = new Vector3(-20, 0, 0);
if(playerWon) {
currPlayer.GetComponentInChildren<Snake>().score = 0;
playerWon = false;
}
//currPlayer.GetComponentInChildren<LineRenderer>().positionCount = 0;
currPlayer.GetComponentInChildren<LineRenderer>().numPositions = 0;
List<Vector2> list = new List<Vector2>();
list.Add(new Vector2(0, 5));
list.Add(new Vector2(0, 6));
StopAllCoroutines();
for(int i2 = 0; i2 < pickups.Length; i2++) {
pickups[i2].StopAllCoroutines();
}
foreach(Transform pickup in pickupsParent) {
Destroy(pickup.gameObject);
}
currPlayer.GetComponentInChildren<EdgeCollider2D>().points = list.ToArray();
foreach(Transform child in currPlayer) {
if(child.CompareTag("PrefabTail")) {
Destroy(child.gameObject);
}
}
currPlayer.gameObject.SetActive(false);
currPlayer.GetComponentInChildren<Tail>().enabled = true;
Destroy(GameObject.FindWithTag("PrefabTail"));
turnSpeed = int.Parse(radiusText.text) * 10;
snakeSpeed = float.Parse(speedText.text);
alive = players;
hasEnded = false;
running = false;
}
Debug.Log("Resetting done.");
}
}
I do have a small suspection that the freezing has something to do with the SpawnPickups method and/or the part where it destroys the pickups in the ResetGame method.
Thanks!
Your method SpawnPickups is doing this.
When you call this coroutine, and enable is true and running is false, you never reach a "yield" instruction, so your while(enabled) is indeed a while(true)
Coroutines are not threads, they run on the main thread and if you block a coroutine like this one, you are blocking the game.
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
//Here you need some yield in case running is true but you reached maxPickups (this one is not necessary if you put the next one)
}
//Here you need some yield in case running is false
//yield return null; //this should be enough to prevent your game from freezing
}
}

I can not change the state of animation in unity

public class TranslatreDora : MonoBehaviour {
public Vector3 WalkSpeed;
public Animator walkDora_;
public float RunSpeedDora=1.6f;
private Rigidbody DoraRigidBody;
public Vector3 JumpVector;
private bool Jumping_;
public Transform DoraFoot_;
public Vector3 DoraFootRay_;
void Start ()
{
walkDora_.GetComponent<Animator>();
walkDora_.SetFloat("DoraSpeed", 1);
DoraRigidBody = GetComponent<Rigidbody>();
}
if (Input.GetKeyDown(KeyCode.J) || (Input.GetKey(KeyCode.W) && Input.GetKeyDown(KeyCode.J)))
{
Jumping_ = true;
JumpVector = new Vector3(0, 300, 0);
walkDora_.SetBool("Jumping", true);
walkDora_.SetFloat("JumpFloat", 1);
Debug.Log("Jump 1");
DoraRigidBody.AddForce(JumpVector);
Debug.Log("Jump 1 ing");
RayCastTest();
}
Debug.Log("Finished");
}
void RayCastTest()
{
Debug.Log("Entered");
//RayCasting
Vector3 DoraRayTest = new Vector3(DoraFoot_.position.x, DoraFoot_.position.y, DoraFoot_.position.z);
Ray RayDoraDown = new Ray(DoraRayTest, Vector3.down);
Debug.DrawRay(DoraRayTest, Vector3.down, Color.green);
Debug.Log("Entered 2");
RaycastHit RHit;
Debug.Log("Entered 3");
***//HERE This if-statement does not even get executed***
if (Physics.Raycast(DoraRayTest, Vector3.down, 1f))
{
Debug.Log("Not still False");
walkDora_.SetBool("Jumping", false);
Debug.Log("False");
}
Debug.Log("Entered Exit");
}
}
That If statement don't even execute so my Animation gets stuck.
I want the ray cast to only scan the ray if I hit jump and then when the character is near the Ground That If Statement should be executed.