Loot System that load items from resource folder to array
Hello everyone.
I'm fiddling with a loot system kinda like Dayz, but dumbed down. In short, I have an empty gameobject called "SpawnFood" as a prefab and I want to be able to just place it around my map and make it spawn a random item from an array. I want it to spawn an item when the player gets within a certain distance and only if there is not an item there already. Also I'm trying to make it despawn the item after a certain time if the player does not pick it up.
This is what I got so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LootManager : MonoBehaviour
{
public GameObject[] foodItem;
public Transform spawnPoint;
public bool isSpawnable = true;
private GameObject player;
public float distance;
public float respawnTimer = 1.0f;
public float despawnTimer = 1.0f;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
foodItem = Resources.LoadAll("Fooditems") as GameObject[];
}
void Update()
{
int foodItem_num = Random.Range(0, foodItem.Length);
distance = Vector3.Distance(transform.position, player.transform.position);
if (distance <= 5.0f && isSpawnable == true && respawnTimer <= 0)
{
Instantiate(foodItem[foodItem_num], spawnPoint.position, spawnPoint.rotation);
foodItem[foodItem_num].transform.SetParent(spawnPoint);
Debug.Log("Spawning Item");
isSpawnable = false;
}
else
{
return;
}
if (isSpawnable == false)
{
despawnTimer -= Time.time;
if (despawnTimer <= 0.0f)
{
if (transform.childCount > 0)
{
Transform child = transform.GetChild(0);
child.parent = null;
Destroy(child.gameObject);
}
}
}
}
}
I get 2 errors with this code. An "Array Index is out of range", which points me to this line:
foodItem[foodItem_num].transform.SetParent(spawnPoint);
and an "Object reference not set to an instance of an object", which points me to this;
Instantiate(foodItem[foodItem_num], spawnPoint.position, spawnPoint.rotation);
Can anyone tell me what I'm doing wrong? When I press play, the items that I've put in the fooditem array in the inspector disappears and its size is set to 0.
Answer by Laseph · Apr 14, 2017 at 12:11 PM
You are setting foodItem array in the start method, could it be that there's something wrong with loading the resources, the wrong path or something, and that's why foodItem has no elements. That would also explain your errors. It's out of bounds because the array length is zero and there are no objects in the array.
I checked the path. The prefabs are located in an "FoodItems" folder within the Resource folder. Do I need a "/" before or after the foldername?
No, that should be good. $$anonymous$$aybe try this ins$$anonymous$$d in start.
foodItem = Resources.LoadAll("Fooditems").Cast<GameObject>().ToArray();
You will also need to add this namespace for it to work.
using System.Linq;
Your answer
