- Home /
Select Object ( Weapon ) Quick! Help! xD
Hi guys :D, how i make to i can change the SelectWeapon to for example "SelectObject ("M4A1")" ?, My script:
function Start () { SelectWeapon(0); }
function Update () { // Did the user press fire? if (Input.GetKeyDown("1")) { SelectWeapon(0); }
else if (Input.GetKeyDown("2")) { SelectWeapon(1); } }
function SelectWeapon (index : int) { for (var i = 0; i < transform.childCount; i++) { // Activate the selected weapon if (i == index) transform.GetChild(i).gameObject.SetActiveRecursively(true); // Deactivate all other weapons else transform.GetChild(i).gameObject.SetActiveRecursively(false); } } Thanks.
Answer by aldonaletto · Nov 25, 2011 at 12:16 AM
Supposing you want to select the weapon by name, the code below can do the job. It's basically the same thing, but more optimized: check all weapons childed to this object and compare its name to the name specified, using the boolean result to set active true or false:
function SelectWeapon (weaponName: String){ // check all weapons childed to transform for (var weapon in transform){ // only the weapon with the specified name will be activated: weapon.gameObject.SetActiveRecursively(weapon.name == weaponName); } }
Dear God, what a noob mistake! Shame on me! Thanks for the warning, @$$anonymous$$arsallima - I fixed this asha$$anonymous$$g error.
xDDD but how i make to turn SelectWeapon(1); to a name of object? i try SelectWeapon( Weapon$$anonymous$$4A1 (Is this name of the object) ); and not work :/ ( Sorry for my english xD )
That's how you use this function!
SelectWeapon("Weapon$$anonymous$$4A1");
will select the object specifically named Weapon$$anonymous$$4A1.
Personally I don't think this is a very good way to do this, but it does what you asked for.
As usual, @syclamoth is right (I can't count how many times I wrote this!): you must pass the weapon name as a String, with the enclosing quotes.