- Home /
How to select the Nth gameObject in a list and put it into a gameObject variable
I'm trying to put a check in my game where it disables everything that doesn't have the same ID as the index. This is the system I have set up:
void WeaponSelect() {
selector = Input.GetAxis ("Scroll");
index += selector;
if (index > weapons) {
index = 1;
}if (index < 1) {
index = weapons;
}
check += 1;
checkedObject = weaponList[check];
if (checkedObject.GetComponent<WeaponID> ().ID == index) {
checkedObject.GetComponent<WeaponID> ().onabled = true;
} else {
checkedObject.GetComponent<WeaponID> ().onabled = false;
}
if (check > weapons) {
check = 1;
}
}
but this gives off this error:
error CS1502: The best overloaded method match for `System.Collections.Generic.List<UnityEngine.GameObject>.this[int]' has some invalid arguments
and
error CS1503: Argument `#1' cannot convert `float' expression to type `int'
If this isn't the right way to do this, what is? Can anybody please help?
Can you include the variable declarations so we can see the types you have?
Answer by gameplay4all · Feb 22, 2017 at 07:18 PM
You want something like this:
List<GameObject> weaponList = new List<GameObject>();
float scrollTracker;
float scrollSensitivity = 3.0f;
int weaponIndex;
GameObject selectedWeapon = 0;
void Update(){
scrollTracker += Input.GetAxis("Scroll") * scrollSensitivity * Time.deltaTime;
scrollTracker = Mathf.Clamp(scrollTracker, 0, weaponList.Count - 1);
weaponIndex = (int)Mathf.Round(scrollTracker);
selectedWeapon = weaponList[weaponIndex];
}
Lists use indices, which are ints. But GetAxis
returns a float, so let's say you have the index 2 and GetAxis
returns 0.6f. Then the resulting index would be 2.6f, which is still 2 when it is converted to an int. So that why you need to use a float value to keep track of the scrolling. Hope this helps, please take a look at my example code and try to understand it :)
Good luck! -Gameplay4all
Based on the errors you are getting, Im assu$$anonymous$$g your variable check
is a float. If that is true you could be attempting to get an index from your list of like 1.56f which is not an index you can grab. Try casting it as a int and it should fix your problem.
checkedObject = weaponList[(int)check];
If this isn't the issue then you'll have to provide the entire script so I can look at it :).
How would I disable everything that Isnt selectedWeapon?
Thanks for the help :D