#Unity basic OnDestroy

1 messages · Page 1 of 1 (latest)

elfin drift
#

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"));
}
#

Do you have any questions?

past bluff
#

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

elfin drift
#

It's best if you explain the practical idea of what you are trying to achieve, instead of code

past bluff
#

"1" is the goal, it has to become 4 after the player reaches 1

elfin drift
#

What sort of components does this 1 have?

#

the object

#

does the ball visually collide with it?

#

or is there a trigger box

past bluff
#

the ball uses wasd to move and collide with the 1

elfin drift
#

please answer each question

past bluff
elfin drift
#

it obviously has components

#

I need to know which

#

do you know what a component is?

#

on the right side -->

past bluff
elfin drift
#

So far, are you destroying 1 when colliding with it?

#

Yes / No?

#

I don't have all day

past bluff
past bluff
#

im destroying the player

#

the ball

elfin drift
#

by colliding with 1 ?

past bluff
#

yes

elfin drift
#

Show me the code for that

past bluff
elfin drift
#

Post it again

past bluff
elfin drift
#

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()

past bluff
#

okay

elfin drift
#

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.

past bluff
#

okay.

elfin drift
#

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

elfin drift
#

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

past bluff
elfin drift
#

Ah, there is a reason for that

past bluff
#

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

elfin drift
#

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

past bluff
#

okay understood

#

how do i get JetBrains Rider again??

elfin drift
#

no idea, haven't used it

#

VS Community is recommended for beginners

#

Rider might be better - ask in the channel

past bluff
#

no thats fine ill get vs community instead

elfin drift
#

2022 released in November. It's pretty good.

#

I have to run soon, but I can be back later

past bluff
#

okay. thanks for the help.

elfin drift
#

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

past bluff
elfin drift
#

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;
past bluff
#

okay

elfin drift
#

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.

past bluff
#

thanks so much

elfin drift
#

Have a nice day o/

past bluff
#

you too 🙂

past bluff
#

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

elfin drift
#

Since you have a deadline and stuff, I assume you are a student.
What instructions were you given?

past bluff
#

they asked me to make a math game

#

so im trying to make a "number" to the power of 2 maze

elfin drift
#

how long time did you have?

past bluff
#

3 days but i started today

#

all the other students are using game templates and scratch

elfin drift
#

does anyone there know what it entails to create a game?

past bluff
#

i just wanted to stand out as a student

#

you know what im talking about>

elfin drift
#

well, if you ever needed a deadline extension, it would be for making a game

past bluff
#

im afraid i cant do that..

elfin drift
#

And you have 15 minutes?

past bluff
#

eh i can extend that

#

the deathline is in 12 hours

#

and its almost midnight

elfin drift
#

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.

past bluff
#

okay on it

elfin drift
#

It means code will be more simple

#

Example of simple commenting:

past bluff
#

wait i just want you to clear a doubt

#

how do i make a follow code?

elfin drift
#

explain in practical terms what you want - the idea

past bluff
#

okay you know how i want the goal (end point) to change numbers from 1 to 4 to 9 and so on

elfin drift
#

Yes

past bluff
#

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

elfin drift
#

Children always follow the parent transform, rotate and scale along with it.

#

Explain to me the idea behind the numbers again

past bluff
#

the pictures of the numbers are children and the "numbers" object is the parent

elfin drift
#

I mean just the numbers - what's the point with them

past bluff
#

when the first level begins only the first picture will be enabled

#

the second level - the 2nd picture and so on

elfin drift
#

Yes, but why the numbers? Are you following some sort of formula?

past bluff
#

yea

#

1^2 = 1

#

2^2 = 4

#

1,4,9,16 so on

elfin drift
#

what's the significance of that formula?

past bluff
elfin drift
#

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

past bluff
elfin drift
#

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.

past bluff
#

okay

#

how do i paste the whole program?

elfin drift
#

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

past bluff
#

okay..

#

i pasted it over there

elfin drift
#

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

past bluff
elfin drift
#

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?

past bluff
#

noise map generation?

#

i remember working with noise nodes

#

in the graph

elfin drift
#

for what? I don't see it anywhere

#

to what is it applied?

#

I'm not familiar with implementations of noise though

past bluff
#

nah i dont think i know

elfin drift
#

What I see is a level, a player ball, and a number goal

past bluff
#

yes..

elfin drift
#

Then it's simple

past bluff
#

okay what now rovsau?

elfin drift
#

I'm typing some stuff out. Might be another 5-10min

past bluff
#

okay.

elfin drift
#

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

past bluff
#

okay

#

do i delete the numbers?

#

the images?

elfin drift
#

You can duplicate the scene, and work in the copy

#

it's always nice to back things up

past bluff
#

kay

elfin drift
#

and save save save in Unity

#

if you run an infinite loop script, Unity will crash

past bluff
#

kay

#

how do i make a backup?

#

ok i think i did it

elfin drift
#

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

past bluff
#

okay.

elfin drift
#

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

past bluff
#

okay what do i do now?

elfin drift
#

the walls all have colliders?

past bluff
#

wait a minute

#

okay walls got boxcollider2d on it

elfin drift
#

you should probably resize the collider to fit the sprite

#

Edit Collider -button

past bluff
#

do I fit it to the shape of the wall?

elfin drift
#

yes

#

or you will be walking above the floor, so to speak

past bluff
#

better?

elfin drift
#

Yes

#

Alright, then apply overrides, so the prefabs in the scene are updated

past bluff
elfin drift
#

Probably fine

#

in the worst case, you won't really need it for the game to function

past bluff
#

okay..

elfin drift
#

so on the player, add a CircleCollider2D for now

#

we can try PolygonCollider after we fix movement

past bluff
#

done

elfin drift
#

add a Rigidbody2D

#

adjust the CircleCollider so it matches the ball somewhat

past bluff
#

why does the image move with the collider green boundaries

elfin drift
#

they are part of the same object - their Positions are relative to the Transform Position

#

ah right, wait

#

you mean in Play mode?

past bluff
past bluff
#

ohkay nvm

elfin drift
#

are you just adjusting the Radius?

past bluff
#

i figured it out

elfin drift
#

kk

#

so now create PlayerScript

past bluff
elfin drift
#

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;
}
past bluff
#

done..

elfin drift
#

Read the comments above Update and FixedUpdate

past bluff
#

per visual frame and per physics tick

#

understood

elfin drift
#

We will check for input in Update (visual frames)
Flip a bool, and execute in FixedUpdate

past bluff
#

okay

elfin drift
#

standard approach

#

there is a Rigidbody2D rb field - do you know how it should be referenced?

past bluff
#

no.

elfin drift
past bluff
#

done

elfin drift
#

components on the same game object, should be referenced in Awake

private void Awake()
{
    rb = GetComponent<Rigidbody2D>();
}
past bluff
#

awake means?

elfin drift
#

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

past bluff
#

understood

#

yep read it

#

Awake is called when the script instance is being loaded.

elfin drift
#
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

past bluff
#

kay

elfin drift
#

But we can opt for a more simple solution, actually, if you want to save even more time

past bluff
#

yep

elfin drift
#

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

past bluff
#

okay

elfin drift
#

Create these fields

private float speed;

private Vector3 direction;
past bluff
#

where??

elfin drift
#

in the Player script

past bluff
#

okay

elfin drift
#
private void FixedUpdate()
{
    direction = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0f);

    rb.AddForce(direction * speed, ForceMode2D.Force);
}
past bluff
#

done

elfin drift
#

oh, and give speed a value, like 5

past bluff
#

???

elfin drift
#

That's how your FixedUpdate should look

#

I will explain how it works

past bluff
#

kay

elfin drift
#

Once you've done this. Post a gdl link to a copy of your script as it is now.

past bluff
elfin drift
#

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

past bluff
#

oh

elfin drift
#
private float speed = 5f;
#

do this, and replace 5 in AddForce with speed

past bluff
#

wait the fixedupdate is good?

elfin drift
#

except AddForce

past bluff
#

yep

#

yep

#

thats what your talking about

elfin drift
#

so, when that's done

past bluff
elfin drift
#

go to the Number object, and in the Collider component, check the isTrigger checkbox to True

#

wait

elfin drift
past bluff
#

yep

elfin drift
#

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;
    }
}
past bluff
#

oh..

elfin drift
#

this is how it should look

past bluff
#

same thing?

elfin drift
#

Yes, good.

past bluff
#

oh kay

elfin drift
#

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

past bluff
#

wait you said something about changing is trigger

elfin drift
#

ah yes

#

on the Number object

#

Collider isTrigger = True

#

in the inspector

past bluff
elfin drift
#

did you Save the script?

past bluff
#

nvm errors are gone now but this showed up

elfin drift
#

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

past bluff
elfin drift
#

you can activate that part

#

was it separate?

past bluff
#

wait a minute

#

i delete the other script

#

but i have a copy

#

okay

#

this is the script

elfin drift
#

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 🤷‍♂️

past bluff
#

we could probably seperate the code we recognize and not the code about map generation

elfin drift
#

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 :)

past bluff
#

yesss

#

ahh

#

it contains the player position and goal position

#

so that it could make the thing harder

elfin drift
#

it can be adapted. I'm just a bit limited on energy now

#

try to just make it generate the basic level

#

first

past bluff
#

okay

elfin drift
#

keep everything else //commented away

past bluff
#

basic maze generator?

elfin drift
#

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

past bluff
#

do we have a track on levels?

elfin drift
#

If you mean Counter, that's easy to add

past bluff
#

yep we might need that

elfin drift
#

first, we need the level to exist, so we can check movement

#

and trigger

past bluff
#

okay

#

yep

#

this is the new code

#

we just need a level counter

#

as a transform

elfin drift
#

does the code work?

past bluff
elfin drift
#

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

past bluff
#

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

elfin drift
#

so you didn't duplicate your scene, as I suggested

past bluff
#

okayyyyyy nvm

#

the game code applys to both

#

but i have a copy of the code

#

its fine

elfin drift
#

Alright

#

I'm gonna watch Star Trek while you fix the level :)

#

got two monitors, so I'm reading

past bluff
past bluff
#

hey what about the umm level tracker thing

#

counter

elfin drift
#

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

past bluff
#

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

elfin drift
#

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

past bluff
#

what does that mean

elfin drift
#

did you delete the last end bracket? }

past bluff
#

nope

elfin drift
#

post script

past bluff
#

its saved?

elfin drift
#

what?

past bluff
#

idk..

elfin drift
#

I need to see the code to understand what's wrong

past bluff
#

its late here

#

my brains not working

elfin drift
#

know the feeling

past bluff
elfin drift
#

Remove the last bracket

past bluff
#

oaky

#

done

#

that just gives me more errores

elfin drift
#

then we dont have the same scripts - what are the errors?

past bluff
#

and it shows the same error

#

type or namespace defeinition thing

elfin drift
#

I copied your entire script into one of my own - saw the error - removed the last bracket - all good

past bluff
#

it works

#

but the walls are bugged

#

they are flickering

elfin drift
#

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

past bluff
#

ill make ten custom levels

elfin drift
#

solid

past bluff
#

another question

#

how?

elfin drift
#

drag the prefab into the scene

#

it will create a copy of it

past bluff
#

whats a prefab

elfin drift
#

the wall object in your Assets

#

blue icon

past bluff
#

okay

elfin drift
#

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

past bluff
#

okay

#

do i just delete the game code?

elfin drift
#

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

past bluff
elfin drift
#

they will have each their own instance

#

hm, isn't it tilted the wrong way?

#

easy to fix:

past bluff
elfin drift
#

In this level, you must jump

#

in the other, you just walked

past bluff
#

its a maze

#

and a ball

#

it dont jump

#

its 2d

elfin drift
#

with Rigidbody there is gravity, but it can be turned off

#

gravityScale = 0f

#

or Physics2D.gravity = Vector3.zero

past bluff
#

why is everything dark when i turn on the game

elfin drift
#

What other scripts are running?

#

how is the camera set up?

past bluff
#

game and the script you made

past bluff
#

cinemachine

elfin drift
#

wasn't game supposed to be disabled?

past bluff
#

yes

#

okay i

elfin drift
#

I don't see a Player object in the scene

past bluff
#

might need to get some sleep

#

its 1: 10 am over here

elfin drift
#

Alright. Good night.

past bluff
#

i dont think i can submit the project tmr

past bluff
elfin drift
#

If you make a new scene, set up Level, Player and Number
and add the two scripts
it will work