首页 > 解决方案 > 我如何将新画布实例化为画布,并在 MainCamera 上设置屏幕空间?

问题描述

我有一个带有一些游戏对象的画布,我想实例化一个包含画布的新游戏对象,所以问题是它出现在主相机之外,我需要在我的游戏的 MainCamera 上设置渲染相机。

我有这个,但它不起作用。

运行游戏的主摄像头: img of unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class newCanvas: MonoBehaviour
{
    // Start is called before the first frame update
  public GameObject text; //here i put the text, that I want to appear
  private GameObject textD; //i use the for to delete the text

  public void Start(){
    textoD = Instantiate(text, transform.position, transform.rotation);//instantiate the text, and its instantiated outside of the maincamera of the game
    Invoke("DeleteText",2f);//invoke to delete the game object
  }
  
  void DeleteText(){
        Debug.Log("Delete text");
        Destroy(textD);
    }
}

我有这样的事情:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class mainGAme : MonoBehaviour
{
public newCanvas text=null;

void Start(){
  text = GameObject.FindObjectOfType<newCanvas>();
  Instantiate(newCanvas);
}


void Update(){

}
}

当我执行游戏时,对象被实例化,它在主摄像头之外被实例化,因为它没有将渲染摄像头设置为游戏的主摄像头。

有人知道怎么解决,谢谢<3

标签: c#unity3d

解决方案


您需要将游戏对象变换的父级设置为相机的变换。

https://docs.unity3d.com/ScriptReference/Transform.SetParent.html

实例化实际上有一个重载,允许你设置父级

公共静态对象实例化(对象原始,转换父);

https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

您可以通过相机中的静态属性获取相机

https://docs.unity3d.com/ScriptReference/Camera.html

您应该查看以下文档以更好地了解如何使用 Transform 和 Gameobject。

https://docs.unity3d.com/ScriptReference/GameObject.html

https://docs.unity3d.com/ScriptReference/GameObject-transform.html

https://docs.unity3d.com/ScriptReference/Transform.html


推荐阅读