未找到 Unity GameObject

Unity GameObject not found

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

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

即使我的脚本和教程脚本是一样的,但是我的出错了,它说我的游戏对象找不到或丢失了...这是我的 pad 脚本

    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();

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

此外,您不需要获取玩家所在的游戏对象。除非你真的需要。

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;
            
        }
   }
}