unity3d 示例化不显示对象

h22fl7wq  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(210)

我试图让一个对象在unity2d中的鼠标位置产生,但没有一个对象显示。它在层次结构中添加了新的克隆,但只是没有显示。
下面是游戏控制器对象的脚本

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

public class gamecon : MonoBehaviour
{
   
    public GameObject square;
   
    public void Start()
    {
    
    
    }
        
    
    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            
            Vector3 spawnpos = Camera.main.WorldToScreenPoint(Input.mousePosition);
            
            GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
        }

    }

}

我在网上找不到任何适合我情况的答案。谢谢你的帮助。

vwkv1x7d

vwkv1x7d1#

解决方案是使用ScreenToWorldPoint方法而不是WorldToScreenPoint,因为您需要的是生成对象的世界位置。
请使用下列程式码:

public void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        
        Vector3 spawnpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        
        GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
    }

}

相关问题