user4589444
user4589444

Reputation:

Unity3D RawImage(UI) Instantiate

When I am instantiating prefab as GameObject there is no problem. But when instantiating prefab as RawImage there is NullReferenceException problem. (Prefab is RawImage if you need to know)

This is my code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Insstantia : MonoBehaviour
{
    public GameObject img;

    public void Instan()
    {
        RawImage[] myObject = new RawImage[8];
        RectTransform[] rt = new RectTransform[8];

        for (int i = 0; i < 8; i++)
        {
            myObject[i] = Instantiate(img, new Vector3(800 * i, 0, 0), Quaternion.identity) as RawImage;
            rt[i] = myObject[i].GetComponent<RectTransform>();
            myObject[i].transform.SetParent(gameObject.transform, false);

            rt[i].anchorMin = new Vector2(0.05875f, 0);
            rt[i].anchorMax = new Vector2(0.94375f, 1);
        }
    }
 }

Upvotes: 1

Views: 2376

Answers (2)

MX D
MX D

Reputation: 2485

Your issue is that you are trying to convert a GameObject into a Component. The instantiate command will create a GameObject for you, which in this case is your prefab with a component attached to it.

To fix this issue, you would just have to store the GameObject instead of the component, and if you were to need the RawImage component, obtain it in the same way as your RectTransform.

public GameObject[] myObject = new GameObject[8];

instead of

public RawImage[] myObject = new RawImage[8];

(and don't forget to change your conversion call from as RawImage To as GameObject)

If you are referring to a Actual Image, and not the component. You might want to take a look at Resources.Load Instead of using Instantiate.

Upvotes: 0

Christopher G
Christopher G

Reputation: 11

This is because you are casting your GameObject prefab to a component type (RawImage) which is possible because the Component type inherits from the Object type.

So when you try to get a Component for example on this line:

rt[i] = myObject[i].GetComponent<RectTransform>();

A NullReferenceExceptiion is thrown because "img" gameObject has been cast to a Component type object and therefore the RectTransform Component does not exist.

Try changing your public GameObject img field to:

public RawImage img;

Upvotes: 1

Related Questions