Gameobject destroy fails inside destructor - c#

I have an object, which contains a list of GameObjects. I wish to destroy all of these GameObjects in its destructor.
However, when I attempt to call GameObject.Destroy() from inside the destructor, it seems to halt execution (the line after GameObject.Destroy() never executes, but the line before it does)
If i copy and paste exactly the same code into a function called not_a_destructor() and call that instead, it works perfectly. What gives? I've got it working, but I would really like to understand what's going on.
Destructor and not_a_destructor() code:
// Destructor DOES NOT work
~MoveAction(){
for(int i = 0; i < arrows.Count; i++){
Debug.Log("wasd");
GameObject.Destroy(arrows[i]);
Debug.Log("asdf");
}
}
// Identical code, calling not_a_destructor() works perfectly
public void not_a_destructor(){
for(int i = 0; i < arrows.Count; i++){
Debug.Log("PRETEND DESTRUCTOR!");
GameObject.Destroy(arrows[i]);
Debug.Log("GameObject destroyed successfully");
}
}
As requested in comments, a full copy of the class:
public class Action
{
public int type;
public string debug_string;
public GameObject ui_pill; // Only present for Actions created on the client
}
public class MoveAction : Action
{
public int type = ActionType.MOVE;
public MapHex origin;
public List<MapHex> route; // Intermediate hexes travelled through during the move (includes target_hex)
public Fleet fleet;
private List<GameObject> arrows = new List<GameObject>(); // Arrows for the graphical representation of the pending move on the tactical map
public MapHex target_hex {
get {
return route[route.Count - 1];
}
}
public string debug_string {
get {
return "MOVE ACTION WITH FLEET: " + fleet.name;
}
}
public MoveAction(Fleet _fleet, List<MapHex> _route){
fleet = _fleet;
route = _route;
origin = fleet.planned_position;
update_arrows_from_route();
}
public void update_arrows_from_route(){
Material default_material = new Material(Shader.Find("Sprites/Default"));
// Create one arrow for every hex we will pass through.
MapHex last = fleet.planned_position;
foreach (MapHex hex in route){
// Create arrow from last to hex
GameObject arrow_gameobj = new GameObject();
arrow_gameobj.name = "move_order_arrow";
LineRenderer line_renderer = arrow_gameobj.AddComponent<LineRenderer>();
line_renderer.material = default_material;
line_renderer.SetColors(fleet.owner.color, fleet.owner.color);
line_renderer.positionCount = 2;
arrow_gameobj.layer = layers.tactical_map;
Vector3[] line_points = new Vector3[]{last.position, hex.position};
line_renderer.SetPositions(line_points);
line_renderer.startWidth = 0.1f;
line_renderer.endWidth = 0.1f;
arrows.Add(arrow_gameobj);
last = hex;
}
}
public void not_a_destructor(){
for(int i = 0; i < arrows.Count; i++){
Debug.Log("PRETEND DESTRUCTOR!");
GameObject.Destroy(arrows[i]);
Debug.Log("GameObject destroyed successfully");
}
}
~MoveAction(){
for(int i = 0; i < arrows.Count; i++){
Debug.Log("wasd");
GameObject.Destroy(arrows[i]);
Debug.Log("asdf");
}
}

Its probable best to use more of Unity and less of C#, there is a good callback called OnDestroy() which would be a fine place to destroy all the arrows. If execution of your unity code depends on running a finalizer on something, this is a very strong code smell.
Unless you are using IO in a way that REQUIRES an action to happen in a finalizer (possibly things like releasing an IO resource), its best to leave them empty, and put Unity code inside Unity callbacks

Related

How to call a method after each line of code or something like that

I have a method that is supposed to check a player's HP and then perform some logic based on if the number is greater than 0, or less than or equal to 0.
The method works but if I type it in the code and then change the hp value of a player it won't do anything until I type in the method name again. Then it will display the correct information.
At first I thought of using some kind of loop instead of a method. If I am correct, that means I'd have to have put curly braces around all my code that needs to get checked (which means basically around the whole code and I don't want that). Same with IF statement - even if I put it at the beginning of the code I'd still have to put curly braces around all the code.
Then I thought of a method which I already mentioned. And as I said - it does what it's supposed to do but only if I paste it multiple times into the main code.
Now, my question - is there ANY way to make the method "repeat itself" constantly or, I don't know, start at some place in the code and remain active?
Here is the method:
static void Status()
{
if (Player.playerHealth <= 0)
{
Player.isDead = true;
Console.WriteLine("You are dead!");
}
else if(Player.playerHealth > 0)
{
Player.isDead = false;
Console.WriteLine("You are not dead!");
}
}
I would be really grateful for any help.
You can define playerHealth as a property. That way, any time anyone changes it, you can make some code fire, including the check that you want.
class Player
{
protected int _playerHealth = 0;
public int PlayerHealth
{
set
{
_playerHealth = value;
if (_playerHealth == 0)
{
isDead = true;
Console.WriteLine("You are dead!");
}
}
get
{
return _playerHealth;
}
}
Now you don't even need to call Status... the logic will occur automatically whenever the player's health is modified.
var player = new Player();
player.PlayerHealth = 0; //Automatically triggers message
Correct me if I'm wrong but you want to call a method everytime the player's life changes? It looks like you should use an event.
public class HealthEventArgs : EventArgs
{
public int Health { get; set; }
public HealthEventArgs(int health)
: base()
{
this.Health = health;
}
}
public class Player
{
public event EventHandler<HealthEventArgs> LifeChanged;
int _Health;
public int Health
{
get => _Health;
set
{
_Health = value;
LifeChanged?.Invoke(this, new HealthEventArgs(_Health));
}
}
}
Then in your code it would look something like that
Player player = new Player();
player.LifeChanged += (o, e) =>
{
Player p = o as Player;
int health = e.Health;
// Whatever logic here, with access to the player and its health
};
With that mechanism in place, everytime the health of a player changes the event will fire and you will have access to the player and its health and can act accordingly.
If you're not confortable with lambda expressions, the code above can also be written as such
Player player = new Player();
player.LifeChanged += PlayerLifeChanged;
public void PlayerLifeChanged(object o, HealthEventArgs e)
{
Player p = o as Player;
int health = e.Health;
// Whatever logic here, with access to the player and its health
};

Unity Changing material color on multiple gameobjects

I made a right click menu and i want to make objects change material color while i have my mouse on a button in that menu.
This is the code:
Color[] startCo;
public void OnPointerEnter(PointerEventData eventData)
{
GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);
for (int i = 0; i < startCo.Length; i++)
{
startCo[i] = objects[i].gameObject.GetComponent<MeshRenderer>().material.color;
}
foreach (GameObject obj in objects)
{
obj.gameObject.GetComponent<MeshRenderer>().material.color = Color.red;
}
}
public void OnPointerExit(PointerEventData eventData)
{
GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);
for (int i = 0; i < objects.Length; i++)
{
objects[i].gameObject.GetComponent<MeshRenderer>().material.color = startCo[i];
}
}
With first for loop it does not work at all, but without it, when I put my mouse on the button, it makes material colors red, but it won't change it back to orginal.
My question is, is there any better way to save original colors with using foreach?
Try this version. It basically does exactly the same thing as your version, but makes sure to initialize the color array before using it (which was probably your main issue). It also keeps a copy of the list of objects whose colors were replaced, which is important in case new objects with a matching tag are created, or existing one's deleted. Finally, it adds a few safeguards to make it more robust in case you want to use ReplaceColors() and RestoreColors() in other places, too.
GameObject[] objectsWithReplacedColors;
Color[] originalColors;
public void OnPointerEnter(PointerEventData eventData)
{
ReplaceColors(GameObject.FindGameObjectsWithTag(myMenu.selected.title), Color.red);
}
public void OnPointerExit(PointerEventData eventData)
{
RestoreColors();
}
private void ReplaceColors(GameObject[] forObjects, Color withColor)
{
if (objectsWithReplacedColors != null) // if there are already objects with replaced colors, we have to restore those first, or their original color would be lost
RestoreColors();
objectsWithReplacedColors = forObjects;
originalColors = new Color[objectsWithReplacedColors.Length];
for (int i = 0; i < objectsWithReplacedColors.Length; i++)
{
originalColors[i] = objects[i].GetComponent<MeshRenderer>().material.color;
objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = withColor;
}
}
private void RestoreColors()
{
if (objectsWithReplacedColors == null)
return;
for (int i = 0; i < objectsWithReplacedColors.Length; i++)
{
if (objectsWithReplacedColors[i]) // check if the objects still exists (it may have been deleted since its color was replaced)
objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = originalColors[i];
}
objectsWithReplacedColors = null;
originalColors = null;
}
Well my guess is you are finding objects every time these methods are called using GameObject.FindGameObjectsWithTag and i am pretty sure the order of these objects returned by FindGameObjectsWithTag is not specified so it can change ever time you call this method. This issue ends up giving you different original colors for different objects. My suggestion would be getting objectsin the Startonce and assigning colors to the array. Then use this array in OnPointerExitfunction.
Other than that your code and logic seems fine to me.

Scripts Works on one scene but error in another [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
So I'm getting an error which says
Object reference not set to an instance of an object Explode.LateUpdate () (at Assets/Scripts/Explode.cs:40)
I'm not sure why I get this error as everything works fine and I have the exact same script in a different scene without the error message. I'd love any help please.
I'm exploding my player with different coloured boxes.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explode : MonoBehaviour {
[System.Serializable]
public class ExplodeColours
{
public Color32[] Colours;
}
public static bool explode, explodeOnce;
public ParticleSystem Explodes;
private ParticleSystem explosionSystem;
public Transform player;
public List<ExplodeColours> ColoursList;
// Use this for initialization
void Start () {
PlayerPrefs.SetInt("SelectedChar", 0);
PlayerPrefs.Save();
explodeOnce = false;
explode = false;
}
// Update is called once per frame
void Update () {
if (explode == true)
{
explodeOnce = true;
PlayerExplode();
}
}
void LateUpdate()
{
if (explode)
{
ParticleSystem.Particle[] Particles = new ParticleSystem.Particle[explosionSystem.main.maxParticles];
//ParticleSystem.Particle[] Particles = new ParticleSystem.Particle[Explodes.main.maxParticles];
int NumParticlesAlive = explosionSystem.GetParticles(Particles);
for (int i = 0; i < NumParticlesAlive; i++)
{
Particles[i].startColor = (ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours[Random.Range(0, ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours.Length)]);
}
explosionSystem.SetParticles(Particles, NumParticlesAlive);
explode = false;
}
}
void PlayerExplode()
{
explosionSystem = Instantiate(Explodes, player.position, player.rotation);
explosionSystem.Play();
}
}
If this is line 40 (I had to count):
ParticleSystem.Particle[] Particles = new ParticleSystem.Particle[explosionSystem.main.maxParticles];
Then explosionSystem or main or maxParticles is null. I'm going to close this as a duplicate, this error is so common and the way to resolve it is easy.
But a break point on the line of code, when the code control halts, check which object is null and make sure its set.
EDIT:
Use the GetComponent to initialize the explosionSystem variable in the Start function.First, find the GameObject the ParticleSystem is attached to the use GetComponent to get the ParticleSystem.
private ParticleSystem explosionSystem;
void Start()
{
GameObject obj = GameObject.Find("NameOfObjectParticleSystemIsAttachedTo");
explosionSystem = obj.GetComponent<ParticleSystem>();
}
Also, inside the for loop, you tried to use Particles's startColor property without initializing each one. You can do that with Particles[i] = new ParticleSystem.Particle();.
Change:
for (int i = 0; i < NumParticlesAlive; i++)
{
Particles[i].startColor
= (ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours[Random.Range(0, ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours.Length)]);
}
to
for (int i = 0; i < NumParticlesAlive; i++)
{
Particles[i] = new ParticleSystem.Particle();
Particles[i].startColor
= (ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours[Random.Range(0, ColoursList[PlayerPrefs.GetInt("SelectedChar")].Colours.Length)]);
}
To avoid the null reference error, make sure all variables (which are using) has values other wise at least assign default values in constructor level

UNITY c#: Spawning character prefabs based on user selection

I have game for multiple players where each user selects their hero before game starts and that loads the selected heroes into the battle arena.
I have small issue with getting the instantiation to spawn in correct numbers of players
The method that I have for Spawning the characters:
private void Placement()
{
for (int i = 0; i < SelectedCards.Count; i++)
{
for (int t = 0; t < AvailableHeroes.Count; t++)
{
if (AvailableHeroes[t].name == SelectedCards[i].name)
{
Debug.Log(AvailableHeroes[t]);
// Instantiate(AvailableHeroes[t], PlayerSpawnLocation[t].transform.position, transform.rotation);
}
{
}
}
}
}
This script checks for amount of selected hero cards and puts it against my list that has all the available heroes to choose from(prefabs).
The debug.log shows that only the correct heroes get called.
Instantiate ends up spawning a loot of heroes instead of the selected amount.
For clarity I attach full class:
{
private int playerSize; //amount of choices for card selection
private GameManager GM;
[Header("Lists for Spawning in Heroes")]
public List<GameObject> SelectedCards;
public List<GameObject> AvailableHeroes;
public List<Transform> PlayerSpawnLocation;
[Header("Canvas used for the game")]
public Transform GameCanvas;
public Transform CharacterCanvas;
//When scene starts it takes how many players will be picking a card.
void Start()
{
//connects this script with gamenmanager to be able to manipulate the cameras
GM = GameObject.Find("GameManager").GetComponent<GameManager>();
//gets playersize information from main menu selection
PlayerPrefs.GetInt("PlayerSize");
playerSize = PlayerPrefs.GetInt("PlayerSize");
SelectedCards = new List<GameObject>();
//enables/disables correct canvas not to cause any problems when we initiate this scene
GameCanvas.gameObject.SetActive(false);
CharacterCanvas.gameObject.SetActive(true);
}
// Update is called once per frame
void Update()
{
if (playerSize <= 0)
{
Placement();
GM.CharacterSelectionCamera.enabled = false;
GameCanvas.gameObject.SetActive(true);
CharacterCanvas.gameObject.SetActive(false);
GM.BattleCamera.enabled = true;
}
}
public void PlayerSelected(int cardPicked)
{
playerSize -= cardPicked;
}
private void Placement()
{
for (int i = 0; i < SelectedCards.Count; i++)
{
for (int t = 0; t < AvailableHeroes.Count; t++)
{
if (AvailableHeroes[t].name == SelectedCards[i].name)
{
Debug.Log(AvailableHeroes[t]);
// Instantiate(AvailableHeroes[t], PlayerSpawnLocation[t].transform.position, transform.rotation);
}
{
}
}
}
}
}
I hope someone can explain where I am going wrong with this.
Thanks,
I got the answer, I guess I was just being tired from working and could not see the obvious.
For those who wonder what solution is
The method gets called each frame thus it continues to endlessly spawn objects
There are 2 ways to fix it
1 Make coroutine and then return after you make your initial batch
2 Use a boolean at update so not only it checks player size but also whenever it can spawn it or not, you set the boolean to false after method get called.
I did not even notice the update function part.
Just a heads up, in your start function, PlayerPrefs.GetInt("PlayerSize"); is not doing anything since the value is not saved anywhere.

Multiple references to a Ball object in Unity

I am making a game like pong with multiple power-ups. One of them is to have a "Triple Ball" power-up. I tried just creating another reference of the ball, but that doesn't seem to work. I figured this would work because I mostly work with Java where I can just create another instance. Here is how I tried to do it, I tried testing through just clicking a button:
public class TripleBall : MonoBehaviour {
public Ball firstBall;
private int amountOfBalls = 2;
private Ball[] ballArray;
private bool start, avail, located;
void Start () {
ballArray = new Ball[amountOfBalls - 1];
for (int i = 0; i < ballArray.Length; i++)
ballArray[i] = new Ball();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.B))
start = true;
if (start)
{
//Begin locator: Makes it so when the balls spawn they spawn where the first ball
if (!located) {
for (int i = 0; i < ballArray.Length; i++)
{
ballArray[i].transform.position = firstBall.transform.position;
}
located = true;
}
//End locator : if statement and loop
}
}
}
But it seems I can't do this because Ball is of type MonoBehavior.
Question: Is there any way to do this the way I planned or any way at all? Thanks in advanced!
You really don't use new to create an instance. The only place you are right in your code is using new to initialize array. After that, you are supposed to use GameObject.AddComponent to create a new instance instead of the new keyword. This is because Ball class derives from the MonoBehaviour.
You Ball class derives from MonoBehaviour.
public class Ball : MonoBehaviour
{
}
Here is your code fixed:
private Ball[] ballArray;
void Start()
{
ballArray = new Ball[amountOfBalls - 1];
for (int i = 0; i < ballArray.Length; i++)
ballArray[i] = gameObject.AddComponent<Ball>();
}
Assuming that your Ball class looks like the code below and does not inherit from MonoBehaviour:
public class Ball
{
}
Then code in your question would be valid and using new is the right way.
You need to use instantiate. It is derived from Unity's Object class, so assuming "ball" inherits from either Object or GameObject, this is what you want. You can find more info about it here: http://docs.unity3d.com/ScriptReference/Object.Instantiate.html

Categories

Resources