現在 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++;
}
}
}
}
ボールとスター (後に続くゲームオブジェクト) は、作成時にホワイトボールが保持していた位置に向かって移動する必要があります。