Issues to be aware of when instantiate a prefab in unity

Source: Internet
Author: User

when you call the instantiate () method to create an object using prefab, the variable type that receives the instantiate () method return value must be the same as the type that declares the prefab variable, otherwise the value of the receive variable is null.For example, I define in the script:
 Public Gameobject Myprefab;
So when using this myprefab to do instantiate (), the type of the receive return value variable must also be Gameobject, as follows:
 as Gameobject;

Note that instantiate () behind the as is also gameobject.

Another example of our prefab type is our custom UserObject,

 Public UserObject Prefab;

So when using instantiate () We need to write:

 as UserObject;

One of the more easily made mistakes is that the types we declare are:

 Public Gameobject Myprefab;

In the instantiate () return value you want to use transform, as follows:

 as Transform;

This time there will be a problem with newobject null.

This question seems to be very strange, but also brought me some trouble, and then after the search and their own experiments to prove the above conclusions, hope to see this article friends can avoid this problem.

The specific cause of the problem is not very clear, perhaps some of the features of the C # language, and I have just contacted C # not long, if after the understanding will be added below this article.

Issues to be aware of when instantiate a prefab in unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.