我目前正在 Unity 中开发游戏,我有一个问题。当生成我创建的预制件的新克隆时,我希望实例化的游戏对象移动到另一个游戏对象在它们生成时的位置。这意味着根据设计,我需要使相同游戏对象/预制件的不同实例表现不同或移动到不同位置,即使它们同时处于活动状态。但是,当通过选项时,我必须在脑海中解决这个问题,我只能得到极其复杂且资源密集型的解决方案(例如,创建一个列表字典,每个列表都保存在创建过程中创建的游戏对象,然后使速度变量对于不同的列表 ext... 表现不同。)但是,我觉得必须有一个更简单且资源消耗更少的解决方案,因为我看到这类问题一直在游戏中得到解决。有谁知道我能做什么?
这是负责移动游戏对象实例的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractMovement : MonoBehaviour
{
Rigidbody2D rb;
GameObject target;
float moveSpeed;
Vector3 directionToTarget;
Renderer m_Renderer;
void Start()
{
if (ScoreScript.scoreValue > 4)
{
target = GameObject.Find("White Ball");
rb = GetComponent<Rigidbody2D>();
moveSpeed = 5f; //Movement speed of all the obstacles and powerups
InvokeRepeating("MoveInteract", 0f, 1f);
}
}
void MoveInteract() //Method responsable for the movement of the obstacles and stars
{
if ( this.gameObject != null)
{
directionToTarget = (target.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
directionToTarget.y * moveSpeed);
}
else
rb.velocity = Vector3.zero;
}
}
这是用于创建相关游戏对象实例的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BallSpawnerControl : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject[] interact;
int randomSpawnPoint, Interact;
int index = 1;
public static bool spawnAllowed;
// Use this for initialization
void Start()
{
spawnAllowed = true;
InvokeRepeating("SpawnAInteract", 0f, 1f);
}
void SpawnAInteract()
{
if (spawnAllowed)
{
if (index % 5 != 0)
{
randomSpawnPoint = Random.Range(0, spawnPoints.Length);
Interact = 1;
Instantiate(interact[Interact], spawnPoints[randomSpawnPoint].position,
Quaternion.identity);
index++;
}
else
{
randomSpawnPoint = Random.Range(0, spawnPoints.Length);
Interact = 0;
Instantiate(interact[Interact], spawnPoints[randomSpawnPoint].position,
Quaternion.identity);
index++;
}
}
}
}
球和星(后面的游戏对象)应该朝着白球在创建时所持有的位置移动,而不是改变它们的方向朝向白球新的 MoveInteract 调用