- Home /
Switching weapons/tools using a GameObject array
Hi there!
Can I use "var guns : GameObject[]" to switch between guns? :) If I can, how? xD Thanks for helping me ^^
Answer by Griffo · Jul 27, 2012 at 07:30 PM
#pragma strict
var EmptyInScene : GameObject;
var weapons : GameObject[] = new GameObject[4]; // Array of Weapons
private var curWeapon : GameObject;
function Start () {
}
function Update () {
if (Input.GetKeyDown("1")) ChangeWeapon(0);
if (Input.GetKeyDown("2")) ChangeWeapon(1);
if (Input.GetKeyDown("3")) ChangeWeapon(2);
if (Input.GetKeyDown("4")) ChangeWeapon(3);
}
function ChangeWeapon(weapon:int){
if(curWeapon){
Destroy(curWeapon);
}
var NewObject : GameObject = Instantiate(weapons[weapon], transform.position, transform.rotation);
NewObject.transform.parent = EmptyInScene.transform;
}
Answer by Piflik · Jul 26, 2012 at 06:36 PM
You can. Create your weapons array, assign the weapons via the Inspector (or any other means you like) and then get your information from the array when you display or fire the current weapon.
If you know how to use arrays, you know how to get it. If you don't know, learn how to use arrays. The Script Reference would be a good start.
Your answer
Follow this Question
Related Questions
Assign a 'Transform' target to prefab by finding a 'GameObject' 1 Answer
Unity Crashes when C# script with code inside class but outside function is added to a GameObject 1 Answer
Acessing scripts in other game objects with prefabs, without using GameObject.Find 1 Answer
How to destroy gun bullet clone? 1 Answer