#Unity basic OnDestroy
1 messages · Page 1 of 1 (latest)
// In the Player script
private GameObject toDestroy;
private void OnDestroy()
{
toDestroy = GameObject.Find("nameOfObject");
Destroy(toDestroy);
}
https://docs.unity3d.com/ScriptReference/GameObject.Find.html
toDestroy can hold a reference to a game object
void OnDestroy() can be used on any MonoBehaviour class, and will be called when the object is destroyed.
GameObject.Find() will find an Active game object in the current scene
Destroy() will destroy a game object
It is possible to do this with less code, if that is the only thing that needs to happen to the object
private void OnDestroy()
{
Destroy(GameObject.Find("nameOfObject"));
}
**This is a valuable link to bookmark: **
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
Do you have any questions?
umm
i understood but
how about
how do i replace this with another object when the level is complete
im sorry if im starting to annoy you
i really dont understand
It's best if you explain the practical idea of what you are trying to achieve, instead of code
okay so im making this maze game where after every "level" the maze gets bigger and the "goal" changes.
the progress i have done till now is, I have made the maze, the maze gets bigger everytime the next level comes, but the object is constant
"1" is the goal, it has to become 4 after the player reaches 1
What sort of components does this 1 have?
the object
does the ball visually collide with it?
or is there a trigger box
the ball uses wasd to move and collide with the 1
please answer each question
the 1 is just an object which is assigned to the main code
it obviously has components
I need to know which
do you know what a component is?
on the right side -->
So far, are you destroying 1 when colliding with it?
Yes / No?
I don't have all day
no
by colliding with 1 ?
yes
Show me the code for that
its on #💻┃code-beginner
Post it again
First off, you don't need to actually destroy game objects which are going to be used again.
It is enough to simply disable them, by using SetActive(false);
This is noticeably better for performance. In groups, this practice is called Object Pooling.
So instead of using the OnDestroy() event, you can use OnDisable()
okay
Second, I'm not able to immediately understand the code you've written.
So far, I have been using the physics system for its ease-of-use functionalities.
But that shouldn't be a problem if you understand how to modify it yourself.
okay.
I believe you can use Raycast to find the other object you're colliding with
However
There is a creative way or two to achieve what you need, with a bit more elegant solution
??
No, OnDisable is a function called by the UnityEngine
child.gameObject.SetActive(false);
Since you are only disabling them, you can keep all of them in a List
i dont understand..
Ah, there is a reason for that
Go into #854851968446365696
and follow a guide for Configure IDE
so do i download all of this?
IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other
No. The readme section has one guide for each of the separate instances possible.
Choose the one that fits your situation.
and it's not a download, it's a guide for how to configure Visual Studio to recognize Unity
Once you are done the text MonoBehaviour in your class name should highlight green
then there's a lot of other stuff that will become apparent
no idea, haven't used it
VS Community is recommended for beginners
Rider might be better - ask in the channel
no thats fine ill get vs community instead
2022 released in November. It's pretty good.
I have to run soon, but I can be back later
okay. thanks for the help.
You're welcome.
Some stuff before I go:
Your player should have a reference to the Parent of those numbers
then do a Foreach Transform child in Parent
and add them to a List
The parent itself can be the object you detect
private List<GameObject> numbers = new List<GameObject>(); // it's ok to initialize a new List in the declaration of a List
private int index;
// When disabled
// Disable current number
numbers[index].SetActive(false);
// Increment number index
index += 1;
// if index exceeds number of indexes
if(index == numbers.Count)
{
// Reset loop // or whatever you want to do
index = 0;
}
// Enable new number
numbers[index].SetActive(true);
This is not a copy paste solution
but if you learn enough of the basics, they are very good instructions
almost all the code you need
tysm
These two lines do the same btw.
I used the most obvious one in the code, but the shorter one is preferred.
index++;
index += 1;
okay
Whenever you need more help, you may refer to this thread if it's still relevant to your current question
But please make sure that your IDE is configured, and that you try to explain as best you can. There are a lot of good helpers around, if the questions are well laid out.
thanks so much
Have a nice day o/
you too 🙂
rovsau i really made 0 progress
and i have to make the game and submit it in an hour
i dont know what to do ;-;
im gonna be honest i have no idea what any of the code means or where to put it or what to do with it
I really would like help right now
Since you have a deadline and stuff, I assume you are a student.
What instructions were you given?
absolutly no instructions
they asked me to make a math game
so im trying to make a "number" to the power of 2 maze
how long time did you have?
3 days but i started today
all the other students are using game templates and scratch
does anyone there know what it entails to create a game?
well, if you ever needed a deadline extension, it would be for making a game
im afraid i cant do that..
And you have 15 minutes?
that's more realistic
I see
In your script, create a comment line above code segments, or lines, which explains in plain English what is going on - to the best of your ability
spend a few minutes on that
I'll help you make it with the physics system instead, which is what you really need to be doing at your level and with your allotted time.
okay on it
explain in practical terms what you want - the idea
okay you know how i want the goal (end point) to change numbers from 1 to 4 to 9 and so on
Yes
im making a parent called number
and inserting all the number images as children
i want all of the children to follow the parents coordinates
Children always follow the parent transform, rotate and scale along with it.
Explain to me the idea behind the numbers again
the pictures of the numbers are children and the "numbers" object is the parent
I mean just the numbers - what's the point with them
when the first level begins only the first picture will be enabled
the second level - the 2nd picture and so on
Yes, but why the numbers? Are you following some sort of formula?
what's the significance of that formula?
the topic is squares and square roots but im only doing squares
google says Square Numbers
alright
You can make a better solution
instead of using a sprite or image to render the number
you can use a UI Text component
only one object, which when triggered, will increment the formula, and display the next number
okay i did not think about that
I just need to see the commented script of yours, so I know what to recreate
I will make sure you learn something, but also try to keep it short in terms of time, since it's very late.
for scripts
I'll be writing stuff to make sure it works, then tell you how it works and how to do it
should be simple enough
I don't expect that many lines of code for this
you need to save the paste and get the link
CTRL+S works for gdl
comment indents should be on the same level as the line below them
this is fine for now
// map generation
What does this do in practical terms? Are you procedurally generating the level?
for what? I don't see it anywhere
to what is it applied?
I'm not familiar with implementations of noise though
nah i dont think i know
What I see is a level, a player ball, and a number goal
yes..
Then it's simple
okay what now rovsau?
I'm typing some stuff out. Might be another 5-10min
okay.
Alright
using System;
using UnityEngine;
using TMPro;
public class NumberScript : MonoBehaviour
{
private TMP_Text numberText;
private int number;
private void Awake()
{
numberText = GetComponent<TMP_Text>();
IncrementNumber();
}
private void IncrementNumber()
{
number++;
numberText.text = Math.Pow(number, 2f).ToString();
}
private void OnTriggerEnter2D(Collider2D collision)
{
IncrementNumber();
}
}
This is the script for the number
Create a new UI TextMeshPro Text object
Hierarchy -> Right Click -> UI > Text - TextMeshPro
Just do that, we'll move on to the Player script
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
private Vector3 spawnPosition;
private void Awake()
{
spawnPosition = transform.position;
}
private void OnTriggerEnter2D(Collider2D collision)
{
transform.position = spawnPosition;
}
}
This is the script without movement
I will now explain what types of components we are going to use
You can duplicate the scene, and work in the copy
it's always nice to back things up
kay
the Physics system works by handling objects with Colliders (you must add the component yourself)
Game Objects with colliders will collide, as long as they are on Layers which can collide (options for later stuff)
For forces to be added, the object needs a Rigidbody, which means the object attached will react to Gravity and you can apply Forces to it, in whatever direction you need
okay.
I'm not sure how you set up your ball and walls,
but you should add a BoxCollider2D to the walls.
If it's set up properly, they should auto-size.
colliders are represented by green lines
in scene view
okay what do i do now?
the walls all have colliders?
do I fit it to the shape of the wall?
okay..
so on the player, add a CircleCollider2D for now
we can try PolygonCollider after we fix movement
done
why does the image move with the collider green boundaries
they are part of the same object - their Positions are relative to the Transform Position
ah right, wait
you mean in Play mode?
nono im trying to adjust the circle but
ohkay nvm
are you just adjusting the Radius?
i figured it out
replace the existing content of the class, with the following
private Vector3 spawnPosition;
private Rigidbody2D rb;
private void Awake()
{
spawnPosition = transform.position;
}
// Update is called per Visual Frame
private void Update()
{
}
// Update is called once per Physics Tick
private void FixedUpdate()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
transform.position = spawnPosition;
}
done..
Read the comments above Update and FixedUpdate
We will check for input in Update (visual frames)
Flip a bool, and execute in FixedUpdate
okay
standard approach
there is a Rigidbody2D rb field - do you know how it should be referenced?
no.
bookmark this:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
done
components on the same game object, should be referenced in Awake
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
awake means?
for referencing components of Other objects, it should be done in Start(), which runs After every other game object present has awoken
Read the MonoBehaviour link - it explains in few words
if (Input.GetKeyDown(KeyCode.W);
{
}
this is how you check for input on specific keys
GetButtonDown is different, it uses words that can be specified in the Input Settings
kay
But we can opt for a more simple solution, actually, if you want to save even more time
yep
We can use GetAxis or GetAxisRaw
read about them
I need a minute to think
Since they are tied directly to a dynamic input, it is okay to reference it directly in FixedUpdate, if I recall correctly
okay
Create these fields
private float speed;
private Vector3 direction;
where??
in the Player script
private void FixedUpdate()
{
direction = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0f);
rb.AddForce(direction * speed, ForceMode2D.Force);
}
done
oh, and give speed a value, like 5
private void FixedUpdate()
{
direction = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0f);
rb.AddForce(direction * 5, ForceMode2D.Force);
}
???
kay
Once you've done this. Post a gdl link to a copy of your script as it is now.
I hope you have your class declaration and stuff in the script
public class Player : MonoBehaviour
everything in the script file is relevant, but for now, good
you forgot to reference the Rigidbody component in Awake
oh
wait the fixedupdate is good?
except AddForce
so, when that's done
go to the Number object, and in the Collider component, check the isTrigger checkbox to True
wait
is this an exact copy of your script?
yep
Then I believe Visual Studio has errors
using UnityEngine;
public class Player : MonoBehaviour
{
private Vector3 spawnPosition;
private Rigidbody2D rb;
private float speed = 5f;
private Vector3 direction;
private void Awake()
{
spawnPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
}
// Update is called per Visual Frame
private void Update()
{
}
// Update is called once per Physics Tick
private void FixedUpdate()
{
direction = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0f);
rb.AddForce(direction * speed, ForceMode2D.Force);
}
private void OnTriggerEnter2D(Collider2D collision)
{
transform.position = spawnPosition;
}
}
oh..
this is how it should look
Yes, good.
oh kay
Now you can test this in play mode
deactivate the old scripts
Speed might be a bit low, not sure how movement will be
and right now we are pushing the circle, instead of rotating it with friction
wait you said something about changing is trigger
did you Save the script?
You can double click the warnings to get to where they are
Did any of your old scripts manage the world / level somehow?
go into scene view, screenshot
the map generation
wait a minute
i delete the other script
but i have a copy
okay
this is the script
hmm
do you have the source for just the map generation?
alternatively - manually construct it in the scene
I'm not sure how it's supposed to work or be great for whatnot 🤷♂️
we could probably seperate the code we recognize and not the code about map generation
if you can completely remove anything related to player movement, and collision check
that would work
it should only generate the map
and if it needs to do something - you can make a public function for it -
but try to rush this, because we're almost finished :)
yesss
ahh
it contains the player position and goal position
so that it could make the thing harder
it can be adapted. I'm just a bit limited on energy now
try to just make it generate the basic level
first
okay
keep everything else //commented away
basic maze generator?
yeah, just make it create a single level, regardless of parameters
so we can make it function
after, if there's time, we can adapt it to increase difficulty based on the Player's properties*
if it's too difficult right now, just manually set up a level by duplicating and changing the prefab objects
do we have a track on levels?
If you mean Counter, that's easy to add
yep we might need that
does the code work?
i think it does
You need to make sure the level spawns, that you can move, and that the trigger both changes the number and moves the player back to spawn
yea thats the problem
it thinks the level is present in the old code
and it has the gameobject as the transform
but the old stuff is gone
so you didn't duplicate your scene, as I suggested
i have a backup
okayyyyyy nvm
the game code applys to both
but i have a copy of the code
its fine
Alright
I'm gonna watch Star Trek while you fix the level :)
got two monitors, so I'm reading
okay
hey what about the umm level tracker thing
counter
It's very simple, so just fix the level first
if we finish this fast enough, I can help you add Game Time Elapsed and FPS as well as level count
ahh
i dont know what the problem is
what do i do with "transform child in what"
nah i think the level system is necessary for the code to work
no wait a minute
it instantiates the level objects with Level as the Parent
every time it runs Start() it will delete the previous level and generate a new one
by deleting the children of Level
Level is an empty game object - the variable references its Transform component, instead of a GameObject type
did you delete the last end bracket? }
nope
post script
its saved?
what?
idk..
I need to see the code to understand what's wrong
oh ok
its late here
my brains not working
know the feeling
Remove the last bracket
then we dont have the same scripts - what are the errors?
i put the bracket back in
and it shows the same error
type or namespace defeinition thing
I copied your entire script into one of my own - saw the error - removed the last bracket - all good
ohkay nvm
it works
but the walls are bugged
they are flickering
well, then I don't know what to do - I don't have the time or energy to reverse-engineer that code
the only solution I know - make a custom level
it takes minutes
we've been trying to fix this for an hour
..
fair enough then
ill make ten custom levels
solid
whats a prefab
okay
it is a Prefab - predefined object or whatnot
once you place copies of it in the scene, their attributes can be changed, and be individual - until you apply Overrides from the Prefab to the Copies or from a Copy to the Prefab
once you have one in the scene, just duplicate that
give walls a high X scale
floor and ceiling a high Y scale
and you've got yourself a house
No, you just don't let it be a component of any object in the scene
no need to delete the asset itself
it can be dormant
Note: A MonoBehaviour script must be a component of a game object, which makes it an instance of that MonoBehaviour (or script)
you can write one mono script and use it on 100++ game objects or more
they will have each their own instance
hm, isn't it tilted the wrong way?
easy to fix:
huh?
with Rigidbody there is gravity, but it can be turned off
gravityScale = 0f
or Physics2D.gravity = Vector3.zero
why is everything dark when i turn on the game
game and the script you made
wasn't game supposed to be disabled?
I don't see a Player object in the scene
Alright. Good night.
i dont think i can submit the project tmr
good night
If you make a new scene, set up Level, Player and Number
and add the two scripts
it will work