Hi all, I have a simple script here where when the player purchases an item it should get added to their inventory array. The problem is I am getting an error saying "Method not found ‘UnityEngine.GameObject.op_Addition’.
Here is my code:
function OnGUI() {
if(GUI.Button(Rect(40,40,50,50),"Used Iron Dagger")){
if(GameObject.FindGameObjectWithTag("Player").GetComponent("Inventory").gold >= 23)
GameObject.FindGameObjectWithTag("Player").GetComponent("Inventory").InventoryArray += [used_iron_dagger]; <<Error Occurs Here
}
}
And the script holding the array looks like this:
var gold : int = 9999;
var InventoryArray : GameObject[];
function Update () {
}
Can someone help point out what I’m doing wrong? Thank you!
You can’t add items to built-in arrays; use List instead. However, “+=” isn’t a valid way to add an item to a List either, you need to use a function such as Add. Also don’t use quotes in GetComponent.
You logic is good, but your way of doing it is a bit flawed.
First what is "used_iron_dagger? It has to be a type of GameObject before you can add it to a array with the type of GameObject.
Secondly when adding a object to a array using Array.Add would make good results.
I hope I gave you some pointers, however if you’re still having problems just say so.
Unity is complaining that there’s no + operator applicable to a GameObject array - and indeed this doesn’t exist.
What are you trying to do? Increment the quantity of used_iron_dagger items in the inventory? Or is the used_iron_dagger a GameObject and you want to add it to the GameObject array InventoryList?
I think you could use instead a very common inventory approach: create a structure where each element is an int that shows how many units of each item the owner has (including the gold), like this:
// define the structure InventoryList
class InventoryList {
var Gold: int;
var UsedIronDagger: int;
var Armour: int;
// function to create and initialize a InventoryList variable
function InventoryList(gold: int, daggers: int, armour: int){
this.Gold = gold;
this.UsedIronDagger = daggers;
this.Armour = armour;
}
}
// create the inventoryList variable:
var inventoryList: InventoryList = new InventoryList(9999, 0, 50);
private var playerInventory: InventoryList; // reference to the inventory
// Find functions are too slow: get a reference to the inventory at Start:
function Start(){
var player = GameObject.FindWithTag("Player");
playerInventory = player.GetComponent(Inventory).inventoryList;
}
function OnGUI() {
if (GUI.Button(Rect(40,40,200,50),"Used Iron Dagger")){
if (playerInventory.Gold >= 23){
playerInventory.UsedIronDagger += 1; // increment item count
playerInventory.Gold -= 23; // spend the gold
}
}
}