- Home /
Instantiate Returning null
Here is the code:
using UnityEngine;
using System.Collections;
public class BuildManager : MonoBehaviour {
public Transform CurrentPartPrefab;
private GameObject CurrentPart;
private bool haveObject = false;
private Vector3 mouseWorldPostion;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
mouseWorldPostion = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPostion.z = 0;
if(Input.GetMouseButton(0))
{
if(haveObject == false)
{
CurrentPart = Instantiate(CurrentPartPrefab, mouseWorldPostion , gameObject.transform.rotation) as GameObject;
Debug.Log(CurrentPart);
haveObject = true;
}
else{
//CurrentPart.transform.position = mouseWorldPostion;
}
}
}
}
but CurrentPart even after the instantiate is called is null? I have tried casting it this way:
CurrentPart = (GameObject)Instantiate(CurrentPartPrefab, mouseWorldPostion , gameObject.transform.rotation);
It just trows a runtime error. Does an one know what is wrong here?
Answer by Loius · Apr 08, 2014 at 05:44 PM
Your CurrentPartPrefab is a Transform, you have to cast to Transform instead of GameObject.
The return of the Instantiate is not going to CurrentPartPrefab it is going to CurrentPart which is a game object.
((Transform)Instantiate(whatever)).gameObject
Instantiate is returning an object which is a Transform and is not a GameObject.
Your answer
![](https://koobas.hobune.stream/wayback/20220613142241im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Animation Error "Null reference exception"? 2 Answers
c# 2D array error: need Help! 1 Answer
Resources.Load texture problem 1 Answer
Fresh installed , with problems 0 Answers
Passing information error 0 Answers