beloto
1
example:
I have a script that instantiate a weapon.
function SetWeapon(weaponType:GameObject){
var clone = Instantiate (weaponType, transform.position, transform.rotation);
}
How can i pass prefab in SetWeapon();
or if i have something like this:
var weapon:GameObject;
function SetWeapon(){
var clone = Instantiate (weapon, transform.position, transform.rotation);
}
I know how to assign prefab from inspector, but how to change it from runtime.
And if it is possible I like to avoid my weapons siting in the scene and setting weapon variable by gameObject.Find();
Thanks in advance :P
duck
2
You can do this by making use of the Resources Folder.
From the example on the Resources.Load scripting reference:
// Instantiates a prefab at the path "Assets/Resources/enemy".
function Start () {
var instance : GameObject = Instantiate(Resources.Load("enemy"));
}
However
Why do you want to do this?
It might be a good idea if you stated your broader goal - why you want to avoid prefab references - because it might help someone give a more helpful answer.
There are many reasons why prefab references are a good way to organise your project, and trying to bypass the way Unity is designed to work is generally not a good idea unless you have a specific reason that warrants it.
beloto
3
//just drop this script in button that you want to act like weapon changer
//use this var in inspector to set the parent of the weapon (drag and drop)
var weaponParent:GameObject;
//use this var in the inspector to set the weapon to be instanced
var weaponToSet:GameObject;
//set this one in the inspector for the keyboard shortcut (default 0)
var shortcut:String="0";
//tag weapons with weapon tag to get cleaned by this function
function RemoveOldWeapon (){
var weapons : GameObject[];
weapons = GameObject.FindGameObjectsWithTag("weapon");
if(weapons.length > 0){
for (var wep: GameObject in weapons) {
Destroy(wep);
}
}
}
//function that instantiate the weapon
function SetWeapon (){
var clone = Instantiate (weaponToSet, weaponParent.transform.position, weaponParent.transform.rotation);
clone.transform.parent = weaponParent.transform;
}
//function that use mouse klick to swap the weapon
function OnMouseDown (){
RemoveOldWeapon();
SetWeapon();
}
function Update (){
//function that use keyboard shortcut to swap the weapon
if (Input.GetKeyDown (shortcut)){
RemoveOldWeapon();
SetWeapon();
}
}
here is the solution that i make when i rethink the problem.
Big thanks to Duck for helping me come with this solution.