#💻┃code-beginner

1 messages · Page 313 of 1

summer stump
#

I don't see any debug.logs here

glass ivy
summer stump
#

Are you using breakpoints?

deft grail
#

create a timer for 5 seconds then you can use built in MoveTowards or create your own

glass ivy
#

't use debug log, i use this fancy thing

summer stump
glass ivy
#

non-suspend breakpoint

misty coral
#

how can I "deactivate" them

#

for the time frame

summer stump
misty coral
#

here is the code that is constantly pulling the object to one of two position, below this code I have

#

A call to recoil animation

#

which

glass ivy
misty coral
#

but only for a single frame rn

slender nymph
misty coral
# deft grail show the code

I basically need a way to deactivate those methods constantly dragging the object in update... But I dont really understand what is truly happening when I call recoilAnimation(), is it cycling every second with Update()? Or is it running independently...

#

Like can I use a boolean to disable those if checks for the duration that recoilAnimation() is running, and after it leaves I set the boolean back to true, and those if checks can be accessed again

summer stump
#

Just to be clear, am I reading the chart right?
It can be kinematic AS LONG as the kinimatic rb is attached to the trigger.
A kinematic non-trigger collider won't send OnTrigger with a static trigger collider.

slender nymph
#

no, kinematic rigidbody sends OnTrigger to static trigger. it's only two static triggers or no triggers at all that don't produce OnTrigger messages

glass ivy
#

what's strange is that the trigger works but other.attachedRigidbody is always null

slender nymph
#

well for starters, why are you null checking the way that you are?

summer stump
slender nymph
#

yep, no worries

glass ivy
#

i don't like the wiggle that rider puts on ?. because it bypasses unity funky object lifecycle, yeah i'm as autistic as you guys 😉

slender nymph
#

i was referring to the way you were doing null checks in your actual code using the is operator

#

because that bypasses unity's overloaded == operator for null checks as well

#

anyway, if attachedRigidbody is null then the object that this component's collider is overlapping does not have a rigidbody

north kiln
#

Really shouldn't be bypassing the check unless you understand it very well

#

Also, use TryGetComponent

tidal kettle
#

hi, i am making a bullet and enemy script in which everything is working however the bullet pushes the enemy around due to its speed. just wondering, should i set the bullet to a trigger or pursue a different solution?

glass ivy
north kiln
#

is {} bypasses the null check

glass ivy
glass ivy
slender nymph
#

apparently not. this is where unity's Debug.Log comes in handy. you can Debug.Break and then print a log that you pass other in as the context object so that when you select the log in the console it highlights that object

slender nymph
glass ivy
#

tsss, nope because i'm pooling. alright time to call it a night

#

tsss*2 it was that:
it deactivated the bullet for pooling which apparently nulls the .attachedRigidbody even tho it still exists... must be deregistering it from physx before the end of the physx update... must be because i have auto sync on.

#

alright it's working now

#

and being able to change code while it's playing is awesome

#

thanks @slender nymph @north kiln

#

this is really cool, how do i add to the input system?

#

things i found out while digging VR

whole idol
#

why am I getting an error here?

#

should I be importing Random ?

gaunt ice
#

why you have static void Main?

whole idol
gaunt ice
whole idol
#

Now I dont have one

whole idol
#

and still dont understand what to do

#

I removed the static void Main class

#

I have my Random random declared in the Update now

gaunt ice
#

static void Main is another issue, now the website tells you how to how ambiguous reference

whole idol
#

yeah I know

#

but I still dont get it

whole idol
#

wait

#

should i be using this?

#

this also could work i guess

grizzled zealot
#

programwise, what's smarter? To return a dictionary<string, float> and then look up keys or to return a large tuple tuple<float, float, ..., float> and knowing on what position you have what value?

The problem is with the dictionary, I have to deal with the possibility that I don't have the key in there. With the tuple I have to deal with knowing the precise position of the value.

whole idol
#

cool

#

but.. I can not use that either

gaunt ice
gaunt ice
#

you use string as key to find a float but you then told me you find it in "a list" of float (access by index)==you already have the float, i dont know what you want to do=>need more info

whole idol
#

lol

gaunt ice
#

You dont know where to put, put the example code inside a method and use it

acoustic arch
#

anyone got any tips for how I could program my card abilities? itll have many different abilities so I was wondering if they should each be their own class or a struct etc

static bay
#

Dictionary or List.

small mantle
#

I am dealing with a array of GameObjects. There are a total of 3 Objects in it and I am constantly switching between them. I don't like checking which is active with```cs
GameObject characterCollection[];

void Update(){
if (characterCollection[0])
{
print("Human");}
if (characterCollection[1])
{
print("Monster");}
if (characterCollection[2])
{
print("Alien");
}}

winged gazelle
static bay
#

Then use that field.

small mantle
static bay
#

GameObject activeCharacter

small mantle
# static bay ``GameObject activeCharacter``

I am using that system, but I may be doing it weirdly. This is what I usually check cs if (activeCharacter == characterCollection[0]){ print("Human"); } Now I don't know if I am using it wrong?

static bay
#

And then do print(activeCharacter.name)

small mantle
#

!Code

eternal falconBOT
static bay
#

Have a method that handles the switching.

#

Do all the setup you want in there.

#

Set activeCharacter

#

use active character

small mantle
#

So instead check the name?

charred spoke
#

Have the same script on all objects. Have that script define an enum with all character types. Then GetComponent from the objects and check the type. Dont check names since that is fragile and prone to errors

static bay
#

is it just debug or actual gameplay relevant

charred spoke
#

Ok…

small mantle
#

I am having such a trouble trying to make my system more readable. I have 3 Objects, 1 that is default Character, 1 that is overcharged version of default Character, and 1 that is Machine Character that is completely different. Lets call the 2 Characters that are default similar to "Modes" and the Machine "Machine". When Mode 1 (Default Character) gets a charge variable up to a fixed number, it will change into Mode 2 (Overcharged Default Character). After a 10 seconds it is back to Mode 1.

Now, I want to check everytime Mode 2 was achieved, so I added a counter that was added everytime Mode 1 was changed into Mode 2. If this counter is 3 then I want the Player to be able to Press 'T' to change into Machine.

In Summary: I need help with making the code easily readable.

gaunt ice
#

then you count the number of times that "a charge variable up to a fixed number"

gaunt ice
#

oh isee

#

just use enum instead of some magic numbers

misty coral
#

How can I moveToward() a child object

#

when I try to do it the parent just doesnt move

summer stump
gaunt ice
#

And your child object world position depends on parent object

acoustic arch
#

hey does anyone have any tips for how to make a system for abilities in my game? ranging from healing attacking or etc?

#

structs, interface?

gaunt ice
misty coral
#

but the whole point of the child is because it allows me to keep track of a position always a certain amount behind the parent

#

how do I move the child behind itself

summer stump
misty coral
#

Ok so

summer stump
#

Do you want to move the parent toeards the child?

misty coral
#

I want the object to move backward when I click the mouse button

#

so I made a child thinking it could always be behind the object, and I could move to it

gaunt ice
#

Then you shouldnt use tree, you parent depend on child but your child depends on parent
Use transform.forward/right/up

misty coral
#

If I want the object to move x distance backwards, how do I keep track of it with transform.forward?

summer stump
gaunt ice
#

Transform.forward is direction not position

misty coral
#

A quantifiable number I can keep track of

summer stump
misty coral
#

I forgot to mention the object is tied to the player

gaunt ice
#

You want your object move in speed x m/s then use move towards to find the position (direction*speed, amount is time.dt) and assign it back to tf.pos

summer stump
gaunt ice
#

Direction wont be changed unless the rotation is changed

misty coral
gaunt ice
#

Then use vec3.forward, it is dir in world space

misty coral
#

man this is so weird

#

forward goes forward

#

but -forward goes to the right

#

it also seems dependent on which way my character moves....

#

like if I move to the right it goes to the right

#

oh nvm

#

vector3.forward is based on the grid

summer stump
misty coral
#

maybe you guys could catch this if i showed like a vid or something

#

This is the code for me trying to move the obj backwards(up is backwards because I rotated it )

gaunt ice
#

2d top down game?

misty coral
#

3d

ruby python
#

Mornin' all, I have a character with animations attached, but I would like it to 'bend' at the waist for the up and down mouselook. But the Animations take priority, so the mouselook has no effect. Is there a way to 'override' the animation on that bone to allow for the mouselook to work?

gaunt ice
#

seems the tf.forward is always pointing to same direction

misty coral
#

but when I call the method isn't it going toward the most recent "transform.up"

misty coral
charred spoke
misty coral
#

Fixed it

#

now it works as intended

gaunt ice
#

oh yes, i always forgot to turn a direction into position

summer stump
# misty coral

MoveTowards a point. That's how I always remember. You can MoveTowards that mountain, but MoveTowards east sounds funny

ruby python
#

Hmm, okay, I've found a bunch of posts etc. saying that LateUpdate() is the way to go for rotating a bone through code, but that you need to store the bones rotation. But not one post has shown an example, so I'm a bit stuck as to where I'm supposed to be storing the rotation value. 😕

teal viper
ruby python
charred spoke
#

The question is why do you need to store the rotation ?

#

Store what rotation? Before the animation ?

teal viper
ruby python
#

!code

eternal falconBOT
ruby python
#

Okay, this is what I have at the moment. In my head, this should work, but the bone isn't rotating (well, it jitters, which says to me that the rotation is getting reset by the animator?)

Update()

//Mouse Input
        mouseRotation = mouseSensitivity * Time.deltaTime * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        transform.Rotate(mouseRotation.x * transform.up);
        playerBoneRotation = mouseRotation.y * transform.forward;

LateUpdate()

    private void LateUpdate()
    {
        playerYBone.transform.Rotate(playerBoneRotation);
    }
teal viper
ruby python
#

Gimme a couple of minutes, I think I just had a brainwave. lol.

willow scroll
#

Why don't you even rotate the playerYBone directly in the Update instead of assigning a variable and rotating it in the LateUpdate?

ruby python
willow scroll
ruby python
#

It's an idle animation, but there will be others.

willow scroll
#

Why do you need an idle animation to reset the rotation?

willow scroll
ruby python
willow scroll
#

Which should make you consider about this animation being redundant

ruby python
teal viper
#

Start by debugging the values and making sure they're all what you expect.
One thing that's incorrect and has been mentioned is multiplying mouse input by delta time

ruby python
#

Okay, well at the moment, this is what I'm getting.

https://streamable.com/okot9u

Debug.Log is the bone Rotation.

Update()

        //Mouse Input
        mouseRotation = mouseSensitivity * Time.deltaTime * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        transform.Rotate(mouseRotation.x * transform.up);
        playerBoneRotation.eulerAngles = new Vector3(0f, 0f, mouseRotation.y);
        //playerBoneRotation.eulerAngles = mouseRotation.y * transform.forward;
        Debug.Log(playerBoneRotation.eulerAngles);

LateUpdate()

    private void LateUpdate()
    {
        playerYBone.transform.localRotation = playerBoneRotation;
    }

I've modified the code a bit, but still getting the same results. I'll fix the deltaTime thing later (if it was that much of an issue tbh the horizontal rotation wouldn't be working either)

Watch "2024-04-20 07-30-37" on Streamable.

▶ Play video
willow scroll
#

Honestly, this is the thing that's most likely to cause the jitter

#

In the Update you multiply the mouseRotation by Time.deltaTime, even though it's only appropriate for rotating the transform, not setting it directly

verbal dome
#

Yeah, deltaTime does not belong with mouse input

willow scroll
#

This might fix the issue you're having

verbal dome
#

Mouse delta already has delta time taken into account. Multiplying it with it again will make it inconsistent

neon marlin
#

Hey this is kind of stupid but im struggling with something pretty bad,
im making a roguelike and i want room transitions to go like this : freeze the game, fade in black, change room, fade out, resume game

ive tried using time.timescale = 0 but that seems to also pause the animations, keep in mind id also want some functions to run right after the fade in to black animation is completed

verbal dome
neon marlin
#

oh lmao ok

verbal dome
#

Simulation Mode in the inspector IIRC

ruby python
#

Okay, well the bone does rotate more, but it seems to be still fighting with the animation as it reeeeeally wants to return to its 'base' position.

verbal dome
#

Wait it might be called something else

#

Maybe Update mode

#

Yeah that

ruby python
#

Set to Normal.

willow scroll
verbal dome
#

Yep

verbal dome
ruby python
#

Update()

        //Mouse Input
        mouseRotation = mouseSensitivity * new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        transform.Rotate(mouseRotation.x * transform.up);
        playerBoneRotation.eulerAngles = new Vector3(0f, 0f, -mouseRotation.y);
    private void LateUpdate()
    {
        playerYBone.transform.localRotation = playerBoneRotation;
    }
verbal dome
#

I just do something like this in LateUpdate
bone.RotateAround(bone.position, rightAxis, lookAngleX)

#

I dont get what all the other stuff is for

ruby python
#

What other stuff?

verbal dome
#

Okay so the total look angles are stored in playerBoneRotation?

#

What is playerYBone

ruby python
#

Vertical look angle yes. The horizontal rotates the whole of the player object, the vertical I want to just rotate the 'spine' bone so that the player bends forward and back at the waist.

verbal dome
#

Right ok. Did you check my example?

#

Just rotate the spine additively in lateupdate

#

Don't directly set it to anything

ruby python
#

Okay, will have a go. lol.

verbal dome
#

And dont use the current frame's mouse input for the rotation, store the total rotation in a variable instead

#

So the x angle you use for spine rotation would be somewhere in the -90...90 range

#

Though ofc you can multiply the final angle to rotate by with a smaller value so it looks more sensible

ruby python
#

Okay, so not sure if I've done this right tbh, but it's still 'fighting' to get back to it's original position.

    private void LateUpdate()
    {
         playerYBone.RotateAround(playerYBone.position, Vector3.forward, -mouseRotation.y);
    }
#

This is frying my brain. And it's only 8am. lol.

verbal dome
#

From what i can see, mouseRotation only stores the delta of the rotation this frame.
You need a variable that holds the accumulated rotation. You know, you add the delta to it every frame

ruby python
#

Right okay, so...bare with me......

#

accumulatedRotation += mouseRotation ?

verbal dome
#

Yeah something like that

ruby python
#

okay will give it a go.

verbal dome
#

Ideally you would use that accumulated rotation value as base for all your rotations, instead of just rotaing transforms and reading back their angles

#

Make sure to clamp the vertical though

ruby python
#

Yeah, I will be. And yeah, that works, kinda. lol. The bone rotates forward and back okay, but when the horizontal is changed, it goes a bit screwy.

#

Fixed it. lol.

#

I had Vector3.forward instead of transform.forward.

#

Thank you so much for the help, really really appreciate it. 🙂

verbal dome
#

Nice 👌

ruby python
#

So just to check, with the horizontal rotation it would be 'better' to do a similar thing to the vertical? (accumulatedXRotation += mouseRotation.x) ?

verbal dome
#

Well thats how I like to do it. Store rotations in variables instead of in transforms

#

Makes it clearer for me at least. And you know that nothing else changes the value, while a transform can be affected by other stuff such as animation

ruby python
#

Okay cool. 🙂

whole idol
#

how can i make the canva ui text always adjust to the size of my screen in unity?

#

is there a way for that ?

#

like a built-in method or build-in keyword or smth?

ruby python
#

(Right side)

frosty lantern
#

So I have a abstract class ChessPiece that my pieces inherit from, and the idea is that when you attempt to move a piece, that piece should broadcast it's location to all pieces on the board, and they respond with their position and color, so that the piece you want to move can determine if that is a valid movement.

But the BroadcastMessage and SendMessage methods don't work on inherited classes, they work on objects and monobehaviors.

Would it be a better idea to keep a singleton data structure with the list of positions instead then, so that when a piece updates it's position it modifies it's position in the structure for all other pieces to see?

But the issue is that singletons and global variables are frowned upon. In this example the only interactions should be from ChessPiece inherited classes, and the interactions will be done through a method inherited from the ChessPiece class, so maybe that makes it more acceptable since there is only going to be two ways of interacting: reporting new positions/colors, and reading the positions/colors.

I'm not aware of a more effective way of keeping track of the gamestate, if you guys have a suggestion.

#

maybe I should make it a struct since it's meant to store data and not actually do anything

misty coral
#

How do I make an object that is rotated by the player camera rotate 15 degrees on its x axis using rotateTowards?

onyx tusk
frosty lantern
onyx tusk
frosty lantern
#

hm, never heard that before

#

pretty neat

timber tide
#

singletons and globals are fine

#

could be a little messy if not organized correctly in larger projects but chess isn't something to worry about

frosty lantern
#

ok then, cool.

timber tide
#

it's not like you're doing some traditional scripting for some c# program. Unity's scene and gameobject lifetime adds some extra complexity that makes it harder to grab references.

eternal needle
#

you can simply store all the pieces in some 2d array, and anything that tries to move a piece will do so through the class storing the array.

#

theres also no need for this array to be static

frosty lantern
eternal needle
#

all the other pieces move themselves? i dont see why really the other pieces need to be aware of the movement

frosty lantern
#

storing the movements as vector3ints helps me generate clone meshes for where the pice can move

eternal needle
#

rather than based on when a piece moves, do it from whatever the game manager is

frosty lantern
eternal needle
#

Ah i see

timber tide
#

Just populate some container of unoccupied and occupied positions

#

and refer to that (easily accessable from the gamemanager)

eternal needle
#

Also just a note, i dont think the original solution would work unless you store them in some 2d array after grabbing all the positions. There are more cases than just "can i move here", for example u cannot move if it would put your king in check.

frosty lantern
#

all of my locations and movements are stored as vector3ints so the tests should be relatively simple and quick

onyx tusk
#

I'm new to work with objects (here .obj) in unity & i have a problem. I'm making objects after start & all primitives work fine except object. When I adding script to an intance created by GameObject.Instantiate(Resources.Load<GameObject>("path")) it doesn't works. But all of this objects has a child named default & when i adding script to it, it doesn't work too.

frosty lantern
#

are you getting a nullreference error from the line?

onyx tusk
frosty lantern
onyx tusk
frosty lantern
onyx tusk
frosty lantern
onyx tusk
#

if i add this script on parent & on default situation is without changes

onyx tusk
# frosty lantern I'm don't know what that means.
    private void OnMouseDown()
    {
        ChessVector vector = ChessVector.GetCoordinatesFromVector(transform.position);
        Figure.select(vector);
        Debug.Log($"Moved {Figure.GetFigure(vector).figure.name}");
    }```
code from script, i clicked on king
frosty lantern
frosty lantern
#

and sometimes it's failing to print out?

onyx tusk
#

but log doesn't print if i click on the king

frosty lantern
#

does the king have this script attached to it?

onyx tusk
#

all GameObjects has the same script, but it doesn't work only here

onyx tusk
frosty lantern
#

can I see the code for figure.getfigure(vector)?

#

and figure.select(vector)?

#

do you need to use that to get the name, instead of just using name as it's built in?

onyx tusk
#
    public static void select(ChessVector vector)
    {
        OnSelect(GetFigure(vector), EventArgs.Empty);
        OnSelect = (sender, e) => { };
        selectedCanBeat.Clear();

        selected = vector;
        selectedCanBeat.AddRange(GetFigure(vector).canBeat());
        GameObject parent = GetFigure(vector).figure;
        GameObject[] moveSpheres = new GameObject[selectedCanBeat.Count];
        int counter = 0;

        foreach(ChessVector i in selectedCanBeat)
        {
            Vector3 coords = ChessVector.GetVectorFromCoordinates(i);
            bool isFigure = GetFigure(i) != null;
            moveSpheres[counter] = GameObject.CreatePrimitive(PrimitiveType.Cube);
            moveSpheres[counter].transform.position = new Vector3(coords.x, 0.025f, coords.z);
            moveSpheres[counter].transform.localScale = new Vector3(1, 0.05f, 1);
            moveSpheres[counter].AddComponent<ForMovePads>();
            if (isFigure)
            {
                moveSpheres[counter].GetComponent<Renderer>().material = materials[((int)(GetFigure(i).color) + 1) % 2];
                GameObject killButton = GameObject.CreatePrimitive(PrimitiveType.Cube);
                killButton.transform.position = new Vector3(coords.x, size / 2, coords.z);
                killButton.transform.localScale = new Vector3(1, size + 0.1f, 1);
                killButton.GetComponent<Renderer>().material = materials[3];
                killButton.transform.parent = parent.transform;
                killButton.AddComponent<ForMovePads>();
                OnSelect += killButton.GetComponent<ForMovePads>().delete;
            }
            else
                moveSpheres[counter].GetComponent<Renderer>().material = materials[2];
            OnSelect += moveSpheres[counter].GetComponent<ForMovePads>().delete;
            moveSpheres[counter].transform.parent = parent.transform;
        }
    }```
willow scroll
eternal falconBOT
frosty lantern
#

wondering if the figure call has something to do with it

onyx tusk
queen adder
#

Guys is it possible to remove the texture from memory if an object is culled ?

frosty lantern
# onyx tusk no, this name ==== Figure.GetFigure(vector).figure.name

as of right now I can't really help with this. Someone with experience in object loading or asset management may have an Idea of what's going on.

basically the code seems to work fine on primitive objects, but once he created a king.obj file and tried to load it, the creation works fine and the start works fine, but the onmouseclick method fails

#

gn guys

#

i've never seen an obj file before

onyx tusk
frosty lantern
onyx tusk
frosty lantern
#

I'm pretty sure onmousedown needs a collider doesn't it?

onyx tusk
frosty lantern
#

In the inspector or the prefab or you can do it in code when you create the object

#

That might be why primitive game objects worked, because they have colliders on them

frosty lantern
onyx tusk
frosty lantern
#

Yay!

#

Took me a while to think of it but this is like my second time actually helping someone

#

I can sleep in peace

frigid sequoia
#

Is there a way to get a NavMesh sorta coordinate? Like I want a NavMesh Agent to pick a random position within the NavMesh boundaries

#

Is that a thing?

eternal needle
frosty lantern
frigid sequoia
#

And not sure what I should do with those methods

#

Is that supposed to return a vector 3 something?

raw aspen
#

hello this is a frame where i have a big frame drop and this is what seems to cause it. what conclusion can i make from this?

eternal needle
queen adder
#

I have 100s of copies of the same object in my world how will I detect a cull ?

frigid sequoia
queen adder
#

That seems tricky

eternal needle
#

Could be an easy test to see what it gives you if you draw or put objects at some of the vertices and see for yourself where they go

fierce marsh
#

looking for a collab

eternal needle
eternal falconBOT
fierce marsh
#

i will make 24 hour game challenge

frigid sequoia
brazen canyon
#

Hey guys
Can I have a look at an example code that does "When the player is dead, it uses an Action to broadcast to the GameManager so the GameManager carries out some functions such as end the game" ?

eternal needle
fierce marsh
frigid sequoia
#

Also, I think none of my enemies have a reference to the NavMesh itself at all, since it is meant to not be an specific one

eternal needle
eternal needle
frigid sequoia
brazen canyon
# eternal needle What part are you struggling with? Based on what you wrote, it seems like you kn...

So I'm watching this video
And when the player dies, I want to open a canvas that tells the player they are losers
https://www.youtube.com/watch?v=8fcI8W9NBEo&t=627s

Learn how to decouple your code by using Actions, Delegates and Events! Trigger code from anywhere in your project by subscribing to an event as a listener, they never need to know each other exist!

Join me and learn your way through the Unity Game Engine, the C# language and the Visual Studio editor. Remember, if this video was useful then DRO...

▶ Play video
willow scroll
# brazen canyon Hey guys Can I have a look at an example code that does "When the player is dead...

You'll have to create e.g. an UnityEvent and call it when the player is dead, which might happen in the one of your methods or OnDestroy

// The private method serialized in the Inspector
[SerializeField] private UnityEvent _onPlayerDead = new();

// The public property for the private method
public UnityEvent OnPlayerDead
{
    get => _onPlayerDead;
    set => _onPlayerDead = value;
}

private void OnDestroy()
{
    OnPlayerDead?.Invoke();
}

You'll be able to subscribe to the event from any other class, assuming you have a reference

playerController.OnPlayerDead.AddListener(DoStuff);
eternal needle
brazen canyon
#

Do I catch the

private void OnDestroy()
{
    OnPlayerDead?.Invoke();
}

Like I do with actions from other classes ?

willow scroll
# brazen canyon I have not study Unity Events thoroughly Can you explain please ?

There's nothing more to explain.
The Invoke method calls the event for every instance currently subscribed to it.

Having 3 different subscriptions to the event, regardless of the classes they're in, will call them all.

playerController.OnPlayerDead.AddListener(() => print("1st"));

playerController.OnPlayerDead.AddListener(() => print("2nd"));

playerController.OnPlayerDead.AddListener(() => print("3rd"));

// =>
// 1st
// 2nd
// 3rd

Say, invoking the event in the Update, will print the 3 messages above every frame.

private void Update() => OnPlayerDead?.Invoke();

By putting the operator ? after the event's name, you ensure no NullReferenceException is thrown in case the event is null. Not using this operator may give you the errors if it is.

brazen canyon
#
=> print("3rd")

Can I replace this with a method instead of writing directly ?

young fossil
#

How should I organise my scenes? I was thinking a serialised list in the inspector. Opinions?

willow scroll
# brazen canyon ```cs => print("3rd") ``` Can I replace this with a method instead of writing di...

Yes, of course.
By using the () =>, you make sure the listener cannot be removed.

() => print("3rd");

If you want to use a method, it will have to match all the parameters your event has. In this case, the method should be passed directly without the parentheses ()

OnPlayerDead.AddListener(DoStuff);

private void DoStuff() => print("3rd")

When the parameters don't match, you'll have to use the parentheses () with the parameters inside of it

OnPlayerDead.AddListener(DoStuff); // error

OnPlayerDead.AddListener(() => DoStuff("something"));

private void DoStuff(string something) => print($"{something}, 3rd")

You can give your event from 0 to 4 parameters by placing them inside of the <>

UnityEvent<string, bool, Vector2, float> YourEvent
fringe plover
#

does .AddListener work with any public method?

willow scroll
young fossil
oblique herald
#

yoooo! I wanna ask a pretty silly question, but basically, I want my game to have a cutscene in a middle scene, and press f to load the cutscene, code are below:

  private void Update() {
        if (inventoryManager.hasSoda) {
            drink.SetActive(true);
            Time.timeScale = 0;
            if (Input.GetKeyDown(KeyCode.F)) {
                SceneManager.LoadScene(sceneBuildIndex, LoadSceneMode.Single);
            }
        }
    }

however when I press f the scene loads but not my animation. Whys that?

young fossil
#

I want a GameManager.cs that exists between levels

oblique herald
#

does timescale bring forward to the next scene?

young fossil
#

So it has to delete the other instance every single time a scene is loaded?

#

Doesn't really make sense, right?

bold nova
#

yeah, you assign one instance in awake if instance is null otherwise delete game object

#

Does ontrigger enter works with character controller? I have a trigger on room entrance to detect if player has entered. After debugging i found out that code doesnt even executes that method, ignores completely, when player enters

young fossil
#

So again, that implies everytime a scene is loaded it deletes the clone.

Example, MainMenu has the GameManager.cs. Then you go to Level1, player dies, it goes back to MainMenu.

Assuming MainMenu has GameManager, it will delete the script upon returning to MainMenu from Level1... Since when that Level is reset it will recreate the original GameManager meaning two exist

eternal needle
#

Your !ide doesnt look configured

eternal falconBOT
eternal needle
#

That initial loading scene can have the game manager

young fossil
young fossil
#

Makes sense. I wanted to avoid having an extra scene, more memory allocation and then have to deal with loading another scene from my understanding

bold nova
young fossil
willow scroll
eternal needle
young fossil
#

It is a singleton, that functionaility exists, it deletes clones

#

But say I did the intial loading scene, it shouldn't ever clone the script unless it is unexpected behaviour?

bold nova
young fossil
young fossil
#

Since when you LoadScene, you are allocating the memory, unloading is freeing the memory

#

It doesn't matter anyway, it's just annoying to deal with another scene. Is what it is I guess

eternal needle
#

Not really sure where additive scene loading was brought up here, I'm not saying to load it additively

young fossil
#

Like I said, doesn't even matter, Thanks for the guidance I'll try what you suggested

eternal needle
#

Dont worry about memory or performance until you actually have an issue, it's a waste of time to think about

#

You can run a LOT more than you think

young fossil
#

I really don't know

#

It is lightweight physics based, uses a lot of triggers and rays

#

2D

eternal needle
bold nova
#

ahh, does anyone know another way of checking if the player entered a room besides triggers? I have build the whole player controller system around character controller, trigger collision doesn't work with character controller but I don't think that just adding collider with a rigidbody solely for room entering is a good architectural decision

lone thunder
#

w server w community

young fossil
bold nova
# young fossil Will NavMesh be a concern?

normally it should't be, but if it is you can check Brackeys video on nav mesh agent optimization
https://www.youtube.com/watch?v=G9Otw12OUvE

Let's see how many NavMesh Agents Unity can handle! That's right, another excuse for making a huge simulation ;)

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

····················································································

♥ Donate: http://brackeys.com/donate/
♥ Subscribe: http://bit.ly/1kMekJV

● Website: h...

▶ Play video
young fossil
#

Oh great, I'll bookmark that

eternal needle
# young fossil Will NavMesh be a concern?

Honestly idk enough about 2d to even know how you use navmesh with it. But as a general answer, the worst part about it will be how much logic you're trying to run at once. Like you arent getting 100 enemies at once on mobile

#

Brackeys also really isnt a good source. You should just test it yourself, see when the framerates really drop

young fossil
#

Thanks guys

low path
#

And how many rooms do you have?

bold nova
#

3d fps shooter, imagine doom

#

i want to have 3

low path
#

Are they box shaped or will they have arbitrary shapes?

eternal needle
bold nova
#

it is strange actually, i added rigidbody and collider on top of character controller, made sure that part of the collider are above character controller and it still doen't register anything

bold nova
#

but fps drops when I enter the room:))

young fossil
#

Gizmo best way to visualise connections

#
    void OnDrawGizmos()
    {
        // Draw a yellow sphere at the transform's position
        Gizmos.color = Color.yellow;
        Gizmos.DrawSphere(transform.position, 1);
    }
bold nova
#

well, i just added a break point on the line of code inside the on trigger enter method when it check for the Player tag

low path
#

What do the connections between your rooms look like?

bold nova
#

if it stops there it has at least detected collision

low path
#

Just open connections or something more restrictive?

bold nova
#

For now it just a playground, where i check if everything works as planned

#

that collider on the ledt is room entrance on the right - player

jovial valve
#
        int z = 0;
        while(z < 50)
        {
            z++;
            Debug.Log(z);
            yield return null;
        }

why is this running only once in my coroutine?

bold nova
#

and I am sure it does work because when i start running the scene it detects enemy inside the room

brazen canyon
willow scroll
willow scroll
brazen canyon
# willow scroll What do you mean?

I mean the whole

// The private method serialized in the Inspector
[SerializeField] private UnityEvent _onPlayerDead = new();

// The public property for the private method
public UnityEvent OnPlayerDead
{
    get => _onPlayerDead;
    set => _onPlayerDead = value;
}

private void OnDestroy()
{
    OnPlayerDead?.Invoke();
}

part here is written in the same script with playerController or in a different class ?

bold nova
eternal needle
bold nova
eternal needle
#

Only one object needs the rigidbody

bold nova
willow scroll
brazen canyon
#

Okay ...
Thanks

willow scroll
split dragon
#

Hi. I have some questions about optimizing the script. I have 2 choices for storing big data: an Array and a Dictionary. I agree that the Dictionary will be more convenient to use. I read on the Internet that the Array takes up less memory and works a little faster (although all I read was that it was written more than 5 years ago). If we take better performance (ignoring the convenience of writing code), will the array be better optimized?

fickle plume
#

Array (or List) for fast iteration, Dictionary for fast item access through keys. Can have both to sacrifice memory for performance.

split dragon
gaunt ice
#

what is load the system less? less memory?

fickle plume
#

You select them for their utility as this would make the most impact

split dragon
fickle plume
#

Arrays are to hold and iterate finite number of items, List/Queue/Stack same but you need to add/remove items. Dictionary you don't often iterate but fast keyed access.

gaunt ice
#

dictionary use more memory for space-time trade off, if you need O(1) access then you should use dict unless you key is int and continuous eg 3,4,5,6,7....

split dragon
#

Ok. I understand. Thanks

gaunt ice
#

in some cases using other data structure maybe faster than dictionary, but rarely.

turbid shell
#
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{

    public float moveSpeed;
    public float jumpForce;
    Rigidbody2D rb2d;
    private Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            transform.localRotation = Quaternion.Euler(0, -180, 0);
            rb2d.AddForce(Vector2.left * moveSpeed);
            anim.SetBool("isMoving", true);

        }
        else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            transform.localRotation = Quaternion.Euler(0, 0, 0);
            rb2d.AddForce(Vector2.right * moveSpeed);
            anim.SetBool("isMoving", true);
        }
        else
        {
            rb2d.velocity = Vector2.zero;
            anim.SetBool("isMoving", false);
        }
        if(transform.localPosition.y < -1)
        {
            Vector2 v = new Vector2(transform.localPosition.x, -1);
            transform.SetLocalPositionAndRotation(v, transform.localRotation);
        }
    }
}```Sometimes the player gets stuck and I need to move in the opposite direction to go in the original direction, why is that?
burnt vapor
#

Could it be that you are not stuck but velocity still puts you in that direction?

turbid shell
#

Sorry? I don't understand what you mean

turbid shell
ionic plank
#

Hello everyone,

I am a student and I have a project on unity and I have a problem that I think it's easy to solve but I'm a newbie in this field. Can someone help me with my problem ?

I am creating a 2D platformer avec I have an issue when i paused the game, go to the menu and go play the game, I have a lots of errors like this :

MissingReferenceException while executing 'performed' callbacks of 'Land/Move[/Keyboard/leftArrow,/Keyboard1/leftArrow,/Keyboard/rightArrow,/Keyboard1/rightArrow,/Keyboard/q,/Keyboard1/q,/Keyboard/d,/Keyboard1/d]'

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

But my character can do all moves it supposed (just a problem in my console I think)

Thank you ❤️

(i am not english sorry for my faults)

gaunt ice
#

The object of type 'Transform' has been destroyed but you are still trying to access it.

short hazel
#

Stack trace of the second error

rustic maple
#

guys do you know what is wrong with this code because im getting a lot of errors

#

if (transform.postion.y = > deadZone, tranform.position.y = < deadZone)

short hazel
#

Yes there is a , in the middle lol

gaunt ice
#

not valid syntax

short hazel
#

That is invalid

rustic maple
#

and some spelling mistakses lol

#

i see now

gaunt ice
#

also =< => operators doesnt exist

rustic maple
#

i need to remove =?

short hazel
#

You type the characters as you'd say them out loud

#

"Less or equal" <=
"Greater or equal" >=

#

(equals always last)

gaunt ice
ionic plank
#

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.set_localScale (UnityEngine.Vector3 value) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
PlayerMouvement.FlipCharacterDirection () (at Assets/Script/Game/PlayerMouvement.cs:59)
PlayerMouvement.<Awake>b__11_0 (UnityEngine.InputSystem.InputAction+CallbackContext ctx) (at Assets/Script/Game/PlayerMouvement.cs:24)
UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Utilities/DelegateHelpers.cs:46)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)

short hazel
#

There we go:

PlayerMouvement.FlipCharacterDirection () (at Assets/Script/Game/PlayerMouvement.cs:59)
Your issue happens in the PlayerMovement.cs file, on line 59

#

More precisely in the FlipCharacterDirection() function

rustic maple
#

how do i set the deadzone to 2 points for the y? because in my flappy bird game i want the gameover screen to come when the bird get to these to points above and down

wintry quarry
rustic maple
#

i found to 2 positions where i want the bird to "die", but how do i set those to points as the deadzone?

willow scroll
wintry quarry
#

it's not going to be exactly one of the values in a list

#

it will be above or below

rustic maple
#

i already made this but is this the correct way?

#

if (transform.position.y >= deadZone || transform.position.y <= deadZone)
{
gameOverScreen.SetActive(true);
}

willow scroll
wintry quarry
#

this will always be true

willow scroll
#

This condition is true in every case, because of you checking for the position being either the same, greater or smaller

wintry quarry
#

don't you have two positions ?

rustic maple
#

yes i have -13.5 and 13.5 where the bird is out of the screen and when i want it to die

ionic plank
wintry quarry
#

something like:

float y = transform.position.y;
if (y > upperDeadZone || y < lowerDeadZone) {
  // die
}``` @rustic maple
willow scroll
short hazel
#

So you should fix them anyway

modest dust
willow scroll
ionic plank
short hazel
#

Well it's happening in there, as per the stack trace

rustic maple
rustic maple
#

if i tell that the y position has to be > than the deadzone and that it dies, how does it know that that only happens when he reaches y -13.5 anf 13.5?

rustic maple
willow scroll
#

If you want it to be 13.5 or -13.5, you simply assign it to the value.

ionic plank
willow scroll
wintry quarry
#

start a thread^

short hazel
#

No, you can just post the !code and the relevant messages here

eternal falconBOT
ionic plank
#

I don't want to polute the chat

wintry quarry
#

start a thread

willow scroll
rustic maple
wintry quarry
#

you do whatever you want to do when the bird dies

rustic maple
#

the game over screen variable is on another screen so i first need them to talk to eachother right

wintry quarry
#

not sure what you mean by "on another screen"

rustic maple
#

okay i have good news

#

it works kinda

#

now when i go out of screen i indeed did something

willow scroll
rustic maple
#

but i got the message that the gameOverScreen is not assigned to the script from the bird

#

because it indeed is assigned to my logicscript for the game over when you die

wintry quarry
#

yep you didn't assign it

rustic maple
rustic maple
wintry quarry
#

yes now you have to assign it

rustic maple
#

OOOH

wintry quarry
#

You only did the first step.

rustic maple
#

WAIT

#

it works kind of

brazen canyon
# wintry quarry You only did the first step.

Excuse me
Can I get your help please ?
Here I subscribe this class to an event
But that CanvasLoseOpen kept being called constantly
So I called that OnDisable() to unsubscribe it
But then the game said the event is null

willow scroll
brazen canyon
rustic maple
#

THANK YOU

wintry quarry
brazen canyon
wintry quarry
#

ok so the error is on line 57 of Character.cs

rustic maple
#

now the game over screen pops up when the y are touched, but now i need to pause the game like it does when you die by touching the pipes

#

cuz now when i go outside the map the screen pops up but i can still play

brazen canyon
willow scroll
wanton canyon
#

can someone point me in the direction for a good tutorial for implenting walking/jumping sound effects? every tutorial is just basically "if walk, play sound" which, sure, but I need it to be way more dynamic than that...

willow scroll
rustic maple
#

no nothing just sharing 😂

wintry quarry
rustic maple
#

but thank you guys you really helped me there

brazen canyon
wintry quarry
#

that's how it works

wintry quarry
willow scroll
brazen canyon
rustic maple
#

private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOver();
croissantIsAlive = false;
}

rustic maple
#

this is my code for the bird to die when touches pipes

#

can i just copy that and put that to when he touches the y positions?

willow scroll
wintry quarry
brazen canyon
wintry quarry
#
public Action example;
public event Action example2;```
#

It's a modifier to the variable

#

it just means nobody else except this class can call example2.Invoke();

#

Action is a delegate type
it just means "A delegate with no parameters that returns void"

willow scroll
rocky canyon
wintry quarry
#

If it's UnityEvent, then yes that's different

rustic maple
#

it works now!!!

willow scroll
brazen canyon
#

Okay I think I'm getting a bit hang of these stuff now

willow scroll
rustic maple
#

i put these 2 logic.gameOver();
croissantIsAlive = false; under this float y = transform.position.y;
if (y > upperDeadZone || y < lowerDeadZone) {
// die
}

willow scroll
# brazen canyon Okay I think I'm getting a bit hang of these stuff now

The difference is that the Action should be subscribed and unsubscribed, otherwise it will cause you troubles,

private Action yourAction = new();

private void OnEnable() => yourAction += YourMethod;

private void OnDisable() => yourAction -= YourMethod;

while you can simply add a non-persistent listener to the UnityEvent, which shouldn't be unsubscribed

private UnityEvent yourEvent - new();

private void Start() => yourEvent.AddListener(YourMethod);
wintry quarry
#

UnityEvents need to be unsubscribed too..

#

assuming the subscriber is destroyed before the publisher

#

RemoveListener is a thing

willow scroll
#

But yeah, they should be unsubscribed if destroyed in order not to cause null errors

wintry quarry
#

The same rules apply as with C# events. If the subscriber has a shorter lifespan than the publisher, the subscriber needs to unsubscribe when it dies.

#

if the publisher will have a shorter lifespan than the subscriber, there's no need to unsubscribe.

willow scroll
#

I see, yes, the listeners are not removed in the majority of cases

wintry quarry
#

A frequent source of bugs 😉

brazen canyon
#

What are you guys talking about ? @@

willow scroll
wintry quarry
#

We're talking about when you need to remove listeners from events and when you don't.

brazen canyon
#

Oh ...
I might need to record this for later uses

willow scroll
#

It is usually so that the actions are always unsubscribed, UnityEvents are just subscribed to using AddListener

#

You don't need a reference when you don't unsubscribe from the event. In this case you may use (...) =>

onyx tusk
#

How 2 make 2d button in 3d project with web-link?

#

I checked some guides but it doesn't works

wanton canyon
#

probably a dumb question, does C# have "if then" statements?

rich bluff
#

yes

onyx tusk
rich bluff
#

i think the then is just the scope { }

wanton canyon
#

if else is different, thanks tho

fickle plume
rich bluff
#
if(true)
  DoStuff(); // for sinle line instructions

if(true)
{ // open scope
  DoStuff();
  DoStuff2();
} // close scope, for multiline
onyx tusk
#

How 2 make 2d button in 3d project with web-link?

wanton canyon
#

my question is not being understood but that's fine I'll figure it out

onyx tusk
naive pawn
#

you may have phrased it inaccurately to what you meant to ask

#

c#'s if statement is just that

fickle plume
#

Are you asking about ternary conditional operator?

onyx tusk
#

condition? ifTrueValue : ifFalseValue

clever fable
#

I'm losing my mind, I have this code, tag is set up properly, got a rigidbody on the pickup, this script is on the object to be destroyed, my player has a collider idk what is wrong: using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackBonus : MonoBehaviour
{

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Debug.Log("Collision");
        //BulletLife.damage += 1;
        Destroy(gameObject);
    }
           
}

}

#

try ontrigger, just checking for .gameobject without tag, still nothing

clever fable
summer stump
#

The rigidbody is NOT kinematic?

clever fable
clever fable
#

the oncollisionenter does not happen no, got nothing in console, There's other stuff in the project with collision that's fine as well,i honestly have no clue

summer stump
#

This may help. It's a troubleshooting guide

wanton canyon
polar acorn
wanton canyon
#

am I overthinking this and just put it after the if statement lol

naive pawn
#

yes

wanton canyon
#

LOL ty

onyx tusk
naive pawn
#

these are identical constructs

// c-like
if (condition) statement;
``````py
# py
if condition:
  statements
``````sh
# sh
if condition; then
  commands
fi
polar acorn
wanton canyon
#

yeah this was a case of over thinking on my part, thank you

naive pawn
onyx tusk
#

How 2 make 2d button in 3d project with web-link?

visual hedge
#

2d button as in UI button?

onyx tusk
#

yes

visual hedge
#

ui canvas > add button?

deft apex
#

how do i get the rotation of a configurable joint? In my case im using a configurable joint instead of a hinge joint for a door because the hingejoint was bouncing on its limits even when bounce was 0

onyx tusk
visual hedge
#

oh, I don't know how. But my logic woudl be to think that depending on OS and hardware / software, you would want to call the default browser of your OS, aren't you?

#

or we aren't talking about like link to some google. com?

willow pike
#

Can someone help me with tile maps, i use composite colliders yet it sort of bugs my player out

willow pike
#

Thank you

visual hedge
# onyx tusk any browser of my OS

the answer I found by googling, tho, would be something like Application.OpenURL(url); where url is string. I don't know if that actually works though

soft kernel
onyx tusk
visual hedge
#

oh okay 😄

visual hedge
visual hedge
#

Make sure the URL starts with "http://" or "https://" for it to work properly. <- string I found in documentation

tepid summit
#

is KeyCode.Space a real thing? what else would i call it

tepid summit
#

alright

#

all good then

naive pawn
tepid summit
#

i forgot to add a tag to my gameobject

#

thats why it wasnt working

onyx tusk
naive pawn
#

not sure what you mean by that

onyx tusk
naive pawn
#

im just saying that it isn't a url

visual hedge
#

wait now I am also kinda puzzled. What is it if not url? 🙂

#

okay, url has to have protocol specified, okay

tepid summit
#

tf is AltGr

#

its a keycode

#

my best guess would be the alt key but whats the gr for

languid spire
#

That is the Alt-Graphics key, it's used for selecting keys which are not normally on the keyboard

tepid summit
#

oh

#

ok

#

so its for fancy characters

#

such as ™️

languid spire
#

exactly

tepid summit
#

cool

rustic maple
#

does anybody know why when i press my button to restart the game, it did restart but i cant play? i used this code

#

public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

tepid summit
#

is that the whole thing

wintry quarry
#

My guess is you set the timeScale to 0 somewhere and forgot to reset it to 1

rustic maple
#

i can press the button to restart and it restarts but i cant press space to start playing again

wintry quarry
#

Why would you expect to be able to press space to start playing?

rustic maple
#

one sec

#

public void gameOver()
{
gameOverScreen.SetActive(true);
PauseGame();
}

public void PlayGame()
{
    gameOverScreen.SetActive(false);
    scoreText.gameObject.SetActive(true);
    Time.timeScale = 1f;
}
public void PauseGame()
{
    gameOverScreen.SetActive(true);
    scoreText.gameObject.SetActive(false);
    gameOverText.text = playerScore.ToString();
    Time.timeScale = 0f;
}
rustic maple
eternal falconBOT
rustic maple
#

oh yeah

#

sorry

#
    {
        gameOverScreen.SetActive(true);
        PauseGame();
    }

    public void PlayGame()
    {
        gameOverScreen.SetActive(false);
        scoreText.gameObject.SetActive(true);
        Time.timeScale = 1f;
    }
    public void PauseGame()
    {
        gameOverScreen.SetActive(true);
        scoreText.gameObject.SetActive(false);
        gameOverText.text = playerScore.ToString();
        Time.timeScale = 0f;
    }
wintry quarry
#

nothing in here about pressing space

#

just share the full scripts

willow scroll
rustic maple
# wintry quarry just share the full scripts
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class LogicScript : MonoBehaviour
{
    public int playerScore;
    public Text scoreText;
    public GameObject gameOverScreen;
    public Text gameOverText;

    [ContextMenu("Increase Score")]
    public void addScore(int scoreToAdd)
    {
        playerScore = playerScore + scoreToAdd;
        scoreText.text = playerScore.ToString();
    }

    public void restartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }


    public void gameOver()
    {
        gameOverScreen.SetActive(true);
        PauseGame();
    }

    public void PlayGame()
    {
        gameOverScreen.SetActive(false);
        scoreText.gameObject.SetActive(true);
        Time.timeScale = 1f;
    }
    public void PauseGame()
    {
        gameOverScreen.SetActive(true);
        scoreText.gameObject.SetActive(false);
        gameOverText.text = playerScore.ToString();
        Time.timeScale = 0f;
    }
}
wintry quarry
#

Still nothing here about pressing space

rustic maple
#

its not about the space its about that the game freezez after i press the play again button

wintry quarry
#

You siad you're not able to press space to start it again

#

that has to do with pressing space

rustic maple
#

yeah thats true, i think i mentioned it wrong, because i want to solve the problem that the game just runs after i press the button and not freeses

tepid summit
#

could someone perhaps please help me normalise my vectors

summer stump
#

Did you google it first btw?

tepid summit
#

pretty sure i tried that and there was an issue

#

ill try agan one sec

deft grail
tepid summit
#

this.transform.Translate(Vector3.forward * _vInput * Time.deltaTime);

#

how would i place it into here

#

just vector3.forward.normalized?

#

becuase i dont have new vector3 anywhere

burnt vapor
#

Please properly explain your error and share the !code instead of this

eternal falconBOT
summer stump
#

Make a vector3 variable, normalize it, pass that into translate

wintry quarry
#

Vector3.forward is already a normalized vector

#

so what are you actually asking how to do here?

#

Why are you asking about normalized vectors? What's going on? Give some context.

tepid summit
#

im about to

wintry quarry
#

I'm chill, just asking for clarification.

tepid summit
#

this is all i have including vectors

        _hInput = Input.GetAxis("Horizontal") * MoveSpeed;
        _vInput = Input.GetAxis("Vertical") * MoveSpeed;

        this.transform.Translate(Vector3.right * _hInput * Time.deltaTime);
        this.transform.Translate(Vector3.forward * _vInput * Time.deltaTime);

the issue: i dont know what to do here

wintry quarry
#

What are you trying to do?

summer stump
#

Do only one translate call for one thing

tepid summit
#

fix the xy issue

wintry quarry
#

what is "the xy issue"?

tepid summit
#

going diagonal is faster than the cardianal directions

wintry quarry
tepid summit
#

i heard normalising is a good fix

wintry quarry
#

now you said your problem

#

normalizing isn't the best fix

#

Clamping the magnitude of your motion vector is the best fix

tepid summit
#

i didnt say best

small mantle
#

I am making an Enemy Count Script, this script will check its collider to see how many Objects with "Enemy" Tag there are in its collider2D. The issue I am having is that the collider2D is checking all the colliders of the enemy. So instead of it giving me 3 Enemy Checks, it will say 6 because each enemy has two collider2Ds(One for rough terrain, and another to make sure they don't clump together when attacking the player.) How can I check for only the 1 collider on each Enemy to ensure I don't get multiple checks for each collider2D on the Enemy's?

Apologies, here is the code: cs private void OnTriggerEnter2D(Collider2D collision) { int counter = 0; if (collision.CompareTag("Enemy")) { counter++; print("1 Enemy" + counter); } }

young warren
#

that might be the simplest fix. see if that'll do

#

or are the colliders on the same object?

rich adder
#

put it on different layer and use Overlap

tepid summit
young warren
#

or what navarone said

small mantle
tepid summit
#

you cant move a terrain collider

rich adder
#

oh yeah they need to be separate for sure, to easier distinguish

cinder crag
young warren
tepid summit
#

in the sound

tepid summit
#

shot sounds in unwanted places

small mantle
tepid summit
#

unless its as simple as Vector3.forward.ClampMagnitude

#

but i doubt it

summer stump
tepid summit
#

yes

#

how though

summer stump
#

You do new vector and do hInout for x and whatever the other one you had for z

#

Or just do new Vector3(Input.GetAxis, 0, getAxis)

tepid summit
#

but would i add that after transform.Translate

small mantle
#

How should I go about making a Objective Manager that will check it's children to see which are active? I may be making it more complicated then it should be.

#

The Objective Manager itself doesn't have a collider, but the children do and also have the code I provided earlier.

cinder crag
# rich adder what is "this" exactly

Well when going back to the main menu and then pressing play , it doesn't load the game properly like you can't do anything, it doesn't load the stuff in that scene

#

Idk why

languid spire
small mantle
summer stump
tepid summit
#

ok

languid spire
small mantle
cinder crag
languid spire
#

the transform of the gameobject, in this case your Objective Manager

tepid summit
#

i tried

cinder crag
#

Dw it's fine

small mantle
languid spire
cinder crag
honest haven
#
             {
                 if (Input.GetKeyDown(KeyCode.B))
                 {
                     canBlock = false;
                     didBlock = true;
                     Block();
                 }
                 else
                 {
                     StartCoroutine(ShowBlockMissText());
                 }
             }``` so im trying to make a message pop up if the player didnt block the move. but even if i block it that message courtine still beng called.
short hazel
#

On one frame you can block, but you don't, so the coroutine starts. On the next frame you effectvely block, but the coroutine is already running

honest haven
#

yh your correct i just cant think of a way to fix this as its in update

#

im stuck in a loop

#

should keycode b be in a timer

short hazel
#

You'd want to start the coroutine if the "can block" grace period expires (when canBlock is set back to false after some timeout)

honest haven
#

i have a trigger at the begining of the animation that sets canblock to true and can block to false at the end of the animation.

#

would i need a timeout if im using animation events

languid spire
#

surely once you have started the coroutine canblock should be set back to false

short hazel
ember oasis
#

could someone explain to me how I could make traffic lights

short hazel
#

If the event occurs and the player hasn't blocked, then didBlock will be false

ivory bobcat
ember oasis
soft kernel
ember oasis
#

punishment is pending

honest haven
short hazel
#

Yup

honest haven
#

cheers

torpid yacht
#

Guys what is the best way to check if there is internet?
Just ping Google?

rich adder
#

wont go into a full on explanation but i can tell you its pretty easy

rich adder
torpid yacht
#

Great, thanks 🙂

honest haven
# short hazel Yup

thanks, Been working on a massive laravel project all week and am drained but feel guilty not working in the game. Cheers for that

#

just could not think

small mantle
#
if (!setKillAmount) {
            if (collision.CompareTag("Enemy")) {
                print("Counting");
                enemyCounter++;
            } else {
                print("Count");
                setKillAmount = true;
            }
        }``` This code is in OntriggerEnter2D. The issue I am having is that I want the "else" statement to take place just after the collision finds no more "Enemy" Colliders. How can I do this?
static bay
#

What's the "goto" for text for a 2D sprite game that exists in the world itself?

rich adder
#

textmeshpro

static bay
#

World-space canvas or a proper mesh?

static bay
rich adder
#

no i mean literally TextMeshPro

#

the mesh version

static bay
#

the TextMesh that is pro

#

got it

#

Wait does it properly layer with sprites?

rich adder
#

if its only text is ur best bet, if you need things like icons and a whole layout infobox then yea using World canvas make sense

small mantle
#

I am using OnTriggerEnter2D and am using the collison.CompareTag. I am adding an int every time it finds a collision with that Tag. The code works but I also want to check when it stopped adding up. How can I do so?

rich adder
small mantle
static bay
rich adder
rich adder
small mantle
static bay
rich adder
#

yeah might have to use Z positioning for that sorting

static bay
#

Which makes sense, this is handled by an SDF shader.

static bay
#

Alright

rich adder
#

what is the original enemy count, to compare it to

#

how will you know "all enemies amount" was reached

small mantle
ivory bobcat
#
if the enemy counter is greater than the number of enemies
    process the done events```
rich adder
#

if you want it to be modular

#

a list/array will tell you exactly how many enemies you got

dusk minnow
#

I need some help, i wanna build and this keeps happening:

small mantle
slender nymph
small mantle
rich adder
ivory bobcat
rich adder
#

eg
List<Enemy> enemiesList = FindObjectsOfType<Enemy>().ToList()

#

int enemiesFound = enemiesList.Count

small mantle
rich adder
ivory bobcat
#

Are the rooms procedurally generated?

#

If not, you can populate the list prior to build

#

If they are, you can differentiate them with some ownership relative to position, trigger event or whatnot.

small mantle
#

Room 1 has 2 Enemys, Room 2 has 5 Enemys. The Room Check Objects have a script that has the code I showed. Each Object checks their collider for Enemy Objects and Counts them...
There will be more rooms*

wintry quarry
#

Each room should know how many enemies it has. Add that number to the total count when a room is spawned

small mantle
wintry quarry
#

or even have each enemy register itself with the enemy counter when they spawn, on OnEnable

rich adder
wintry quarry
#
public class Enemy : MonoBehaviour {
  void OnEnable() {
    EnemyManager.Instance.Register(this);
  }
}```
rich adder
#

Would do exactly this ^

wintry quarry
#

I'd do something like this

ivory bobcat
#

A bool to simply tell you that you're done would still require you to know when you're actually done - no dodging the bullet.

small mantle
wintry quarry
#

No, that's not what I suggested

#

The code example I shared is what I suggested

ivory bobcat
small mantle
static bay
#

It respects sorting groups

rich adder
static bay
#

But doesn't EXPOSE a sorting layer and priority

rich adder
#

yeah thats following the typical UI sorting (hierarchy order)

static bay
#

_>

ivory bobcat
static bay
rich adder
static bay
#

The real answer is probably "transparent materials"

rich adder
#

UnityChanPanicWork expensive operations

small mantle
ivory bobcat
#

Where you simply set the room reference/value when a new room is enabled

wintry quarry
#

I would just keep a HashSet of all the currently living enemies

#

and once that's empty you're done

small mantle
wintry quarry
#

unregister when they die

wintry quarry
rich adder
wintry quarry
#

like a List

#

but is faster to remove arbitrary items from it

small mantle
rich adder
#

no that will simply register Enemy to the list

#

like RSVP to a party, you added yourself

ivory bobcat
wintry quarry
#

Having each room keep track of its enemies?

small mantle
wintry quarry
#

Make a Dictionary<Room, HashSet<Enemy>> or something then

#

or have each Room have a script with a HashSet<Enemy> in it

#

to track its own enemies

#

Or if the enemies are all disabled at the start then you needn't do anything other than the first example

ivory bobcat
#

I still think it'd be fine to docs void OnEnabled() { player.room = this; }Assuming everything is in the scene by default and can be easily referenced.

#

Unless you've got multiple rooms active at any given time..

small mantle
ivory bobcat
#

The integration should be quite simple

small mantle
#

I just need to make a way to have the enemyCounter added to a list.

real rock
#

so I'm trying to understand this tutorial for making a ship game in unity, but I don't understand why they're adding a force to the rigidbody using the existing velocity of the rigidbody.

#

same with the addtorque they're in the middle of typing, in my mind it makes sense that addatposition would have the rigidbody just work it out

small mantle
#

Is there a way to check after a collision has found no more?

wintry quarry
maiden vigil
#

hello, I am a complete newbie in coding in unity, but for some reason i decided to do my seminar assigment in it. Everything worked perfectly but now the game doesnt work and just stutters for some reason, is there anyone that could help me its probably a stupid small fix but as i said i am not very good in unity

real rock
wintry quarry
real rock
#

Noted ok I think that makes sense. This is done on the individual "floaters" (the corners for simplicity) but if each floater is running this at fixedUpdate, would it be better to have a fixedupdate on the actual rigidbody run the drag calculation?

ivory bobcat
# small mantle ```cs if (collision.CompareTag("Enemy")) { print("Counting"); ...

I'm not sure what your setup is but if this script is on the player and designed to discover the number of enemies he's met you could probably just set the enemies collider to be ignored after being found once, if you're simply trying to not add an enemy more than once.
You could probably change the enemies tag, disable the particular collider (assuming it's used for nothing else), ignore collision between those specific colliders, disable a particular component that you'd try to get on collision from the enemy, etc

wintry quarry
real rock
#

doesn't look like the values change so I guess just *floaterCount it or something

#

I'm sure when I get around to trying this with my system I'll discover why it's individual XD

small mantle
wintry quarry
real rock
#

the main ship's one

wintry quarry
#

What about the AddForceAtPosition

small mantle
#

I still have that issue though, how can I check when there are no more enemys.

wintry quarry
#

what position is it using?

real rock
#

also I just realised the displacement multiplier changes so that's probably it

wintry quarry
#

also that

#

yeah the displacement is using the floater's position

#

same with likely the AddForceAtPosition

real rock
#

ok that makes sense then

wintry quarry
#

and the wave height at this floater

real rock
wintry quarry
#

so yeah you'd do a loop over the floaters if you wanted to consolidate this to one script on the main boat doing it all

real rock
#

ok, probably not worth it

ivory bobcat
small mantle
ivory bobcat
#

The hashset will only contain each enemy once regardless of how many times you try to add them

static bay
ivory bobcat
rich adder
small mantle
ivory bobcat
small mantle
#

Is there no way to just check that this code is not getting used? cs if (collision.CompareTag("Enemy")) { print("Counting"); enemyCounter++; }

gaunt ice
#

Impossible for physics system determine if some area does not contain collider anymore (in future).
you can use a timer to set time out manually but not recommend

novel beacon
#

I am trying to set up Unity with Visual Studio, I have done everything, but when I open C# files in Visual Studio from Unity, it doesn't recognize any Unity function/variable in the code

soft kernel
eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

small mantle
ivory bobcat
soft kernel
small mantle
# soft kernel why do you need to check that?

This is the whole picture ```cs
[SerializeField] bool setKillAmount = false;

private void OnTriggerEnter2D(Collider2D collision) {

    if (!setKillAmount) {
        if (collision.CompareTag("Enemy")) {
            print("Counting");
            enemyCounter++;
        } 
    }
    

    if (collision.TryGetComponent<PlayerCollisionScript>(out PlayerCollisionScript playerCollision)) {
        playerCollision.currentRoom = gameObject;
    }
}
ivory bobcat
novel beacon
#

It worked

novel beacon
#

Yeah I searched up my problem on google and a site told me that resetting MEF cache could solve my problem

#

And it did

small mantle
ivory bobcat
small mantle
gaunt ice
#

you can let the rooms spawn the enemies then store them in their list/hashset/whatever

small mantle
#

How can I see how Untiy Executes their Methods? Like Awake is before Start, Start is before Update, etc

ivory bobcat
gaunt ice
#

you can just enter some numbers (of enemies) to the inspector of rooms monobehaviour, done

#
public class Room:Monobehaviour{
  [SerializeField]private int numberOfEnemies;
  
  private void Awake(){
    for(int i=0;i<numberOfEnemies;++i){
      //spawn the enemies and store them
    }
  }
}
ivory bobcat
#

If you're activating and deactivating rooms and their enemies, maybe consider resetting the room's kill count on enable so that you'll be able to recount the enemies properly?

small mantle
#

So, I found the solution because there was no issue. This whole time I thought OntriggerEnter2D would occur after Update method. I was wrong and could have stopped trying to find a solution to an imagined issue. My fault for not testing it sooner. notlikethis