Instantiate and then destroy a prefab in a list. C#

I’m trying to spawn a simple object with some kill code in it that will be destroyed in a collision event later on. I’m not too sure on what I’m doing but as far as I can tell I need to make it into a prefab then instantiate it into a list and then destroy it in the collision and clear the list. The list is necessary since there are multiple of them and I only want to remove some, not to mention them all having the same name making it confusing. I’ve been trying for a while and think I’ve been able to get it to go into the list but it only seems to ever allow one in there and I could only make it go as a Object rather than GameObject. I cant destroy it since it’s saying something about it only trying to destroy the transform and I can’t figure it out. Here is the code for the object spawner:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ObstacleGenerator : MonoBehaviour {

public Object Obstacle;
private float yPos;
public List<Object> currentObstacles = new List<Object>();

public void Start () {
	yPos = Random.Range (20, 200);
	currentObstacles.Add (Instantiate (Obstacle, new Vector3 (250f, 1.5f, yPos), Quaternion.identity));

And here is the code for the collision:

public class ResetPos : MonoBehaviour {

public ObstacleGenerator obstacleGeneratorScript;

void OnTriggerEnter(Collider Player){

	obstacleGeneratorScript.GetComponents<ObstacleGenerator> ();

You are right till the “…make it into a prefab then instantiate” the whole list thing is useless unless you need to refer to them later on. Now for the destroy event which is triggered by a collision you need to attach that script on the prefab and make the collider of the prefab a trigger , assuming you want it to be destroyed when collide with the Player GameObject.

void OnTriggerEnter(Collider col)
        if (col.CompareTag("Player"))

Make sure to add the tag Player on the player GO.

And this to Instatiate:

public GameObject obstaclePrefab;
    void Start()                //don't use the Start though because you ll only instatiate one obstacle!
        float yPos = Random.Range(20, 200);
        Instantiate(obstaclePrefab, new Vector3(250f, 1.5f, yPos), Quaternion.identity));

As for the fact that you list is taking only objects is because you “instructed” it to do so if you change the List to List and the Object Obstacle to GameObject Obstacle. There is no point to use Object in this case as it is a base class and won’t hold lot of info you need stick to GameObject instead. Cheers.

Note: if you instatiate and destroy the same prefab(object) again and again i highly recommend to create a pooling system and just disable/enable them accordingly, as on how to do this, look around there are several tutorials on the subject.