I am making a game where people walk around catching cats then releasing them into a safe spot.
Here’s all the relevant code:
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class PlayerCatching : MonoBehaviour
{
public Text playerScore;
private int playerScoreInt;
public Text catHoldCount;
public List<GameObject> cats;
GameObject tempGameObject;
private int catCount;
private void Start()
{
playerScoreInt = 0;
cats = new List<GameObject>();
playerScore.text = playerScoreInt.ToString();
tempGameObject = null;
catCount = 0;
}
private void Update()
{
playerScore.text = playerScoreInt.ToString();
catHoldCount.text = catCount.ToString();
if (catCount < 0)
{
catCount = 0;
}
if (Input.GetKeyDown(KeyCode.F))
{
if (catCount >= 1)
{
GameObject releaseCat = cats[cats.Count - 1];
Vector3 catReleasePosition = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
GameObject newObject = Instantiate(releaseCat, catReleasePosition, transform.rotation);
newObject.SetActive(true);
catCount--;
Destroy(cats[cats.Count - 1]);
cats.RemoveAt(cats.Count - 1);
}
}
}
private void OnTriggerStay(Collider other)
{
if (Input.GetKey(KeyCode.E) && other.gameObject.CompareTag("Cat") && (catCount < 3))
{
playerScoreInt++;
tempGameObject = Instantiate(other.gameObject);
tempGameObject.SetActive(false);
cats.Add(tempGameObject);
catCount++;
Destroy(other.gameObject);
}
//Debug.Log("Collided with " + other.ToString());
}
}
Thanks in advance for any help
I was able to get the core mechanic of getting the cat and (to some degree) releasing them. However, when the player object releases cats, it sometimes doesn’t release them (note: I checked the inspector and they do instantiate and set themselves to active). For example, I take 3 cats (works every time), then I press “F” 3 times to release 3 cats, but sometimes only 2 release. Another example is that if I press F 3 times, but press them with some delay after each other, all 3 release attempts are successful, but if I press F 3 times really fast, 1 or 2 cats don’t release.
I hope someone can tell me if there’s some weird Unity shenanigans going on.
I am also sure that I am not prematurely deleting the cats when I release them.
Edit:
This function works perfectly when I Build and Run the game. It seems that it only has the inconsistent problem of spawning the cats (exists in inspector, but doesn’t show in the game preview). Could this be because of the code block? :
if (catCount >= 1)
{
GameObject releaseCat = cats[cats.Count - 1];
Vector3 catReleasePosition = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
GameObject newObject = Instantiate(releaseCat, catReleasePosition, transform.rotation);
newObject.SetActive(true);
catCount--;
Destroy(cats[cats.Count - 1]);
cats.RemoveAt(cats.Count - 1);
}
Geeky15 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Cute idea!
First of all, some ideas to simplify and optimise your code:
-
Don’t use a separate variable for
catCount
when you already have theList
‘scats.Count
value. It’s completely redundant and adds a bunch of extra code to sync these values. -
Don’t keep deleting and reinstantiating the cats from the
cats
list. Rather, when a cat is picked up, disable the object and add it to the list. Then when it is put down, activate it and remove it from the list. You already have theGameObject
s instantiated and referenced there. If you really need a reference to all cats at any given time, then do this with a new list (or an array if the total amount doesn’t change) calledallCats
instead. -
I can’t imagine why, in your
OnTriggerStay
method, you’d be creating a new instance of the object you collided with, then disable it, then destroy the original. That makes little to no sense to me. Perhaps don’t do this.
It seems to me that you need to do some research on what it means to instantiate an object. Generally objects are instantiated at load time, then simply activated and deactivated as needed during run time. This method is way more performant and helps alleviate the issue of accidentally creating memory leaks (filling up your RAM with tons of object instances).
This is not as important, especially since you are learning and prototyping, but try to extract things into methods where you can. You could put the code for picking up and dropping cats into PickupCat(GameObject cat)
and DropCat()
methods. This really improves the readability and reusability of your code.
So, refactoring your code based on the sugestions (plus a few extra touches):
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerCatching : MonoBehaviour
{
public Text playerScore;
private int playerScoreInt;
public Text catHoldCount;
public List<GameObject> cats;
private const int maxHeldCats = 3;
private void Start()
{
playerScoreInt = 0;
cats = new List<GameObject>();
playerScore.text = playerScoreInt.ToString();
}
private void Update()
{
playerScore.text = playerScoreInt.ToString();
catHoldCount.text = cats.Count.ToString();
if (Input.GetKeyDown(KeyCode.F))
{
DropCat();
}
}
private void OnTriggerStay(Collider other)
{
if (Input.GetKeyDown(KeyCode.E) && other.gameObject.CompareTag("Cat"))
{
PickupCat(other.gameObject);
}
}
private void PickupCat(GameObject cat)
{
if (cats.Count >= maxHeldCats)
return;
playerScoreInt++;
cat.SetActive(false);
cats.Add(cat);
}
private void DropCat()
{
if (cats.Count <= 0)
return;
GameObject releaseCat = cats[cats.Count - 1];
Vector3 catReleasePosition = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
releaseCat.transform.position = catReleasePosition;
releaseCat.SetActive(true);
cats.remove(releaseCat);
}
}
Note that I changed the input for E
to GetKeyDown
instead of GetKey
. I also added a constant for the maxHeldCats
to replace your hardcoded value. You also had unnecessary using
directives.
That should not only simplify reading the code, but also the execution, because now your PC doesn’t have to create and destroy objects the whole time, it just manipulates what is already there.
As a final note, I would recommend the variable names be changes to something clearer:
Text playerScoreText;
int playerScore;
Text catHoldCountText;
List<GameObject> heldCats;
I hope this helps. Let me know if and how this works for you please!
3