- Home /
How do I add scripts to gameobject if (x) but remove them if (not x)
I'm trying to make a game where you can click on a character to control them, so I want to add a PlayerController script to an object when clicked on. the stuff in this script is just adding and removing the PlayerController from the gameobject it's attached to, but it doesn't work. I've removed the faulty stuff and replaced it with comments describing what exactly I want to do, but I cannot figure out, no matter what method I use, how to make it work. (the stuff I need is in the update function)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flufbol : MonoBehaviour
{
float energy = 5f;
public float food = 5f;
public float metabolicRate = 0.1f;
public float foodEfficiency = 2f;
public float energyUsage = 0f;
public float speed = 4f;
public float jumpheight = 10f;
public GameObject player;
PlayerBase playerData;
void Start()
{
playerData = player.GetComponent<PlayerBase>();
}
void Update()
{
//if playerdata.followedFlufbol = this gameobject:
//add PlayerController script to this gameobject (but only 1)
//else:
//remove PlayerController script, if it exists, from this gameobject
}
void FixedUpdate()
{
if (food > 0)
{
energy += metabolicRate * Time.fixedDeltaTime * foodEfficiency;
food -= metabolicRate * Time.fixedDeltaTime;
}
energy -= (metabolicRate * Time.fixedDeltaTime) + energyUsage;
if (energy <= 0)
{
Destroy(gameObject);
}
}
}
Answer by NPnpNPnpNP · Apr 19, 2021 at 02:36 PM
To add a comonent, use gameObject.AddComponent<Component Type>();
. To delete it, use Destroy();
.
In your case, you can do something like this :
// Get the PlayerController attached to this gameObject
PlayerController playerController = GetComponent<PlayerController>();
if (playerdata.followedFlufbol == gameobject)
{
if (!playerController) // Check that there is no PlayerController
gameObject.AddComponent(PlayerController);
}
else if (playerController) // Check that there is a PlayerController
{
Destroy(playerController);
}
worked perfectly (on my third try, capitalization and whatnot). thank you! I think my other ideas didn't work because I was setting a variable pc to addcomponent but only if it was null, which was why it didn't work with multiple charectors and probably why my Destroy() wasn't working.
Your answer
Follow this Question
Related Questions
How to destroy Instantiated objects (C#)(not last instantiated one) 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Create destroyed prefab 1 Answer
Trouble with destroy function 2 Answers