Destroy after duration slider

For my school project, I’ve designed a solar system simulator and one of my last success criteria seems very simple but I just can’t get it to work at all.

What I want is a slider which dictates how long a planet will last for before being destroyed as I’ve stated this as being one of my success criteria.

I already have an add planet button which works fine but I want the user to be able to adjust how long it’ll last.

I’ve already created the slider in the inspector, I just want the method to go along with it

Here’s my current code:

using System.Collections;
using UnityEngine;

public class AddPluto : MonoBehaviour {

    public GameObject clone;
    public GameObject Pluto;
    public float duration = 50f;

    public void PlanetDuration(float duration)
    {

    }



    public void AddObject()
    {
        //Creates clone of Pluto
        clone = Instantiate(Pluto, new Vector3 (2F, 0, 0), Quaternion.identity);
        Destroy (clone, duration); 
    }
     
}

@matt_baker298

If this is a school assignment, shouldn’t you figure this out yourself?

Anyway, do you mean you need a slider on screen (game view) or in Unity Inspector?

Well this is kind of a school assignment, just that you are allowed to get help online.

I mean a slider on screen as well

Everything you code in Unity happens “right now,” generally speaking.

To do something later, you need a coroutine.

Fortunately there are dozens of tutorials on coroutines available on google, and they’re really a powerful time-control construct in Unity.

For the coding part of your solution, you would:

  • read the .value field out of the Slider reference
  • convert that to whatever number of seconds it should be in your context
  • start a coroutine that yields for that many seconds, then destroys the planet in question.

I actually figured it out. It’s just that I had to use UnityEngine.UI and use the slider reference. It seems like such a simple thing to implement, yet I’ve spent the last 3 hours trying to figure it out.

This is now the amended code:

using System.Collections;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class AddPluto : MonoBehaviour {
  
    public GameObject clone;
    public GameObject Pluto;
    public Slider PlanetDuration;

    public void AddObject()
    {
        //Creates clone of Pluto
        clone = Instantiate(Pluto, new Vector3 (2F, 0, 0), Quaternion.identity);
        // Destroys clone after 60 seconds
        Destroy (clone, PlanetDuration.value);  
    }

    public void duration(float newPlanetDuration){

        PlanetDuration.value = newPlanetDuration;
    }
      
}
1 Like