Attach a shield to player (C#)
I'm making a 2D game and I'm trying to make a power up that spawns out a shield on the player. It's supposed to be attached to the player, so when the player moves it will be attached to the players position. I've managed to instantiate the shield but it only spawns on the players position and is not attached.
How can i attach the shield to the player? Greatful for any help I can get, you guys are the best!
using UnityEngine;
using System.Collections;
public class PickUpScript : MonoBehaviour
{
public GameObject shield;
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "PowerUp1")
{
SpawnShield();
Destroy(GameObject.FindGameObjectWithTag("PowerUp1"));
}
}
public void SpawnShield()
{
Instantiate(shield, GetComponent<MoveScript>().character.transform.position,
GetComponent<MoveScript>().character.transform.rotation);
}
}
Answer by TreyH · Mar 12, 2016 at 02:11 PM
You'll want to set the shield's parent as your character (untested code):
public void SpawnShield()
{
// Get the transform ahead of time for readability
Transform charTransform = GetComponent<MoveScript>().character.transform;
// Instantiate and keep track of the new instance
GameObject newShield = Instantiate(shield, charTransform.position, charTransform.rotation);
// Set parent
newShield.transform.SetParent(characterTransform);
}
It works! The only thing I had to change was:
GameObject newShield = Instantiate(shield, charTransform.position, charTransform.rotation);
to:
GameObject newShield = Instantiate(shield, charTransform.position, charTransform.rotation) as GameObject;
You are the best my friend, I wish you all luck in the world, thanks! :D
Answer by Earl_Wade · Aug 13, 2016 at 01:39 AM
if it is a child of the ship, Check the box to make it inactive. When you pick up the powerup, set to active ex: void OnTriggerEnter(Collider other) { if(other.tag == "Poweup") { Shield.SetActive(true); } } this is a much easier way to change shield looks, according to how much is left, set one to active, and set the other to inactive when the shields reach a certain level.