Add Image component to new gameobject

2020-05-04 18:02发布

问题:

I created a new game object:

GameObject newObject = new GameObject("ObjectName");
newObject.AddComponent<RectTransform>();
newObject.GetComponent<RectTransform>().sizeDelta = new Vector2(width, height);

I'm looking for a way to add an image (script) for color purposes. How can I do it?

回答1:

The same way you are adding RectTransform.

newObject.AddComponent<Image>();

You also need to add using UnityEngine.UI to be able to find the Image component.



回答2:

This adds the Image component to your GameObject:

newObject.AddComponent<Image>();

More things has to be done in order for the Image component to show:

1.Create a Canvas. The includes creating the GameObject that will hold the Canvas then attach Canvas component to it. You also have to attach other important UI components such as CanvasScaler and GraphicRaycaster to the Canvas.

2.Create your Image GameObject with your new GameObject("ObjectName"); then call newObject.AddComponent<Image>(); to attach Image component to that GameObject.

3.Make that Image GameObject a child of the Canvas.

This is the whole process of creating a Canvas and an Image as the child:

void Start()
{
    //Create Canvas
    GameObject canvas = createCanvas(false);

    //Create your Image GameObject
    GameObject newObject = new GameObject("ObjectName");

    //Make the GameObject child of the Canvas
    newObject.transform.SetParent(canvas.transform);

    //Add Image Component to it(This will add RectTransform as-well)
    newObject.AddComponent<Image>();

    //Center Image to screen
    newObject.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
}



//Creates Hidden GameObject and attaches Canvas component to it
private GameObject createCanvas(bool hide)
{
    //Create Canvas GameObject
    GameObject tempCanvas = new GameObject("Canvas");
    if (hide)
    {
        tempCanvas.hideFlags = HideFlags.HideAndDontSave;
    }

    //Create and Add Canvas Component
    Canvas cnvs = tempCanvas.AddComponent<Canvas>();
    cnvs.renderMode = RenderMode.ScreenSpaceOverlay;
    cnvs.pixelPerfect = false;

    //Set Cavas sorting order to be above other Canvas sorting order
    cnvs.sortingOrder = 12;

    cnvs.targetDisplay = 0;

    addCanvasScaler(tempCanvas);
    addGraphicsRaycaster(tempCanvas);
    return tempCanvas;
}

//Adds CanvasScaler component to the Canvas GameObject 
private void addCanvasScaler(GameObject parentaCanvas)
{
    CanvasScaler cvsl = parentaCanvas.AddComponent<CanvasScaler>();
    cvsl.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
    cvsl.referenceResolution = new Vector2(800f, 600f);
    cvsl.matchWidthOrHeight = 0.5f;
    cvsl.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
    cvsl.referencePixelsPerUnit = 100f;
}

//Adds GraphicRaycaster component to the Canvas GameObject 
private void addGraphicsRaycaster(GameObject parentaCanvas)
{
    GraphicRaycaster grcter = parentaCanvas.AddComponent<GraphicRaycaster>();
    grcter.ignoreReversedGraphics = true;
    grcter.blockingObjects = GraphicRaycaster.BlockingObjects.None;
}


回答3:

RectTransform is mostly used for UI purposes. If you have a canvas already set up, then you can add an Image component, but you'll want to set it as a child of your canvas:

using UnityEngine;
using UnityEngine.UI;

public class ImageTest : MonoBehaviour {
    public Canvas canvas;
    public Sprite sprite;
    public float width = 10;
    public float height = 10;

    private void Start () {
        GameObject newObject = new GameObject("ObjectName");
        RectTransform rectTransform = newObject.AddComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(width, height);
        Image image = newObject.AddComponent<Image>();
        image.sprite = sprite;
        newObject.transform.SetParent(canvas.transform, false);
    }
};

If you just want to put the sprite in the scene, you can use a SpriteRenderer:

using UnityEngine;

public class SpriteTest : MonoBehaviour {
    public Sprite sprite;

    private void Start () {
        GameObject newObject = new GameObject("ObjectName");
        SpriteRenderer spriteRenderer = newObject.AddComponent<SpriteRenderer>();
        spriteRenderer.sprite = sprite;
    }
}

Or to simply show a texture, you can override the main texture on the material of a MeshRenderer:

using UnityEngine;

public class TextureTest : MonoBehaviour {
    public Texture texture;

    private void Start () {
        GameObject newObject = GameObject.CreatePrimitive(PrimitiveType.Quad);
        MeshRenderer meshRenderer = newObject.GetComponent<MeshRenderer>();
        meshRenderer.material.mainTexture = texture;
    }
}