JavaScript: Destroying transform trough .gameObject not works

This is my code. After 2 hours of messing with creating arrays, i cant destroy object (look for update function: it says that “Assets/Scripts/UIScript.js(33,59): BCE0019: ‘gameObject’ is not a member of ‘Object’”. Trying to destroy it without .gameObject returns “Can’t destroy Transform component of ‘UIHeart(Clone)’. If you want to destroy the game object, please call ‘Destroy’ on the game object instead. Destroying the transform component is not allowed.”

Code: #pragma strictvar playerStats: controller;var UIHeart: GameObject;var he - Pastebin.com

Couple of things I can see:

  • You are instantiating UIHeart.transform instead of UIHeart.
  • Instantiate returns an Object, which is where your error comes from so you want to cast to a GameObject
  • Your actual deleting code doesn’t remove anything from the array so you will run in to issues if you run that code multiple times. You need to splice the array too.

There are a few problems in your code related to types of objects.

  1. Instantiate returns the same type as the object you give it. However, it returns it as the base type UnityEngine.Object. You will need to cast it to the correct type to use any of that type specific fields/types. In your case you are instantiating a transform, so instantiate returns a transform

  2. You are using the unity class Array. I would advice you to not use it, but use one of the generic collections in .net. i.e. List<>. Array stores everything as System.Object(the base class everything inherits from), which means that you lose your type information and have to cast it back to the correct type every time you use it. With a generic list, the type information is stored and everything is returned as that type. So you don’t need to cast it to use it.

An example for that would be:
import System.Collections.Generic; // this at top

var heartsContainer: List.<GameObject> = new List.<GameObject>(); // this replaces the array line

// this goes in Start; currentObject is not used outside of Start, so it can be a local var
var currentObject=Instantiate(UIHeart.gameObject, Vector3(screenLTCornerMarker.transform.position.x+(mod/1.5), screenLTCornerMarker.transform.position.y, 0), Quaternion.identity);
heartsContainer.Add(currentObject);

// this goes in Update
Destroy(heartsContainer[heartsContainer.Count-1]);
heartsContainer.RemoveAt(heartsContainer.Count-1);