- Home /
Edit only one of many instantiated objects
So I'm instantiating cubes with rigid bodies every 1.5 seconds at random locations. But when the instantiated cubes hit the platform their isKinematic is turn to true so they don't move anymore. But when I set it to true every instantiated cubes isKinematic is set to true when they get instantiated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bloackfall : MonoBehaviour
{
public Rigidbody fallingBlockPrefab;
public static Rigidbody fallingBlockInstance;
// Start is called before the first frame update
void Start()
{
StartCoroutine("SpawningBlocks");
}
// Update is called once per frame
void Update()
{
}
IEnumerator SpawningBlocks()
{
yield return new WaitForSeconds(SpawnTime);
int Randx, randZ;
Randx = Random.RandomRange(0, 10);
randZ = Random.RandomRange(0, 10);
fallingBlockInstance = Instantiate(fallingBlockPrefab, new Vector3(Randx, 20, randZ), transform.rotation);
StartCoroutine("SpawningBlocks");
}
and the OnCollision script is on the prefab itself
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class onCollision : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Platform")
{
Bloackfall.fallingBlockInstance.isKinematic = true;
}
}
}
if I remove the static I wont be able to use the on collision enter in the other script
Also didn't fix the problem even if I removed the static
Answer by mchts · Mar 07, 2019 at 05:57 PM
Instantiate() as the name implies means creating an "individual" instance of an object. If you want to handle each instance individually just attach your onCollision
script to your prefab and change collision detection part like:
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Platform") {
this.gameObject.GetComponent<Rigidbody>().isKinematic = true;
}
}
Btw you won't need public static Rigidbody fallingBlockInstance;
field anymore unless you want to keep a reference to your instance. If you want so you should keep track of every instance in a different way e.g. pooling or keeping them in a container and its a complete different story.
Thank you very much, much simpler than what I was trying to do. I'll have to do some research on containers