- Home /
The question is answered, right answer was accepted
Add Item To A List Of Classes
I have a List of classes, which stores info for my weapons when i switch them. I want 9 spaces for having weapons so the rest have to be filled with an icon, and and empty gameobject. how do I add an item to it in script?
using System.Collections;
using System.Collections.Generic;
public class WeaponSwitching : MonoBehaviour {
public List weapons = new List();
[System.Serializable]
public class WeaponList
{
public GameObject weapon;
public Texture2D icon;
public string name;
}
public int curWeapon;
public Texture2D iconSelect;
public bool allowName = true;
public int maxItems = 9;
public Texture2D noneIcon;
public GameObject None;
void Start ()
{
if(curWeapon > weapons.Count)
{
curWeapon = 0;
}
if(weapons.Count < 9)
{
weapons.AddRange{None, noneIcon, ""};__This is where i need it to be added__
}
weapons[curWeapon].weapon.SetActive(true);
}
void Update ()
{
float scroll = Input.GetAxis ("Mouse ScrollWheel");
//Up
if(scroll > 0)
{
weapons[curWeapon].weapon.SetActive(false);
curWeapon ++;
if(curWeapon >= weapons.Count)
{
curWeapon = 0;
}
weapons[curWeapon].weapon.SetActive(true);
}
//Down
if(scroll < 0)
{
weapons[curWeapon].weapon.SetActive(false);
curWeapon --;
if(curWeapon < 0)
{
curWeapon = weapons.Count - 1;
}
weapons[curWeapon].weapon.SetActive(true);
}
}
void OnGUI()
{
if(allowName == true)
{
GUI.Label(new Rect(32, Screen.height - 96, 128, 128), weapons[curWeapon].name);
}
for(int i = 0; i < maxItems; i ++)
{
GUI.DrawTexture(new Rect(64 * i + 16, 16, 64, 64), weapons[i].icon);
}
GUI.DrawTexture(new Rect(64 * curWeapon + 16, 16, 64, 64), iconSelect);
}
}
It looks to me that you are thinking about your "WeaponList" class in the wrong way. I think I would call that class "WeaponInfo", because it holds all the information you need about a weapon.
In line 26 it looks like you are trying to add a list to your weapons variable (that's what AddRange does), but in reality you just want to add a single object multiple times. So:
WeaponList emptyWeapon = new Weapon();
emptyWeapon.icon = noneIcon;
emptyWeapon.name = "";
for (int i = weapons.Count; i < 9; i++){
weapons.Add(emptyWeapon);
}
This fills up your remaining slots with empty weapons. I kept your class name, but it might also be a good idea to define a constructor to simply the code a bit.
Follow this Question
Related Questions
Trouble with Add-ing and Retrieving from a List of Custom Class 1 Answer
UNITYSCRIPT - Class's and Instances - Functions/Methods - Correct Usage 0 Answers
How to search a certain variable in a list of a created class (C#) 1 Answer
Trying to make a simple quest system, but i stuck how to do 0 Answers
Save an array with custom classes 1 Answer