- Home /
Assigning script to a variable with a variable
So the title is a bit weird but i didnt know how to call it.
I am working on a FPS game and I am trying to make a simple weaponsystem. Every Player can have a primary and a secondary weapon. I am at the moment trying to write a script to change between the assigned primary/secondary weapons.
So at first I am doing this:
var primary : GameObject;
var secondary : GameObject;
So I have some GUI Buttons that when they get clicked they assign the desired weapon to the variables primary/secondary.
An code example:
function assignump45() {
primary = ump;
}
Now I want to write a function to switch between the primary and secondary weapon. So I tried this:
function switchtoprimary(){
if(Input.GetKeyDown("2")){
primary.inv(); //makes the primary weapon invisible
secondary.vis(); //makes the primary weapon visible
}
}
Of course I get this error:
BCE0019: 'inv' is not a member of 'UnityEngine.GameObject'.
I know that what I wrote is wrong. So I tried to get the script of the primary/secondary weapons so I can disable/activate them:
var primscipt : umpscript = GameObject.Find(ump).GetComponent(umpscript);
This works BUT I can´t write for every weapon this kind of script because I then I need to write several combinations of switching between the weapons and that isn´t possible because i know there is a better solution..
I can´t do a if clause and then assign the primscript because the variable only would be assigned in the if clause..
What I need is something like this (doesn´t work of course^^).
var primscipt : primaryscriptstring = GameObject.Find(primarystring).GetComponent(primaryscriptstring);
So I could assign the variable primaryscriptstring with "umpscript" for example. the variable primarystring does work in this case
Are there any workarounds? I am pretty desperate at the moment :/
Answer by siaran · Mar 15, 2015 at 08:44 PM
I think you're overthinking this. Why not something simple like
//put all weapon gameobjects in this array
GameObject[] weapons;
//pointer to currently active weapon
int activeWeaponIndex;
void SwitchToWeapon(int newWeaponIndex){
weapons[activeWeaponIndex].SetActive(false);
activeWeaponIndex = newWeaponIndex;
weapons[activeWeaponIndex].SetActive(true);
}
If you need to access more of your weapon's functionality, make a Weapon[] instead of a GameObject[], then you could do things like weapons[i].SomeWeaponFunction();
Your answer
Follow this Question
Related Questions
Functions overwrite or work seperatelly ? 1 Answer
How to declare typed array in UnityScript 1 Answer
My script seems fine, yet I keep getting BCE0044: expecting }, found ''. 1 Answer
How to I play an animation using the Animation Element Array via Script? 0 Answers
BCE0053: Property 'UnityEngine.Component.light' is read only. 1 Answer