微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未找到 Unity 游戏对象

如何解决未找到 Unity 游戏对象

大家好,这是我第一次尝试在 Unity 中制作简单的游戏,但我被困在移动脚本中,

我已经为我的播放器编写了一个名为“播放器”脚本的脚本,所以现在我正在尝试为我的控制器编写一个脚本,它是一个触摸屏板,例如向左、向右和跳跃,我正在关注 youtube 教程,

即使我的脚本和教程脚本是相同的,但我的有错误,它说我的游戏对象没有找到或丢失......这是我的垫脚本

    public class TouchPad : 
    MonoBehavIoUr {

    public GameObject player;

    public void OnMouseDown()
    {
     if (gameObject.name == 
    "Left")
     {
     }
     else if (gameObject.name == 
    "Right")
     {
     }
     else if (gameObject.name == 
    "Jump")
     {
     }
     }
     public void onmouseup()
     {
     if (gameObject.name == "Left")
     {
     }
     else if (gameObject.name == 
    "Right")
     {
     }
     else if (gameObject.name == 
    "Jump")
     {
     }
     }
     public void OnMouseDrag()
     {
     if (gameObject.name == 
    "Left")
     {
         
    player.GetComponent<player>. 
    ().Left(); <<<<<<< The 
    <player> got "Could not be 
    Found"
     }
     else if (gameObject.name == 
    "Right")
     {
     }
     else if (gameObject.name == 
   "Jump")
     {
     }
    }
    }

解决方法

这是一个固定的代码。希望能帮助到你。另外,我已经用开关替换了你的 Else If,因为它比 Else if 性能更高。

您的问题是您的代码中在 player>.() 之后有一个 (.)。应该是

GetComponent<player>().Left();

但是,我决定修复您的整个代码,因为虽然它确实有效,但对性能不利。

此外,您不需要获取玩家所在的 GameObject。除非你真的需要。

public class TouchPad : MonoBehaviour 
{
    public GameObject Player; //We need to reference this in the unity inspector.
  
    private player PlayerScript;
    
    private void Awake()
    {
        if(Player != null)
        {
            PlayerScript = Player.GetComponent<player>(); //We get player from here.
        }
    }
    
    public void OnMouseDown()
    {
        switch(gameObject.name) //Switches are faster than Else if. So use them whenever possible.
        {
            case "Left": //Code here.
            break;
            
            case "Right": //Code here.
            break;
            
            case "Jump": //Code here.
            break;
            
        }
        
    }
    
    public void OnMouseUp()
    {
        switch(gameObject.name)
        {
            case "Left": //Code here.
            break;
            
            case "Right": //Code here.
            break;
            
            case "Jump": //Code here.
            break;
            
        }
    }
     
    public void OnMouseDrag()
    {
        switch(gameObject.name)
        {
            case "Left": PlayerScript.Left();
            break;
            
            case "Right": //Code here.
            break;
            
            case "Jump": //Code here.
            break;
            
        }
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。