C# Instantiate problem

Newbie instantiate question…

I have a prefab (MyPrefab) which has the following C# script attached to it;

public class MyPrefab : MonoBehaviour {
int mA;

void Start () {
}
void Update () {
}
public void SetA(val) {
mA = val;
}
}

Another script is being used to generate MyPrefab game objects using instantiate;

MyPrefab test = Instantiate(Resources.Load(“MyPrefab”));
test.SetA(10);

The problem i have is that the code above fails as Instantiate returns an Object and cannot be cast to a ‘MyPrefab’. If i make test an Object type everything works fine and my object is instantiated. But i cannot call the SetA method.

Any help would be appreciated. Thanks.

GameObject go = Instantiate(Resources.Load("MyPrefab")) as GameObject;
MyPrefab test = go.GetComponent("MyPrefab") as MyPrefab;

I’m trying to instantiate a prefab like this, but I’m not sure how to reference the name/path? I want to do this programmatically, not by dragging a reference to a variable in the editor.

For instance, I want to instantiate a bush from the terrain assets pack. I tried Resources.Load(“Bush1”) and Resources.Load(“Terrain Assets/Bushes/Bush1”) but neither seemed to work. I know this is a total noob error. Sorry. :slight_smile:

I couldn’t find an example of how to reference a nested asset in the docs or wiki, and searching the forums gave me tons of irrelevant results.

thecreatrix,

I managed to get this working by creating a directory called Resources under assets and placing my prefab in that directory. Hope that helps.

Thanks rom, i’ll give this a try. Is this in the documentation anywhere? I thought i’d checked all the Instantiate docs but must have missed this.

Ah, thank you! It worked.

Likewise,

Had the same problem and now it works thank you Rom :slight_smile: