Reputation: 80
I am working on a "Shoot a ball into bin" game. I am trying to get a prefab object (via inspector) then instantiate it but then stumbled upon this problem when the inspector doesn't show a prefab option to input the prefab GameObject even though this code:
[System.Serializable]
public class Obj
{
public GameObject prefab;
}
Should do just that.
Full code:
public class MouseLook : MonoBehaviour
{
[System.Serializable]
public class Obj
{
public GameObject prefab; // Get Prefab from Inspector
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Obj obj = new Obj();
Instantiate(obj.prefab, playerBody); // playerbody is a Transform
}
}
}
If anyone has a solution to this problem, please tell me.
It will be very helpful :)
Upvotes: 1
Views: 247
Reputation: 90659
I'm pretty sure this is not the Full code
.. otherwise it wouldn't even compile ;)
As it stands
You defined a class, yes, but I don't see any field in your class actually using your type!
It should probably be e.g.
public class MouseLook : MonoBehaviour
{
[System.Serializable]
public class Obj
{
public GameObject prefab;
}
public Obj obj;
// Or also
//[SerializeField] private Obj obj;
// Wherever you get this from
Transform playerBody;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(obj.prefab, playerBody);
}
}
}
In particular note that if you do
Obj obj = new Obj();
inside this just newly created Obj
Instance the prefab
would of course be unassigned.
My question would be though: Is this really all your Obj
class does? Because in such case why not rather simply have
public class MouseLook : MonoBehaviour
{
public GameObject prefab;
// Or also
//[SerializeField] private GameObject prefab;
// Wherever you get this from
Transform playerBody;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(prefab, playerBody);
}
}
}
Upvotes: 1