MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. ObjectPooler.GetPooledObject () (at Assets/Scripts/ObjectPooler.cs:31) PlatformGenerator.Update () (at Assets/Scripts/PlatformGenerator.cs:57)
PlatformGenerator
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformGenerator : MonoBehaviour
{
public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;
private float platformWidth;
public float distanceBetweenMin;
public float distanceBetweenMax;
//public GameObject[] thePlatforms;
private int platformSelector;
private float[] platformWidths;
public ObjectPooler[] theObjectPools;
//public GameObject[] thePlatforms;
// Start is called before the first frame update
void Start()
{
//platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;
//to search which of the platform has BC2D with sz
platformWidths = new float[theObjectPools.Length];
for(int i = 0; i < theObjectPools.Length; i++)
{
platformWidths[i] = theObjectPools[i].pooledObject.GetComponent<BoxCollider2D>().size.x;
}
}
// Update is called once per frame
void Update()
{
if (transform.position.x < generationPoint.position.x)
{
distanceBetween = Random.Range (distanceBetweenMin, distanceBetweenMax);
platformSelector = Random.Range(0, theObjectPools.Length);
transform.position = new Vector3 (transform.position.x + (platformWidths[platformSelector] / 2) + distanceBetween, transform.position.y, transform.position.z);
//Instantiate(/* thePlatform */ thePlatforms[platformSelector], transform.position, transform.rotation);
GameObject newPlatform = theObjectPools[platformSelector].GetPooledObject();
newPlatform.transform.position = transform.position;
newPlatform.transform.rotation = transform.rotation;
newPlatform.SetActive(true);
transform.position = new Vector3(transform.position.x + (platformWidths[platformSelector] / 2), transform.position.y, transform.position.z);
}
}
}
ObjectPooler
using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class ObjectPooler : MonoBehaviour { public GameObject pooledObject;
public int pooledAmount;
List<GameObject> pooledObjects;
// Start is called before the first frame update
void Start()
{
pooledObjects = new List<GameObject>();
for(int i = 0; i < pooledAmount; i++)
{
//casting mtd
GameObject obj = (GameObject) Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
return obj;
}
}