kyle hadley
kyle hadley

Reputation: 57

unity3d how can i delete enemy :S and not the animator

How would I delete an enemy on the enemyprefab but not the enemanim animator?

#pragma strict

var enemy : GameObject;
var speed : float = 1.0;
var enemanim : Animator;

function Start() {
    this.transform.position.x = 8.325;
    this.transform.position.y = -1.3;
    enemanim = this.GetComponent(Animator);
    enemanim.SetFloat("isdead", 0);
}

function OnCollisionEnter2D(coll: Collision2D) {
    if (coll.gameObject.CompareTag("distroy")) {
        Destroy(this.gameObject);
    }
}

function enemstruck() {
    enemanim.SetFloat("isdead", 1);
}

function FixedUpdate() {
    this.transform.Translate(Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0));
    this.rigidbody2D.velocity = Vector2(-5, 0);
}

This is my enemy prefab code i am instantiating it in my main

These 2 var:

var enemytrans : Transform;
var enemy : GameObject;

function Start () {
    while (true) {
        yield WaitForSeconds (Random.Range(3, 0));
        enemy = Instantiate(enemytrans).gameObject;
    }

Upvotes: 1

Views: 123

Answers (2)

axwcode
axwcode

Reputation: 7824

It is possible to save the Component and Destroy the GameObject. Although I can only think of very few special cases when this would be done with logic (not out of madness).

For example, you might have different enemies, when one dies, its special power transfers over to another enemy via the Component.


So this is how I would do it, using the example above (code is C# because UnityScript lacks power):

public void die()
{
    Component c = GetComponent<TheType>();

    // Send component.
    BroadcastMessage("setComponent", c);

    // Destroy.
    Destroy(gameObject);
}

Then whatever object is listening to setComponent will handle it:

public void setComponent(Component c)
{
    gameObject.AddComponent<c>();
}

I have never done this before, but it came out so awesome that now I am going to add it to one of my games

Upvotes: 0

maZZZu
maZZZu

Reputation: 3615

I think you cannot delete GameObject and save one of its components. Every component needs to be attached to some GameObject and you cannot move them to other GameObjects either.

What you can do is to remove other components from your GameObject and you will get the same result. You can remove a component with following script:

Destroy(gameObject.GetComponent(yourComponent));

Upvotes: 2

Related Questions