【问题标题】:Only one game object moves in unity when I have 3 identical objects当我有 3 个相同的对象时,只有一个游戏对象统一移动
【发布时间】:2020-09-29 06:52:22
【问题描述】:

这一直困扰着我一段时间,我找不到解决方案。只有ground3 移动,而其他 2 保持在原地。我正在使用统一并做一个 2d 项目。

代码:

using System.Collections.Generic;
using UnityEngine;

public class GroundMovement : MonoBehaviour
{
    public float globalspeed;

    public GameObject Ground1;
    public float Ground1Speed;
    Rigidbody2D rb1;

    public GameObject Ground2;
    public float Ground2Speed;
    Rigidbody2D rb2;

    public GameObject Ground3;
    public float Ground3Speed;
    Rigidbody2D rb3;


    // Start is called before the first frame update
    void Start()
    {
        rb1 = Ground1.GetComponent<Rigidbody2D>();
        rb2 = Ground1.GetComponent<Rigidbody2D>();
        rb3 = Ground1.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        rb1.velocity = new Vector2(globalspeed + Ground1Speed, 0);
        rb2.velocity = new Vector2(globalspeed + Ground2Speed, 0);
        rb3.velocity = new Vector2(globalspeed + Ground3Speed, 0);
    }
}

【问题讨论】:

  • 你确定所有的东西都在你的检查器中分配了,并且你的所有对象都有一个刚体组件吗?
  • 是的 100% 我检查了 10 次
  • 为什么是rb3 = Ground1.GetComponent&lt;Rigidbody2D&gt;(); 而不是rb3 = Ground3.GetComponent&lt;Rigidbody2D&gt;();
  • 因为我很笨,这就是解决方案
  • 你每次都从 ground1 得到 rb,所以只得到了 1 个

标签: c# unity3d variables rigid-bodies


【解决方案1】:

问题出在Start()方法中,当你分配刚体时,你将它们全部分配给Ground1 GameObject中的刚体,方法应该是这样的:

void Start()
{
    rb1 = Ground1.GetComponent<Rigidbody2D>();
    rb2 = Ground2.GetComponent<Rigidbody2D>();
    rb3 = Ground3.GetComponent<Rigidbody2D>();
}

【讨论】:

  • 另外我建议你使用 C# 命名约定(变量的骆驼大小写)例如:ground1ground1SpeedglobalSpeed
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
相关资源
最近更新 更多