Question by
ThadeuMelo · Nov 16, 2016 at 03:48 AM ·
c#gameobjectrandom
Randonly Losing reference to GameObject from prefab
This seems like a weird situation.
My respawn code are working fine for large numbers of entities, but after a wily if the player start eating some of the food the reference to my prefab becames null and I cant instantciate it any more.
using UnityEngine;
using System.Collections;
using UnityEditor;
public class FoodRespawn : MonoBehaviour
{
public GameObject Player;
public string AssetName;
public float spawnRadius = 100; //Distance from de center, usualy the player
public float spawnTime = 3f;
public int maxSpawn = 3;
public int Spawn_count = 0;
private SpriteRenderer spriteRenderer;
private GameObject SpawnType;
void Awake()
{
string assetPath = "Assets/Prefabs/" + AssetName + ".prefab";
SpawnType = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) as GameObject;
spriteRenderer = GetComponent<SpriteRenderer>();
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Start()
{
if (SpawnType == null)
{
print("Spawn Type NULL");
}
//Update is called every frame
}
void Update()
{
}
void Spawn()
{
if (maxSpawn >= Spawn_count)
{
//int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Vector3 randomPosition = Random.insideUnitSphere * spawnRadius + Player.transform.position;
randomPosition.z = 0;
this.transform.position = randomPosition;
if (SpawnType != null)
{
Instantiate(SpawnType, randomPosition,
Player.transform.rotation);
Spawn_count++;
}
else
{
print("Spawn Type NULL");
}
}
}
}
I couldn´t find an exactly patter only that then the player eats too many too fast (but this dont happens if there are many - more than 1000)
Comment
Answer by ThadeuMelo · Nov 16, 2016 at 04:11 AM
When the food item colides with the player it decrements the public player count from foodRespawn and destroys itself.