Unity 3D: Instantiating an object after setting it into a list isn’t consistent

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);
        }

New contributor

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:

  1. Don’t use a separate variable for catCount when you already have the List‘s cats.Count value. It’s completely redundant and adds a bunch of extra code to sync these values.

  2. 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 the GameObjects 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) called allCats instead.

  3. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật