Hi friends, noob here.
I currently have a script for making a bottle instantiate into a brokenbottle on collision. It looks like this:
using System.Collections; using
System.Collections.Generic; using
UnityEngine;
public class Break : MonoBehaviour {
public GameObject destroyedVersion;
void OnCollisionEnter ()
{
Instantiate(destroyedVersion, transform.position,
transform.rotation);
Destroy(gameObject);
} }
Simple enough, but the problem is the actual instantiate is delayed a moment. From my understanding this has to do with how the engine works. So to bypass this I would like a script that instantiates upon detection of a difference in y position or when velocity > 0. I’m still quite green and any insight is greatly appreciated.
Hi @bloodshot2
You can simply store the last y or velocity and check for a significant change in each update tick and switch between the models.
For example:
float lastY = 0;
void Start(){
lastY = this.transform.position.y;
}
void Update(){
if(Mathf.abs(this.transform.position.y - lastY) > THRESHOLD){
//trigger the switch/instantiate
}
lastY = this.transform.position.y;
}
If you want to have a switchable model, use a parent object with the above script attached, as well as two children. The children only have a meshrenderer and -filter, one for the whole bottle, and one for the broken one. On triggering, simply deactivate the “whole” mesh, and activate the other.
If you put in when if(velocity > 0) it will break as soon as it starts falling, not when it hits the ground. there is a delay with the instantiate because it uses a lot of resources, instead you should be pooling the broken bottle objects, or in this situation I’d make the bottle have 2 states governed by the bool isBroken; then you have references to your graphic for each and swap it when isBroke changes. Or you could have 2 separate sprite or objects that you enable or disable and there are many ways to manage that, but the easiest would be unbrokenBottle.Setactive(!isBroken); brokenBottle.Setactive(isBroken);