【问题标题】:Scripting problems in UnityUnity 中的脚本问题
【发布时间】:2020-06-24 10:48:27
【问题描述】:

我是 Unity 初学者。 我的脚本有问题:在上图中,移动脚本中不存在播放器项目。

这是我的代码:

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

public class Move : MonoBehaviour
{
    public float speed;
    public Transform player;
    // Start is called before the first frame update
    void Start()
    {
    
    }
    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");
        transform.Translate(x * speed * Time.deltaTime, y * speed * Time.deltaTime, 0);
        Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
        player.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
    }
}

【问题讨论】:

  • 您使用的是什么版本的 Unity、操作系统和 IDE?另外,您是否确保在添加 public Transform player; 后保存了脚本?

标签: c# unity3d


【解决方案1】:

我不确定我是否理解正确,但由于此脚本是属于 Player Gameobject 的脚本,因此您无需指定“public Transform player”。 Gameobject 类继承自 Transform 类,因此如果您尝试它应该可以工作:

Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);

也许为了更清楚: 您不需要将 Player 作为您拉入检查器中相应字段的“项目”,因为如果您与不包含“移动”脚本的游戏对象相关联,情况就是如此。 因此,如果您将脚本附加到游戏对象(在这种情况下,您将脚本附加到“玩家”),那么您编写的任何方法都会直接影响脚本所属的游戏对象。 例如。尝试以下方法:

void Update() {
    if(Input.GetKeyDown("space")) {
        Destroy(gameObject);
    }
}

您会看到,当您按下空格键时,构成您的播放器的圆圈会自行销毁。参数“gameObject”指的是脚本所属的游戏对象。

我希望这可以帮助您理解,您无需指定需要链接到脚本的额外游戏对象,只要您要操作的游戏对象包含此脚本即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多