c# - 当我有 3 个相同的对象时,只有一个游戏对象统一移动
问题描述
这一直困扰着我一段时间,我找不到解决方案。只有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);
}
}
解决方案
问题出在Start()
方法中,当你分配刚体时,你把它们都分配给了GameObject中的刚体Ground1
,方法应该是这样的:
void Start()
{
rb1 = Ground1.GetComponent<Rigidbody2D>();
rb2 = Ground2.GetComponent<Rigidbody2D>();
rb3 = Ground3.GetComponent<Rigidbody2D>();
}
推荐阅读
- php - 不要在 Gmail 中获得后者,而是在 Outlook 中获得
- vue.js - 使用补丁包在本地修补 NPM 包,不起作用
- c++ - 增强 opencv 类型的序列化
- amazon-web-services - 构建应用程序时从 s3 存储桶混合配置文件
- google-apps-script - 从当前电子表格在其他电子表格中运行脚本
- json - 在 Logic-App Liquid Map 中将字符串转换为整数
- python - 如何仅使用 If、elif 语句解决基本的里氏量表问题
- linux - epoll的EPOLLEXCLUSIVE可以同时触发同一个socket上的多个读取吗?
- php - PHP 致命错误:未捕获的 GuzzleHttp\Exception\ClientException
- r - R 面板数据中变量的计数/绘图随时间变化