I have two scrips
public class ItemManager : MonoBehaviour
{
public Weapon[] WeaponList = new Weapon[2];
public Weapon weapon;
void Start()
{
for(int i = 0; i < WeaponList.Length; i++)
{
int rnd = Random.Range(0, WeaponList.Length);
weapon = WeaponList[rnd];
WeaponList[rnd] = WeaponList[i];
WeaponList[i] = weapon;
}
}
}
and
public class WeaponPickUp : MonoBehaviour
{
public Weapon item;
private ItemManager itemmanager;
private static int i = 0;
public int poop;
void Start()
{
itemmanager = GetComponent<ItemManager>();
}
void OnTriggerEnter2D (Collider2D hitInfo)
{
if (hitInfo.gameObject.tag == "Player")
{
item = itemmanager.WeaponList[i];
i++;
PickUp();
}
}
void PickUp()
{
Debug.Log("Picking up " + item.name);
Inventory.instance.Add(item);
Destroy(gameObject);
}
}
the first script holds an array of weapons and shuffles the order of them. The second script then sets the value of Weapon item to a weapon in the array. However when it gets to line item = itemmanager.WeaponList*; it gives me the error Object reference not set to an instance of an object*
I find it very difficult to believe that your ItemManager script is attached to the same GameObject as your WeaponPickup script. That’s the only way that this code would work properly:
itemmanager = GetComponent<ItemManager>();
Since they’re not attached to the same GameObject, this code will simply set your variable to null, resulting in the error you are seeing.
Are you simply ignoring my posts explaining how to fix this and then making fresh duplicate posts?
https://discussions.unity.com/t/836004/2
You absolutely need to understand how to fix these errors. It’s like learning how to eat. If you can’t fix this kind of a trivial everyday super-common error, you are not going to get very far.
I’ll re-include the blurb here just so you can fix your problem. Unfortunately, there IS NO OTHER WAY than to do these following steps. That’s the ONLY way.
The answer is always the same… ALWAYS. It is the single most common error ever.
Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!
Some notes on how to fix a NullReferenceException error in Unity3D
- also known as: Unassigned Reference Exception
- also known as: Missing Reference Exception
- also known as: Object reference not set to an instance of an object
http://plbm.com/?p=221
The basic steps outlined above are:
- Identify what is null
- Identify why it is null
- Fix that.
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
This is the kind of mindset and thinking process you need to bring to this problem:
https://discussions.unity.com/t/814091/4
Step by step, break it down, find the problem.
1 Like
In his defense, from the timestamps it looks like he was making duplicates before anyone responded 