- Home /
can't load a prefab as my GameObject variable
I need to change the projectile type as user clicks a button.
I have used this script but it cannot assign my prefab to "projectile" variable. I even tried `Resources.Load() ` and `GameObject.FindWithTag()` help please!
if (Input.GetButtonDown ("Fire2")) {
if (projectile.transform.name == "cannonball") {
projectile = GameObject.Find("rocket");
}
else {
projectile = GameObject.Find("cannonball");
}
print(projectile.transform.name+ " is selected!");
}
Answer by DoctorWhy · Nov 14, 2012 at 09:03 PM
Try AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(GameObject)) as GameObject;
thanks it worked :) although your short answer made me do a little study about the syntax but it was worth doing it.
Answer by iHaveReturnd · Nov 14, 2012 at 09:11 PM
I believe that .find only works on objects in the hierarchy. So if the prefab doesn't exist in the world it won't be able to find that object.
I hope someone will verify that though.
An easy alternative is to create variables for each projectile type that weapon can use.
var projectile1 : GameObject;
var projectile2 : GameObject;
And drag the prefabs in in the inspector. Then change the projectile that way.
Yes you are right and I did not know the fact that .find can not be used on prefabs. your way works too but It will be a little untidy when lots of projectile types should be used. thanks by the way.
Your answer
![](https://koobas.hobune.stream/wayback/20220613083857im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
prefab is instantiating without a script 2 Answers
Acessing scripts in other game objects with prefabs, without using GameObject.Find 1 Answer
How do I assign a prefab reference to a private variable? 1 Answer
Reinitialize prefab 0 Answers
How to save/load references to components and prefabs 1 Answer