- Home /
The object spriteRender and collision is off
Hi, I making a platform game that when the player jump on the platform after a few second the platform spriterender and collision is off and after few second after that the platform spriterender and collision is on again.
this is my code for the platform
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platform : MonoBehaviour
{
BoxCollider2D box2D;
SpriteRenderer platformSp;
public float timeToSpawn;
public bool platformDown;
// Start is called before the first frame update
void Start()
{
box2D = GetComponent<BoxCollider2D>();
platformSp = GetComponent<SpriteRenderer>();
}
private void Update()
{
if(platformDown)
{
platformSp.enabled = true;
box2D.enabled = true;
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player") && !platformDown)
{
StartCoroutine(PlatformFall());
platformDown = true;
}
else if(platformDown)
{
StartCoroutine(PlatformSpawn());
}
}
IEnumerator PlatformFall()
{
yield return new WaitForSeconds(1f);
platformSp.enabled = false;
box2D.enabled = false;
}
IEnumerator PlatformSpawn()
{
yield return new WaitForSeconds(timeToSpawn);
platformDown = false;
}
}
there no error and I dont know what to do I appreciate any help
Answer by jmfp92 · Nov 09, 2021 at 09:33 AM
It is because you literally wrote the code to do exactly what you're asking about. I think I'm a little confused on the question because from the code provided you seem to be intentionally using coroutines to turn the boxcollider and spriterenderer off every few seconds. When you set the enabled value to the boxcollider and spriterenderer to false, don't do that anymore. Then in your update function you are turning them back on again once they fall. Assuming the platform is just supposed to fall after a few seconds of the player being on it, why not just destroy the gameobjects this script is attached to instead of disabling it? are you reusing the same platform?
Yes I using the same platform gameobject because if I destroy the platform I encounter a few more problem that why I choose to this instead
Ok try this then. Create your platform, add the components you need for it, save it as a prefab in your project, and instead of reusing the same gameobject Instantiate a new object from the prefab. I don't want to insult your intelligence or experience but if you don't know how to instantiate objects in unity you should read some docs before proceeding https://docs.unity3d.com/ScriptReference/Object.Instantiate.html