#💻┃code-beginner

1 messages · Page 540 of 1

burnt vapor
#

And if the answer here is not "just add it" then you might need to explain a bit more as to why this is not possible

stiff pollen
#

I tried to "just add it" but it gave me an error

#

so I want to reference the player wall touch code to the Player's code

naive pawn
stiff pollen
#

reference ambiguity

rich adder
burnt vapor
rich adder
#

you have to show the full error

burnt vapor
#

Show the actual error. The console at least, or paste the error

pliant abyss
naive pawn
#

we can't really help you if you're going to dripfeed us information

pliant abyss
#

I am having a brain fart. When we are talking radians in computers, do we include pi when we express an angle as a floating point number?

naive pawn
#

no, that's not how radians work

pliant abyss
#

2 * pi => 1.0 right?

#

Because we measure the rotations

naive pawn
#

1 radian is not some specific fraction of pi, it's 2pi radians that completes a full turn

naive pawn
pliant abyss
#

right. So when I enter sin(1.0) the answer should be 0 because that's the y value on the unit circle

stiff pollen
naive pawn
#

when we express an angle as a floating point number?
what do you mean by this?

#

it's always a floating point number

stiff pollen
#

i'm just gonna skip this part

naive pawn
rich adder
naive pawn
#

π radians is 180°, so 1 radian is gonna be a little less than 60°

#

that might be easier to visualize

stiff pollen
naive pawn
#

ok... are you gonna tell us the specific error, or how exactly the code doesn't work?

pliant abyss
naive pawn
#

or how exactly your code differs?

stiff pollen
steep rose
#

give us a screenshot of the error

naive pawn
#

stop saying "an error" and "doesn't work"

#

those are not helpful pieces of information

stiff pollen
#

okay, we can forget this

pliant abyss
naive pawn
#

give the exact error, and if you can't, show it
explain how exactly the code doesn't work

stiff pollen
#

thank you for trying to help though

#

I really apprectiate it

naive pawn
stiff pollen
#

i'll ask again if something comes up with more detail

naive pawn
rich adder
coral fossil
#

i have a collectable item (just makes the ui number go up when collected) but i dont know how to get it to transfer across scenes

#

the number just resets when i enter a new scene

rich adder
#

SO are also viable option

coral fossil
#

i have no idea what that means lol MikuDerp but ty! ill look it up

rich adder
#

but you still need a holder for SO

coral fossil
#

mikuloves ty!

sage steppe
#

Heya, im making an AI code and I was going through a tutorial, though it was quite old it was helpful in making a random walking AI, however im having difficulty making it switch it's state into either chasing or attacking, is this a raycast problem or it is a problem with "whatIsPlayer" and how AI doesn't detect the whatIsPlayer layer, at least that's what I think? The code for the enemy is below along with some screenshots, if anybody knows how to modernise this code or fix it that would be really helpful!

#

(movement script is the player)

rich adder
eternal falconBOT
sage steppe
#

Should be all on here

rich adder
sage steppe
#

Im not sure

#

i think its more likely that the AI isnt seeing the player on the layer

rich adder
#

for example you can also change the colors of the gizmos based on your bools

steep rose
#

you should have the "what is player" layermask on the player for the checksphere to find it

sage steppe
#

yeah iv got that as a layermask

rich adder
#

are the bools on , did you look in the inspector?

#

CheckSphere sucks because it doesnt return you the collider so its hard to debug whats hitting if anything at all

steep rose
#

consider using 1 overlapsphere

sage steppe
#

Iv got one for sight one for attacking

rich adder
#

yes can see that lol

sage steppe
#

and all im getting is there are 2 audio listeners in the scene

#

in the console

#

"There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene."

steep rose
#

remove one

rich adder
#

thats not related rn

sage steppe
#

but its still following the random movement code

#

oh alr

rich adder
#

so did you check the two bools in the inspector? what are the values

steep rose
#

so the booleans are not true?

rich adder
#

put logs in the methods to see if they ever get hit

steep rose
#

overlapsphere is neat because it gives the array of colliders which is very useful for debugging

sage steppe
#

where would i see those?

rich adder
#

the what bools? in the inspector, they are public

sage steppe
#

a pain

#

im not getting anything though

#

let me try smthn

rich adder
sage steppe
#

(enemy is the one iv selected)

#

wait why did it auto crop

rich adder
#

cant see the inspector

sage steppe
#

thats better

steep rose
#

show player inspector

sage steppe
#

i added some print statements to print playerinattackrange and playerinsightrange and they arnt printing anything so

rich adder
#

okay . lets see the player also

sage steppe
#

why cant i say k lol

#

alr uhh here

#

iv tried setting the include layers to whatisplayer but that doesnt work

rich adder
sage steppe
#

there isnt anything else up?

#

do you mean scroll down?

rich adder
#

yeah i mean so I can see the object name and all its properties

sage steppe
#

oh this

rich adder
#

there you go

sage steppe
#

wait

#

i just

rich adder
#

player is in Default

steep rose
#

you are not using the layermask

rich adder
#

also the navmesh surface doesn't go on the player lol it should be on a static object

steep rose
#

that is a tag

sage steppe
#

I had it scrolled the whole time

sage steppe
#

lemmie change it and see if thats a fix

rich adder
sage steppe
#

it works so all good

steep rose
#

also consider using a overlapsphere so you can return the colliders and find the player and remove that find method

rich adder
#

if you use anything that returns more than 1 collider , use the nonalloc version
allocating a new array each time can get expensive

sage steppe
#

i dont see anything else so it seems good?

#

no other warnings

rich adder
sage steppe
#

yup

#

actually while im here how would i send something to the player so they open a UI and delete themselves

rich adder
#

if you plan on interacting with the player and its componens consider using the collider raycast/overlap

steep rose
rich adder
sage steppe
burnt vapor
# stiff pollen i'm just gonna skip this part

We asked you to share your code and/or give a proper description of the issue. You have done neither. If you want to be helped you have to give context to the people that try to help you, or we have to resort to all kinds of guess work, which includes just telling you to add it because we have no clue why you don't just do that

sage steppe
#

well i say think nothing is easy lol

rich adder
#

its not easy because there are so many ways to do something

sage steppe
#

sounds right

steep rose
rich adder
#

especially if its called in Update. Imaging creating a new array each frame, yeah not a good time for GC

steep rose
#

yes mine is called in update 😅

#

I should profile my project just to see what needs to be optimized

rich adder
#

Layers do help at least filtering much of the colliders but still

#

the unity profiling tools are pretty good tbh

#

you can get pretty granular info (its a rabbit hole)

steep rose
#

I have not used them before, so it should be an adventure trying to use it

rich adder
#

yeah start simple, heirarchy mode. Sort by GC or .ms you will see whats mostly causing hog. Ignore EditorLoop. ofc profiling is best done on a separate instance (executable)

steep rose
#

I will definitely check it out

rich adder
steep rose
#

sweet thanks

#

my game seems to be running at just below 4000 FPS, but I do see spikes in GC when the AI "sees" a player which I thought I was using the overlapsphere method but I just double checked and I'm using overlapcircleall.

#

It does say in the docs that it does allocate memory, I'm not entirely sure if there is any method that doesn't (for overlapcircle)

rich adder
#

also did you turn on deep profiling, it probably isnt a big deal with 1 enemy but multiply that by how many enemies you will spawn / have running at once

warm raptor
#

Hello, I'm trying to call a public void from one script to an other , but it don't work because the script that try to call the void is actually in a static class, and the void isn't static, so I have an error.
I tried to fixed the error by making my void static but it didn't work really well because , the UI that I'm trying to enable or disable in that script aren't static, and I can't set them as "static" because they won't appear in the Inspector anymore and because I already use them as non-static in other part of my script, so I wonder: Is their a way to call a void that's not static, from an other code that's in a static class ?

here's the part where I reference the script containing the void I want to call :

Myplayer = GameObject.Find("MainCharacter"); fpsController=Myplayer.GetComponent<FPSController>();

here's the part where I call the void :

if(MyLivingState == "0" && MyPreviousLivingState == "1")
{
    FPSController.Died();
}

and here's the void that I'm trying to call:

public void DiedUI()
{
    PlayerUI.gameObject.SetActive(false);
    LeaderBoard.gameObject.SetActive(false);
    DeathUI.gameObject.SetActive(true);
}
burnt vapor
#

Perhaps you want a singleton instance instead?

steep rose
burnt vapor
#

Ehh, forget the first question, but regardless you probably want to implement some singleton pattern

#

Even then, your static class can probably be non-static

#

@warm raptor

cosmic quail
steep rose
#

yes

#

but im using the allocation version of overlapcircle

cosmic quail
steep rose
#

yes which I will do

warm raptor
naive pawn
steep rose
#

that is what it said with deep profiling turned off

burnt vapor
#

Generally I advice you avoid big static classes unless they are purely utilities without states

#

The biggest reason to avoid this and to use singletons is because you can properly manage a single instance and it makes it testable

rich adder
swift elbow
warm raptor
burnt vapor
naive pawn
#

like, just processing as fast as it can

fickle kelp
#

What’s the difference between local and global?

swift elbow
fickle kelp
#

Like world coordinates

rich adder
fickle kelp
#

Oh ok that makes sense!

cosmic dagger
languid spire
#

local position/rotation is relative to it's parent. world position/rotation is relative to the world

cosmic dagger
#

ah, yeah. can't forget about the parent . . .

dense bridge
#

And it's the same with tools, you can rotate globally or locally depending of what you want to achieve (do i want to rotate the weapon locally (turning on hand) et rotate it globally (making my weapon point the sky))
It's the reference point

steep rose
cosmic dagger
#

i'd only use non-alloc versions anyway . . .

steep rose
#

I never used it properly before, I believe I saw it and tried to use it then failed

#

but it works well

cosmic dagger
#

generally, you have an idea of how many items a collection will have, even if it's an estimate . . .

#

plus, with testing, you can pinpoint if a more accurate number is needed . . .

queen adder
#

i need help, i keep getting errors when making a project???

languid spire
queen adder
tulip nimbus
#

Is there a cleaner way to write this code?

 {
     if (GameToPlay == 1) 
     {
         
     }
     if (GameToPlay == 2)
     {

     }
     if (GameToPlay == 3)
     {

     }
     if (GameToPlay == 4)
     {

     }
     if (GameToPlay == 5)
     {

     }


 }```
alpine fjord
swift crag
#

It sounds like you've put five different games into one component

rich adder
#

also use enums

swift crag
#

Perhaps each game should be its own component.

#

But if GameToPlay is really just "which round are we on?", then that's a different story

rich adder
#

maybe SO too?

tulip nimbus
swift crag
#

Explain what's going to happen in this function

languid spire
tulip nimbus
# swift crag Explain what's going to happen in this function

Before this function is a function that randomly selects a game out of a list of possible games, so each new Round there cannot be any duplicate games after 5 Rounds and all Games are played once. The GameToPlay variable simply stores an int to link to a minigame, which means that GameToPlay = 1 would mean the minigame "tag" is played. So if GameToPlay comes out to be 1, all the code in the if statement runs the code used for "tag". But i know that its not a very clean way of coding but since im a beginner this is what worked best but it gets complicated quickly.

naive pawn
rich adder
swift crag
#

yeah -- if you have a collection of games that are all used in the same way, put them in array or list

#

You should only have to write code to handle different kinds of things

naive pawn
#

also if you shuffle the list instead of randomly choosing one each time, you won't have issues with duplicates

swift crag
#

indeed. consider the Fisher-Yates shuffle (I don't think List comes with a Shuffle method)

rich adder
#

isnt list just Array with benefits?

swift crag
#

It's quite simple.

public static void Shuffle<T>(this List<T> list)
{
    int index = list.Count - 1;
    while (index >= 0)
    {
        int i = Random.Range(0, index + 1);
        if (index != i) (list[index], list[i]) = (list[i], list[index]);
        --index;
    }
}

look at me and my mildly clever use of tuples

slender nymph
#

yeah unfortunately c# doesn't have a built in shuffle method until .net 8, and it's on the Random class

swift crag
#

You pick a random pair of items and swap them, narrowing the range by one item each time until you're done

#

It's equivalent to randomly drawing items from the list without replacement and putting them into a second list

#

instead of putting the items in a second list, you just stick them at the end

slender nymph
#

also you could take that a step further and use IList<T> instead of just List<T> and you can support arrays with that extension method too. this was my extension method for it:

public static void Shuffle<T> (this IList<T> collection)
{
    for (var i = collection.Count - 1; i >= 0; i--)
    {
        var index = UnityEngine.Random.Range(0, i);
        (collection[i], collection[index]) = (collection[index], collection[i]);
    }
}
swift crag
#

Extension methods let you define new methods to call on existing types

#
    public static class ListExtensionMethods
    {
        public static void Shuffle<T>(this List<T> list)
        {
            int index = list.Count - 1;
            while (index >= 0)
            {
                int i = Random.Range(0, index + 1);
                if (index != i) (list[index], list[i]) = (list[i], list[index]);
                --index;
            }
        }
    }
#

a more complete example

#

and yeah -- go with IList to let this work on other kinds of data structures

#

List is a very specific type. IList lets you use anything that implements that interface.

#

(extension properties when)

stiff pollen
naive pawn
#

...so are you still stuck on the issue or not

stiff pollen
#

Still

naive pawn
#

so are you gonna tell us what the issue is

stiff pollen
#

But it's fine, I'm just gonna skip it

stiff pollen
naive pawn
stiff pollen
#

I know, maybe I'll take a look to another tutorial

naive pawn
# stiff pollen How should I describe the issue?

instead of saying there's an issue, provide details on what the issue is
if there's an error, show us the error and where it's coming from
if there's unexpected behavior, tell us what the expected behavior is and what the actual behavior is

toxic tiger
#

Hey, just wondering, surely there's a better way to write my if statement without having 4 or 5 && conditions in a row right? I've had a quick look but couldn't really find much. Any help would be appreciated, thanks is advance

wintry quarry
stiff pollen
# naive pawn instead of saying there's an issue, provide details on what the issue is if ther...

so I am trying to implement this. the thing is that mine doesn't work, tried to change stuff with no error or warning but still doesn't work

https://youtu.be/qcRRYeGMZ68?si=r38gXaSCVjI5kq0x&t=1499

How to add a jump action for a platformer controller and management movement animations while in the air. This is part of my Unity 2022 Platformer Crash course.

Reference Project Patreon Download ➣ https://www.patreon.com/posts/2d-platformer-73894085
2D Crash Course Platformer Tutorial Playlist ➣ https://www.youtube.com/playlist?list=PLyH-qXFkN...

▶ Play video
viscid fable
#

first time trying to code haah i tried making an enemy that shoots at you but...

swift crag
#
bool playerValid == player && player.alive == true;
bool enemyValid == enemy && enemy.health > 0 && !enemy.stunned;

if (playerValid && enemyValid) {
  // ...
}
toxic tiger
#

Ahh okay that makes sense

#

I'll just send my code quick if that's all good

#

Not sure how to do the whole code in Discord thing so will send it like this for now

eternal falconBOT
toxic tiger
wintry quarry
#

but yes break that up into individual lines

naive pawn
#

you probably don't need all the parens either

burnt vapor
umbral bough
#

Hey, when I am creating a new volume profile via editor script, do I need to recompile scripts to be able to access them?
Logging asset gives me null in this case https://pastebin.com/LhYXWuv0

naive pawn
stiff pollen
wintry quarry
#

Also replacing those FindWithTags calls with using your own Lists or HashSets to keep track of enemies and bullets would both clean up the code and make things more efficient.

toxic tiger
#

Perfect, thanks for help

stiff pollen
naive pawn
#

@stiff pollen are you going to tell us what the issue is

swift crag
#

What does "doesn't work" mean?

#

If it did work, you wouldn't be here 😉

naive pawn
west radish
#

yeah, the random.range part has confused me too

toxic tiger
west radish
#

all thats going to do is make it random whether the enemies shoot, but written like that, the chance of them shooting will go down the more enemies you have. 1 enemy and its something like 1/20 chance to shoot. 2 enemies is a 1/40 chance of shooting. Thats even if you reach that condition in the first place

naive pawn
stiff pollen
toxic tiger
#

Oh yeah I want the enemies to have a higher chance to shoot when there's less of them, I'm doing like a Space Invaders game

naive pawn
toxic tiger
west radish
#

what's the idea of the player.GetComponent<Animator>().GetCurrentAnimatorClipInfo(0)[0].clip.name condition? I'm reading that as you wanting to check if the player is in a death animation (presumably because you dont want to shoot the player that is already dead

naive pawn
toxic tiger
naive pawn
#

yeah

#

the Random.Range(..) == 0 wouldn't work because you aren't factoring framerate into that

toxic tiger
civic cradle
#

hey mates, where do I ask questions about the editor / IDE itself?
I'm losing it rn, not gonna lie

toxic tiger
#

Thanks btw, been here like 10 mins and learning so much already

civic cradle
#

thank you @wintry quarry

naive pawn
#

@stiff pollen i think this condition is reversed?

private Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.left : Vector2.right;

#

if x > 1, it's facing right, so it should check for a wall to the right, no?

rocky canyon
#

if the objects localScale of the X is Positive

naive pawn
rocky canyon
#

then ya,, Greater than that should be left..

rocky canyon
#

no wait.. greater than X is right

rocky canyon
#

-1, 0, 1, 2 ---> right right?

naive pawn
#

i mean, it depends on the initial direction. the initial direction here is rightwards

#

1 is rightwards, -1 is leftwards

#

so x > 0 should involve a check towards the right

#

the vector here is being used in a cast

rocky canyon
#

ya, all comes down to orientation, and scale i guess

#

pretty simple to debug.. w/ some empty gameobjects

#

also debug the values ur receiving in script make sure that matches ur expectations

dapper yarrow
#

Hello. I am trying to make a endless surfer game as practice (kinda like subway surfers). However, I am not sure how to implement rules to limit how the obstacles are being spawned. I am currently spawning them along with the tiles, by using random to decide which lane (left, mid and right) to spawn. I am unable to keep track of them and hence can not use any rule to limit them. Also, I think the way I am spawning them is not very optimal as well. I would be grateful if anyone can provide me some advices. Thanks!

My code for tiles generation
https://hastebin.com/share/wohohabipu.csharp

stiff pollen
naive pawn
naive pawn
stiff pollen
#

so what should I change?

naive pawn
#

swap Vector2.left and Vector2.right

stiff pollen
#

still stuck

naive pawn
#

make sure you've saved everything and let unity recompile

west radish
#

I know I'm late on this, but you could lay things like a little bit like this @toxic tiger it becomes a lot longer than what youve got, but some tricks here can make it a little more easier to read

int enemyBulletAmount => GameObject.FindGameObjectsWithTag("EnemyBullet").Length;
bool inRange => Mathf.Abs(transform.position.x - player.transform.position.x) < shootPositionRange;

bool isDead; //probably best to set this as true when the player dies, rather than rely on checking an animation

void Update()
{
  if(!isDead) //the player is not currently dead
  {
    EnemyShootLogic();
  }
}

void EnemyShootLogic(){
  if(enemyBulletAmount > 3)  {
    return;    //dont continue the rest of the function, too many bullets
  }

  if(!inRange)  {
    return; //dont continue the rest of the function, player isnt in range
  }
  
  if(some probability check here, like your random.range == 0.0)  {
    return; //dont continue the rest of the function
  }
  
  //perform the shooting code now
  //once you reach this line, it means all your previous conditions allow the enemy to fire

}
fickle kelp
#

Hey so I just started the junior programmer course on the unity website and I did everything right but when I open the prototype 1 scene in the assets folder the mountain and road are pink? How would I fix this?

wintry quarry
steep rose
naive pawn
wintry quarry
# fickle kelp

in general you should be using the exact same UNity version and project template as the tutorial to avoid issues like this

swift crag
swift crag
#

One option is to just create valid chunks of obstacles by hand and then spawn them in sequence. That way, it's impossible to create an unwinnable track.

stiff pollen
steep rose
#

they are most likely using URP instead of BIRP as it looks like they are using unity 6 which default template is URP

wintry quarry
west radish
#

its useful to have those if (blah) { return; } lines when you want to quit the function. Is the player out of range of the enemy? No point checking any other condition after, therefore you return

toxic tiger
naive pawn
swift crag
naive pawn
#

if there's unexpected behavior, tell us what the expected behavior is and what the actual behavior is

toxic tiger
dapper yarrow
keen cargo
#

hey yall, i've got a theory question

using the unity animator as a state machine (for code) - yay or nay?

watched my teacher do it and it just looks way too complicated for implementing a state machine

dapper yarrow
rocky canyon
#

might as well learn other methods imo..

#

even a simple enum statemachine. but i like stateless statemachines

keen cargo
#

yeah it just looks really unwieldy, by the way how my teacher did it at least

rocky canyon
#

yea.. teacher sounds sus

#

unless he just showcasing that the animator is basically a statemachine

keen cargo
#

he did mention that it basically is one, and then how to make it into one for code

swift crag
#

If you put the walls too close together, you might create an unwinnable obstacle.

rocky canyon
#

"simple"

keen cargo
swift crag
#

average VRChat asset

stiff pollen
# naive pawn alright, can you get more detailed iwth what exactly the issue is

that's the thing I don't know what's wrong, I was trying to make the character not stuck on the wall with those code, it doesn't give me an error but it just doesn't work, the character still get stuck and I get those codes from here https://youtu.be/qcRRYeGMZ68?si=r38gXaSCVjI5kq0x&t=1499

How to add a jump action for a platformer controller and management movement animations while in the air. This is part of my Unity 2022 Platformer Crash course.

Reference Project Patreon Download ➣ https://www.patreon.com/posts/2d-platformer-73894085
2D Crash Course Platformer Tutorial Playlist ➣ https://www.youtube.com/playlist?list=PLyH-qXFkN...

▶ Play video
keen cargo
#

legend of zelda topic came up and he said he hates it because of how feminine Link is

#

which is like

#

?? huh ??

toxic tiger
dapper yarrow
rocky canyon
#

may be a good read.. if u just scoping out statemachines in general

keen cargo
#

i do definitely want to use state machines as i really liked the idea from an old electronics lesson we had

#

they just seem fun to tinker around with

rocky canyon
#

yup, the beginnings of ur AI journey

keen cargo
#

but seeing the mumbo jumbo my current teacher is propagating just stunlocked me

rocky canyon
#

can't have Game AI w/o a statemachine of some sorts

west radish
keen cargo
#

another teacher i had did show how to do state machine in a way, which was super cool, with all the patrol, alert, chase states

rocky canyon
#

just b/c its visual..

steep rose
keen cargo
#

i think the statemachine he made is for loading screens too

west radish
#

All it means is any time something wants to get the value of enemyBulletAmount the => means the code will quickly "get" the value in that moment

rocky canyon
keen cargo
#

like yeah

toxic tiger
rocky canyon
#

if its just managing screens and stuf

keen cargo
#

ahh i see

rocky canyon
#

or maybe even Game states

#

in a smaller game

naive pawn
rocky canyon
#

Your Turn -> Action -> Enemy Turn -> Action etc

swift crag
dapper yarrow
toxic tiger
steep rose
# rocky canyon lol.. AI *Budget Edition*

mine is going to be based off of percentages so its semi random, so it gives the illusion of higher "Intelligent" AI instead of 100% scripted movements if certain conditions are met

#

should be pretty interesting to do

keen cargo
west radish
rocky canyon
west radish
#

haha, years of programming and I always forget the name of things

rocky canyon
#

yea.. codes is hard

west radish
#

I vote to call them "the word that is the name of the thing you put numbers inside"

toxic tiger
rocky canyon
steep rose
rocky canyon
rocky canyon
rocky canyon
#

thats more about telegraphing..

steep rose
naive pawn
#

a variable (or field, in this case) holds a value

west radish
naive pawn
#

but a property is like a function, in the math sense
you call it to evaluate a new value

rocky canyon
rocky canyon
#

@steep rose care to share a snippet or so of how ur doing it?

steep rose
toxic tiger
steep rose
naive pawn
rocky canyon
#

float randomValue = Random.Range(0, totalWeight);

#

ezpz

west radish
#
  int TextureWidth, TextureHeight;
  Vector2Int TextureDimensions => new(TextureWidth, TextureHeight);```Theres one way I use it, but there its more just out of laziness than me wanting to create the Vector2Int elsewhere
toxic tiger
naive pawn
#

an example might help

swift crag
#

A property is a member that has field-like syntax, but that invokes methods when you access it.

rocky canyon
#

u can read about stuff all day long. theres not quite an alternative than actually using it

toxic tiger
rocky canyon
naive pawn
#
using System;
class Example {
  static Random rand = new();
  int field = rand.Next();
  int prop => rand.Next();
  int Method() { return rand.Next(); }
  void Ex() {
    Console.WriteLine("With field");
    for (int i = 0; i < 5; i++) Console.WriteLine(field);
    Console.WriteLine("With prop");
    for (int i = 0; i < 5; i++) Console.WriteLine(prop);
    Console.WriteLine("With method");
    for (int i = 0; i < 5; i++) Console.WriteLine(Method());
  }
  static void Main(string[] args) { new Example().Ex(); }
}
```@toxic tiger try running that in an online c# compiler
#

(whoops, forgot about the static thing)

toxic tiger
rocky canyon
steep rose
#

This is what I have so far

toxic tiger
toxic tiger
#

If you're trying to show through example this is maybe a little too much for me to understand

naive pawn
#

try running it and just look at the output first

toxic tiger
#

Yeah I have

naive pawn
#

(not in unity, try googling for online c# compilers)

#

so notice that with a field, it doesn't change

#

it actually holds the value from rand.Next()

#

but with the property and method, it changes each time, because rand.Next() is called again each time

fickle kelp
#

Whats the short cut to open the project tab?

naive pawn
#

but the property is accessed like a field, rather than a method.

toxic tiger
#

Ahh okay I get you, different outputs of same thing with field, property, method?

languid spire
naive pawn
#

different behavior, specifically

fickle kelp
#

Thanks!!

toxic tiger
#

So obviously field stays the same, but are property and method doing the same thing or no?

fickle kelp
languid spire
wintry quarry
naive pawn
toxic tiger
#

Okay definitely understand more now, but as I said, to understand fully probably need to use it for myself

#

Thanks for all the help, defo learnt a lot

swift crag
#

create asset, then immediately load an asset at its path

umbral bough
swift crag
#

Print out the path of the asset after you create it and compare it to the path you’re constructing

#

(you can ask the asset database what the path for an object is)

umbral bough
umbral bough
#

I see the GetAssetPath but it expects an id

swift crag
#

It takes either an instanceID or a unity object

tawny edge
#

want to say that i just arrived at the part in my course that starts explaining coroutine!

swift crag
#

neat (:

umbral bough
swift crag
#

you already have a unity object!

#

I believe you can call this on the object you just passed to CreateAsset

umbral bough
#

oh 🤦‍♂️

swift crag
#

I could be wrong about that, though. I just noticed I did something...pretty silly

umbral bough
#

sure, imma test it either way, doesn't hurt

swift crag
#
var found = AssetDatabase.FindAssets("t:IconSet " + key, new string[] { BASE_PATH });

IconSet iconSet = CreateInstance<IconSet>();

if (found.Length == 0)
{
    var set = CreateInstance<IconSet>();
    AssetDatabase.CreateAsset(set, BASE_PATH + setName + "/" +  key + ".asset");
    found = AssetDatabase.FindAssets("t:IconSet " + key, new string[] { BASE_PATH });
}

iconSet = AssetDatabase.LoadAssetAtPath<IconSet>(AssetDatabase.GUIDToAssetPath(found[0]));
#

I believe I had to do this because the reference stored in set is not the same reference that you'd have gotten from LoadAssetAtPath

#

So that would imply you can't ask for the path of the object you passed to CreateAsset

umbral bough
#

yeah, that would make sense to me ig

#

I do have a function that would ask for the script compilation, I just find it odd that you'd need that after creating an asset

#

thought that save+reload would be enough

willow sand
#

I'm busy adding a feature where my cursor changes when im in different states the states are decided by tags and layers I don't know whats wrong its not changing the cursor but i added debugs and its running but not changing

eternal falconBOT
wintry quarry
willow sand
#

what do you mean how do i fix this

wintry quarry
#

All I see are markerInstance?.SetActive(false);

#

(which btw is duplicated 5 times unnecessarily)

#

Share your code with paste sites so I can actually see line numbers

willow sand
#

theres line 119

wintry quarry
#

the only thing SetMarkerType is doing right now is deactivating objects

#

SHouldn't you be *activating * the new cursor?

#

I would expect SetMarkerType to:

  • Deactivate the old one
  • Activate the new one
#

right now you're only doing the deactivate part.

west radish
# willow sand

if you post a code screenshot, you really should include the line numbers in the image

wintry quarry
#

Or better yet - don't poost screenshots

west radish
#

any of those could be line 119

wintry quarry
polar acorn
eternal falconBOT
willow sand
#

at the bottom i added it so that it turns it true

#

is this correct

wintry quarry
#

overcomplicated

willow sand
#

line 106 is red

wintry quarry
#

Also:
(type = currentCursor) this doesn't make sense and is going to assign the thing

#

There's no need to duplicate all this code

polar acorn
willow sand
#

what should I do

polar acorn
polar acorn
willow sand
#

he told me that there is no lines that activates the cursor so i added one that activates it by copying the deactivation one and changing it to false to true and from != =

wintry quarry
wintry quarry
#

and duplicated the whole if statement and switch for some reason

willow sand
#

it still doesn't work

wintry quarry
#

Define "doesn't work"

#

Take some simple debugging steps here

#

add some logs

#

see what's happening

willow sand
#

the cursor does not get assigned

wintry quarry
#

start debugging your code to see why

polar acorn
willow sand
#

yeah

wintry quarry
#

what makes you so sure

polar acorn
willow sand
#

i fixed it

devout flume
#

Lmao

umbral bough
swift crag
#

You must have the wrong path.

umbral bough
#

I am loading a different asset in almost the same way

#

yeah, here's the other thing I'm doing:

            var so = CreateInstance($"{_sceneName}ConfigData");
            var soPath = Path.Combine(_sceneDir, $"{_sceneName}ConfigData.asset");
            AssetDatabase.CreateAsset(so, soPath);
            var sm = AssetDatabase.LoadAssetAtPath<ConfigData>(Path.Combine(_sceneDir, $"{_sceneName}ConfigData.asset"));
coral fossil
#

it worked fine before but then i added a script to change scenes and now for some reason whenever i touch the collectable it also transfers me to the next scene

#

when its not supposed to

#

im not sure whats making it do that

#
using UnityEngine;
using UnityEngine.UI;

public class Collectable : MonoBehaviour
{
    public Canvas canvas;
    private TextMeshProUGUI scoreText;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        if (canvas == null)
        {
            Debug.Log("Could not find canvas");
            return;
        }

        var child = canvas.transform.GetChild(0);
        if (child == null)
        {
            Debug.Log("Could not find child transform");
            return;
        }

        scoreText = child.GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            scoreText.text = "<sprite name=\"collectooble\"> 1";
            Destroy(gameObject);
        }
    }
}
``` this the the code for the collectable
#
using UnityEngine.SceneManagement;

public class ToNextScene : MonoBehaviour {
    private int nextSceneToLoad;

    private void Start()
    {
        nextSceneToLoad = SceneManager.GetActiveScene().buildIndex + 1;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        SceneManager.LoadScene(nextSceneToLoad);
    }
}``` and this is the code for the scene transfer
naive pawn
#

you sure you aren't just hitting the scene transfer thing as well?

swift crag
#
    private void OnTriggerEnter2D(Collider2D collision)
    {
        SceneManager.LoadScene(nextSceneToLoad);
    }

This punts you to another scene if this function gets run, ever

#

It doesn't care what got hit

coral fossil
#

ohh

naive pawn
#

mightve accidentally added it to some random object

#

or set up layers incorrectly yeah

swift crag
#

So, for example..what if the collectible hits the scene-change zone?

#

(I'm not sure what object ToNextScene is on)

#

If it's on the player, then touching any trigger collider will take you to another scene

coral fossil
#

its on the collider that needs to be touched to trigger a scene change

#

but the collectable and collider arent on top of eachother

swift crag
#

to sanity check that you don't have extra scene-change components in your scene, search for this in the Hierarchy search box

#

t:tonextscene

#

This will show you every object with a ToNextScene component on it

coral fossil
#

ah it is on the character too right

#

the tutorial i watched said to put it on both the character and the collider

swift crag
#

Perhaps it meant to have two different components?

#

One could look for the other and only do the scene change if that second component is found

#

That way, random stuff crashing into the trigger zone won't do anything

coral fossil
#

how would i go about doing that?

swift crag
#

I think you missed something in the tutorial.

#

Go back and have a closer look

coral fossil
#

got it working!! tysm

swift crag
#

no prob!

#

I'm guessing it wound up being something like

#
void OnTriggerEnter2D(Collider2D other) {
  if (other.TryGetComponent(out Player playerComponent)) {
    // do the scene change 
  }
}
coral fossil
#

MikuDerp i just wasnt supposed to attach the script to the character

swift crag
#

Ah, that works too :p

coral fossil
#

but now my collectables arent working so im trying to get that working again!! yay

swift crag
coral fossil
#

ah okayy

jaunty coyote
#
    private void Update()
    {
        ai = gameObject.transform.GetComponent<zombieAI_1>();
        
    }``` why is ai always returning null? getcomponent isnt working at all
swift crag
#

which component is this code from?

#

Ragdoll?

jaunty coyote
#

For more context, im trying to access the zombieai script from the Ragdoll script

swift crag
#

The names don't match

#

one is called Zombie AI_1 and one is called ZombieAI

#

That could be down to how Unity displays component names vs. the actual class name

jaunty coyote
#

oh, oooooh

#

thanks, looks like i have 2 of the same scripts, have a nice day ❤️

ionic wing
#

getting a strange error trying to do a room transition

#

heres my code for the room move function

swift crag
#

It's complaining about your method's parameter type

#

Look at the type you asked for in the method vs. the type Unity is trying to give it

wintry quarry
long jacinth
#

https://paste.ofcode.org/TceFXeR6itqvqdyBW24XaA I have a script that is on different gameObjects a function should be deleting two buttons but it isnt and bec its on different gameObjects i have been told this is the problem how can i solve this so it deletes for all

wintry quarry
wintry quarry
#

You should really avoid stuff like this:

        GameObject buildImage = instantiatedButton.transform.GetChild(0).gameObject;
        GameObject buildText = instantiatedButton.transform.GetChild(1).gameObject; 
        GameObject costText = instantiatedButton.transform.GetChild(2).gameObject; 
        GameObject lvlText = instantiatedButton.transform.GetChild(4).gameObject;
long jacinth
wintry quarry
#

Put a script on the thing you are instantiating

#

have that script manage all of its internal stuff

#

this script should not "reach inside" another object like this

#

This code should look something like:

BuildButton instantiatedButton = Instantiate(buildButtonPrefab, Spawn.transform.position, Quaternion.identity, Scroller.transform);
instantiatedButton.Initialize(BStats);```
#

Then have that script do all the initializing inside itself

#

see how much cleaner and more readable this is?

#

Anyway It's unclear where you are trying to "delete" buttons here

#

I don't see anything that looks like that

long jacinth
#

foreach (GameObject buildButton in buildButtonDelete)
{
Destroy(buildButton);
}

wintry quarry
#

so you will need to be more specific about where your problem is

long jacinth
#

but i realized thats not effecient since there are different gameObjects

#

using the script

#

my question is how to delete all the buttons for all scripts

ionic wing
#

This message parameter has to be of type: Collider2D
The message will be ignored.

wintry quarry
ionic wing
#

would it be the other that needs to be replaced?

polar acorn
wintry quarry
#

are you calling ShowCountryStats multiple times on this same instance?

wintry quarry
#

look at ythe parameter you have

#

and look at what it's asking for

ionic wing
#

what does that mean though

wintry quarry
ionic wing
#

i have collider2d there

wintry quarry
long jacinth
ionic wing
#

i did i still dont get it

polar acorn
ionic wing
#

on trigger enter 2d...

long jacinth
wintry quarry
polar acorn
wintry quarry
ionic wing
#

i changed that

wintry quarry
ionic wing
#

wb other?

polar acorn
#

Problem solved

wintry quarry
ionic wing
#

ah

#

alr

polar acorn
ionic wing
#

lmfao

polar acorn
#

That's the name you are deciding to give the variable

#

it means nothing intrinsicly

ionic wing
#

alr it worked wow

#

problem is it doesnt warp me to the gate

#

it warps me completely out of reach

#

player change is def the issue

#

dunno what values id have to put tho...

#

thank you for the help tho

umbral bough
#

Hey @swift crag, I am 99% sure that the path isn't wrong now, are you still sure that's it?
https://pastebin.com/i13XaPTw
Sorry for the @, it's been a while since you answered and I won't do it again.

wintry quarry
# ionic wing

rather than hardcoding numbers in the inspector why don'y you just make an empty GameObject specifying where youi want to move the player to?

long jacinth
#

i got an idea how about i delete all gameObjects in the scene with a certain Tag aka button tag

swift crag
# swift crag No prob :p

Maybe try loading a plain UnityEngine.Object instead of a VolumeProfile? That shouldn’t change anything…

umbral bough
#

oh

bold plover
#

Is it possible for an IDE to "unconfigure" itself? It seems like it no longer wants to work with my scripts in VS despite updating.

#

Weird.

swift crag
#

I’m curious to see what falls out

ionic wing
#

i have one year left b4 i go into
college and id like to learn how code works

umbral bough
#

I don't see a function to convert gui to path

swift crag
#

AssetDatabase.GUIDToAssetPath

umbral bough
#

but it logged 5 assets regardless, there should be 6

swift crag
#

I see 6 things in this folder--

#

yeah

#

You could quickly check by opening the .meta file for the asset of interest and seeing if its GUID is in that list

umbral bough
swift crag
#

Interesting. Your asset does not exist in the eyes of the AssetDatabase

long jacinth
#

ButtonDelete.Add(GameObject.FindGameObjectsWithTag("BuildingButtonTab"));
This is not working even tho my object is a list for some reason

umbral bough
swift crag
#

try reimporting the profile asset

umbral bough
#

gimme 5 min cuz that includes a bit of code refactoring

umbral bough
swift crag
#

right click on the asset in the Project window and click Reimport

umbral bough
frail hawk
swift crag
#

It sounds like something is in a Weird State (tm)

umbral bough
#

Imma need a bit of time to test the reimporting stuff cuz I need to isolate the function for getting the asset

vocal wharf
#

I'm currently trying to make my own AI random roaming script from scratch for a snowman npc in my game and it's not going well...
My basic idea was to invoke a method every 30 seconds that adds a slightly varying number to the current position and calls that the target position and reports the number in debug.log. The script then moves the npc to the target position. However this is not working correctly, as at the beginning of runtime when the method is first invoked, the script records the current position as "(0, 0)", when in reality the starting transform of the npc is more like (39 , -323). It does record a target position that is within (25, 25) and seemingly moves to that position, then when the method is invoked a second time the npc logs its correct transform and a target position within 25 units of the current position. However the npc never tries to move toward that second target position. Any help would be greatly appreciated.

public class SnowmanAI : MonoBehaviour
{
    public Rigidbody rb;
    public float roamingSpeed = 1f;
    private Vector3 targetPos;
    private Vector3 currentPos;
    void Start()
    {
        Invoke("FindNextTargetCoordinate", 0f);
    }
    void Update()
    {
        currentPos = transform.position;
    }
    void FixedUpdate()
    {
        rb.AddForce((targetPos - currentPos) * roamingSpeed * Time.deltaTime);
    }
    void FindNextTargetCoordinate()
    {
        targetPos = new Vector3(currentPos.x + Random.Range(-25, 25), 0, currentPos.z + Random.Range(-25, 25));
        Debug.Log("Current Coordinate: (" + currentPos.x + ", " + currentPos.z + ")" + "Target Coordinate: (" + targetPos.x + ", " + targetPos.z + ")");

        Invoke("FindNextTargetCoordinate", 30f);
    }
}
long jacinth
#

but a new problem appeared

#

wait i think i know a solution

coral fossil
#

hii sorry im back miku_high

coral fossil
#

it worked fine before

#

but now when i try to interact it just doesnt do anything

swift crag
#

Check if the code is running at all

#

you can log before and after the if statement in the trigger enter method

burnt vapor
swift crag
#

Also consider logging the thing you hit

coral fossil
hexed terrace
#

triggers aren't for UI..

swift crag
#

you've already got a few log statements!

swift crag
#

it is a little silly to directly talk to the text component on the HUD, though

hexed terrace
#

it does a getcomponent for the TMP, assuming this component has been placed on UI

#

oh, perhaps not.. it's doing it on the canvas.. with a load of unnecessary code to get a child component

vocal wharf
rich adder
umbral bough
# swift crag right click on the asset in the Project window and click Reimport

no need to do that, I just waited for the execution of my regular scene creation to execute, ran the thing that gets and prints stuff and it printed everything correctly :/

        [MenuItem("Assets/Test", false, -202)]
        private static void Test()
        {
            // Assign the newly created profile to it
            var assets = AssetDatabase.FindAssets("", new [] { "Assets/Scenes/Test8" });
            foreach (var asse in assets) Debug.Log(asse);
        }
vocal wharf
tawny notch
vocal wharf
#

I just want a snowman npc that roams around to random points

rich adder
#

whic log is that, also you should not put Time.deltaTime inside AddForce

hexed terrace
#

FindNextTarget is called before the first Update, so CurrentPos hasn't been updated

vocal wharf
vocal wharf
#

so I should just add a delay on the first invoke?

rich adder
#

why do you even need that current pos in update?
just put the transform.position when you do the FindNextTarget

hexed terrace
#

Using Invoke() is poor btw .. especially with a string to call it. It inevitably leads to problems which the IDE can't catch. If you really must use Invoke() don't use strings with it, use Invoke(nameof(FindNextTargetCoordinate));

hexed terrace
vocal wharf
coral fossil
#

i have the singleton set up

#

but when i collect a thing in the next room it just overlaps the "1" again

hexed terrace
#

int++

coral fossil
#

instead of counting up to 2

coral fossil
rich adder
#

int myInt = 0
myInt++ is same as myInt += 1

coral fossil
#

ah ok tysm!!

vocal wharf
#

shoot lemme remove the deltatime thing quick

wintry quarry
#
  1. this is going to rocket the thing towards the target position
vocal wharf
#

I know I forgor

wintry quarry
#

it's going to accelerate constantly

#

like a rocket

vocal wharf
#

lezgo it works after I removed time.deltatime

umbral bough
#

Hi, how do you set the profile of a volume with an editor script?
I tried the following:

            // Store the path
            var path = Path.Combine(_sceneDir, $"{_sceneName}VolumeProfile.asset");
            
            // Create a new game object
            GameObject go = new("GlobalVolume");
            
            // Attach volume component to it
            var vol = go.AddComponent<Volume>();
            
            // Assign the newly created profile to it
            var asset = AssetDatabase.LoadAssetAtPath<VolumeProfile>(path);
            Debug.Log(asset);
            vol.profile = asset;

And I do get the asset back as seen in the screenshot, but it doesn't get set in the inspector.

vocal wharf
#

either way I'm happy that it works now, thank you guys for the help

wintry quarry
vocal wharf
#

just gotta make the snowman griddy now 😤

wintry quarry
#

it will continually accelerate

#

it's just a slow acceleration if the number is low

#

if you're happy, it's fine

vocal wharf
wintry quarry
#

it's your game

#

you can move it how you want

#

it depends on what your desired motion is like

vocal wharf
#

well now that I think about it, it would make more sense if it were a constant speed/motion

#

would rb.velocity or rb.MovePosition do that?

#

sorry I should google that

wintry quarry
vocal wharf
#

yes rate of motion in a certain direction

wintry quarry
#

so if you want a constant rate of motion in a certain direction, it stands to reason you want to set the velocity, right?

vocal wharf
#

yeah

#

I'll implement it 👍

umbral bough
# swift crag I just want to see if anything changes when you do that

Hey Fen, I managed to fix it.
Turns out that recompiling stuff was necessary afterall.
On top of that, we both missed the fact that, for some reason, you are not supposed to set the profile property of the volume but sharedProfile instead, awesome...
With all that, it works flawlessly now.
Thanks for helping along the way!

swift crag
#

Oh, that would not help, yes.

#

profile is like material on a renderer

#

you get an instantiated copy

#

I don't see why recompiling would be needed to create and load a VolumeProfile, though. That type already exists

umbral bough
#

I tried calling the regular reload and that didn't help, I'll try once again for good measure:

        private static void Reload()
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
swift crag
#

Perhaps the new assets did not appear until the recompilation process finished

#

(since recompiling is triggered by importing new or modified code assets)

umbral bough
#

quite possibly

#

I mean it's one more reload, which is like 5-10 seconds so not a big deal, especially considering the fact you won't be doing this process to often

whole sequoia
#

hello everybody , can anybody help me out with this error pls

wintry quarry
whole sequoia
wintry quarry
#

step 1 - read the error message

#

what does it say?

whole sequoia
wintry quarry
# whole sequoia

Right because you have this:
orientation.right * (Input.GetKey(Left) && Input.GetKey(Right))

polar acorn
wintry quarry
#

Input.GetKey returns a bool

#

bool && bool also gives you a bool

#

orientation.right is a Vector3

#

WHy are you trying to multiply a Vector3 by a bool?

#

what do you expect that to do?

whole sequoia
wintry quarry
#

i.e. orientation.right * Input.GetAxis("Horizontal")?

#

think about it

#

GetKey merely tells you if a particular keyboard key is pressed

#

which is true or false

#

GetAxis gives you a numerical value between -1 and 1 for the given input axis.

whole sequoia
#

ok got it

#

thank u tho

coral fossil
#

i updated my code but it only counts up to 1 still, and just overlaps after

#
    {
        if (collision.gameObject.CompareTag("Player"))
        {

        // Increment the score
        int myInt = 0;

            scoreText.text = "<sprite name="collectooble"> " myInt++

            Destroy(gameObject);
        }
    }
}
wintry quarry
#

The comment says "increment the score"

#

but that's not whjat this code is doing at all

#

this code is:

  • declaring a brand new local variable called myInt
  • incrementing that brand new local variable
#

no other code can see that brand new variable

#

and it will promptly disappear as soon as this method finishes executing

#

Also this line: scoreText.text = "<sprite name="collectooble"> " myInt++won't even compile as it's missing basic syntax elements such as a + between the string and the int variable as well as a semicolon

coral fossil
#

oh right i forgot that

coral fossil
wintry quarry
#
  1. If you don't have some central manager for tracking the score with one single central score variable, you need to create one
coral fossil
#

ill try that out, thanks!

vocal wharf
#

My npc now successfully moves to the target location, but since I'm multiplying the rb velocity by the difference between the target position and the current position, the velocity scales down as the npc gets closer to the target point. I want it to have a constant velocity and stop at the target point. I know my moving code can't do that, I just don't know of another way to do it... 😕

void FixedUpdate()
{
    Vector3 moveDirection = targetPos - currentPos;
    rb.velocity = moveDirection * roamingSpeed * Time.deltaTime;
}
wintry quarry
#

As for stopping you can check your distance to the destination and if it's within a certain threshold, then stop

#

Really the "right" way to do it would be to check if your velocity would bring you to the target point within a single fixed timestep, and if it would, set a lower velocity that moves you to the target point in exactly one physics frame. After that, stop.

tepid rover
#

I want make regenRate in health after 5 sec 2d game ?

#

how

#

@wintry quarry

polar acorn
rich adder
#

maybe throw in a bool for good measure

tepid rover
#

private void RegenerateHealth() { currentHealth += Mathf.RoundToInt(regenRate * Time.deltaTime); currentHealth = Mathf.Clamp(currentHealth, 0,(int) maxHealth); sliderhealt.SetHealth(currentHealth); }

rich adder
# tepid rover show me :)
public void Regen(){
    if(health < maxHealth && !healthRegen){
    StartCoroutine(RegenHealth());}
}
IEnumerator RegenHealth(){
    healthRegen = true;
    yield return new WaitForSeconds(5);
    while(health < maxHealth)
    {
        health += Time.deltaTime * healthRegenRate;
        yield return null;
    }
    health = maxHealth;
    healthRegen = false;
}```
#

ideally you call the Regen in a hit method or something

#

probably want to store it in a coroutine variable to deal with canceling old routine for new 5 sec timer when multiple hits in row happen

cerulean bear
#

private Vector3 spawnRotation = new Vector3(0, 0, 0);

can Vector3 be used like this for rotation?

rich adder
cerulean bear
rich adder
swift crag
#

Quaternion.Euler is a method

#

That would make sense if Euler was a nested type inside of Quaternion

#

e.g.

#
public class Quaternion {
  public class Euler {
  
  }
}
#

magic keyboard, please

#

That's not the case, though. Euler is a method of the Quaternion struct that calculates a rotation from Euler angles

cerulean bear
#

oh ok thx

west radish
#

useless fun fact: Euler is commonly mispronounced as "you-ler", when in fact its actually pronounced "oy-luh"

swift crag
#

much like "oiler"

umbral bough
#

that made my overcomplicated solution sound simple 💀

#

I think that the solution to the message you replied to was simple using sharedProfile instead of profile, lemme make sure

coral fossil
#

my ui buttons work fine in the editor, but dont work in the build. is there something i did wrong?

tawny edge
#

`what am i missing here?
I seem to be misunderstanding how to apply a Vector3

        {
            transform.rotation = new Vector3(0,0,0);
        }```
rich adder
#

if you want to give it a v3 you need Euler function from Quaternion struct

tawny edge
#

i just need to set all of it's rotations to zero

rich adder
#

Quaternion.Identity should do fine

tawny edge
#

i don't know how to use Euler, Quaternions or what a struct is

rich adder
#

the struct part is not relevant, struct and class are similar.

tawny edge
#

thanks!

ivory breach
#

I am having trouble trying to instantiate a tmp text on top of an enemy the player destroyed. Can someone help?

rich adder
spark sinew
#

hi quick question, is there a built in function to display an arrow to point to a particular object in the 3D space? A bit like the arrows you have in video games when you get shot at

#

(basically the arrow making you turn your head towards the object)

rich adder
#

idk what you mean display an arrow though

ivory breach
#

I don't exactly know how I can do that

rich adder
ivory breach
rich adder
#

its just a 3D object with a material/shader

swift crag
#

TextMeshProUGUI is the UI version

#

The former can stand on its own, and makes sense for in-world popups like this

#

I would suggest creating a ScorePopup component that's responsible for:

#
  • setting the text based on the amount of points
  • making the text move (if desired)
  • destroying the object after enough time passes
rich adder
ivory breach
swift crag
#

You can turn a world position into a screen-space position (look at the methods on the Camera component), clamp the result based on the screen's size (see the Screen class), and then convert back to a world position

#

if the screen position's x value is less than 50, make it 50; if it's more than Screen.width - 50, make it Screen.width - 50

#

that kind of thing

ivory breach
#

Ok, I'll think about it

spark sinew
#

(the offscreeen target indicators)

rich adder
swift crag
#

you can look at the signed angle between the player's forward vector and the vector to the enemy

spark sinew
#

yes, when you are not looking in the right direction. Do you have to build it yourself or is there something built in ?

rich adder
#

i have a script somewhere.. shite.

swift crag
#

There isn't a component for this, no

swift crag
#

Then lerp between that point and the edge of the screen as it gets close to the edge

#

so that when they go off screen, the indicator slides to the edge and then stops there

spark sinew
#

I did something quick and dirty by looking at the cross product of these vectors (component of the cross product on vertical axis) and the angle but meh

#

I do not develop a game it is just for research

rich adder
#

I shamely used the codemonkey tutorial when I did it, so I'm no help there 😛

swift crag
#

I'm still fussing with the effect

wraith condor
#

are 3d tilemaps good for a minecraft like game?

#

do they have chunk support and mesh combining?

somber herald
#
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    [Header("Jumping Settings")]
    [SerializeField] private LayerMask ground;
    [SerializeField] private float distFromGround = 1;
    [SerializeField] private float jumpPower = 1;
    [SerializeField] private float cooldown = 0.2f;

    [SerializeField] private float jumpTimer = 0;

    [Header("Movement Settings")]
    [SerializeField] private Rigidbody rb;
    [SerializeField] private float speed = 1;
    [SerializeField] private float maxVelX = 1;
    [SerializeField] private float maxVelZ = 1;
    [SerializeField] private Transform head;
    [SerializeField] private float rotateToHeadDamp = 0.3f;
    [SerializeField] private float acceleration = 0.3f;

    [Header("Debug")]
    [SerializeField] private bool grounded;
    [SerializeField] private float timer = 0;


    void Update()
    {
        float w = Input.GetAxisRaw("Vertical");
        float a = Input.GetAxisRaw("Horizontal");

        Vector3 mForward = transform.forward * w * speed;
        Vector3 mRight = transform.right * a * speed;
        Vector3 combined = new Vector3(mForward.x + mRight.x, rb.velocity.y, mForward.z + mRight.z);

        rb.velocity = Vector3.Lerp(rb.velocity, combined, acceleration);

        if(Input.GetAxisRaw("Jump") != 0)
            Jump();
        grounded = Grounded;
        timer = Time.time;
    }

    void Jump()
    {
        print("Worked");
        // If jump too recent return.
        if (timer >= jumpTimer + cooldown)
            return;

        print("Nope");
        // Grounded check
        if (!Grounded)
            return;
        print("Yep");

        rb.velocity += new Vector3(0, jumpPower, 0);
        jumpTimer = Time.time;
    }
    bool Grounded => Physics.Raycast(transform.position, transform.up * -1, distFromGround, ground);
}

I have this code that doesnt work its supposed to jump every 0.2 seconds maximum but it doesnt jump at all

#

in ```cs

void Jump()
{
    print("Worked");
    // If jump too recent return.
    if (timer >= jumpTimer + cooldown)
        return;

    print("Nope");
    // Grounded check
    if (!Grounded)
        return;
    print("Yep");

    rb.velocity += new Vector3(0, jumpPower, 0);
    jumpTimer = Time.time;
}
#

It prints "Worked" and thats it

#

Somehow its returning even though timer is way more than 0.2

rich adder
#

debug your timer

somber herald
#

Timer is in debug

#

at the bottom

rich adder
#

oh wops just saw screenshot

somber herald
#

ye so 6 is more than 0.2 i really dont understand

#

when I hit spacebar ^

rich adder
#

what is the jumpTimer + coolDown value

somber herald
#

Jumptimer is basically stuck at 0 since the jump function doesnt continue and cooldown is 0.2

#

I also tried changing the print message to see if maybe code wasnt updating but it is

somber herald
#

oh my-

late moon
#

Chill Guy

somber herald
#

listen

#

I had a final today

#

the brain cells died out today

late moon
#

⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⢀⣀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠜⠁⣷⢊⠤⡇⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⡠⠴⠨⠼⡜⡝⠀⠀⠀
⠀⢀⣀⣀⣠⡤⠔⠒⠚⠉⢙⣖⡎⢰⣞⣶⠄⠘⢣⠀⠀⠀
⢰⣿⣿⣿⣿⣿⠀⠀⠀⠰⠀⠎⠁⠈⠾⠏⠀⠀⠈⡆⠀⠀
⢸⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀
⢸⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⢄⡀⠂⡇⠀⠀
⠀⠙⠿⣿⡿⠟⠀⠀⠀⠀⠀⠀⠀⣀⣠⠮⠀⠠⢈⠃⠀⠀
⠀⠀⠀⠀⠉⠒⠒⠒⡆⠀⠀⠈⡽⠥⠄⠀⠄⢀⣼⡀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢀⠏⠓⠶⠖⣒⣲⡲⠮⠝⠛⠁⠈⢆⠀
⠀⠀⠀⠀⠀⠀⠀⡌⡆⠀⠀⠀⠀⠀⠀⠀⠀⠸⠁⠀⠈⡆
⠀⠀⠀⠀⠀⠀⠀⢏⢇⠀⠀⠀⠀⠀⠀⠀⠀⣠⠓⠋⠀⣀
⠀⠀⠀⠀⠀⠀⠀⠈⢺⠓⢶⢒⣶⣲⣶⡒⠶⠲⣄⣀⡸⠉
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠃⠻⣥⠥⠄⠀⠐⠔⢸⠇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⢠⣄⠀⢻⡀⢀⠀⠀⠀⢸⡇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢘⡀⠙⠀⠘⡃⠘⠄⠀⠀⢸⡇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⣌⠉⠉⠉⠹⠉⠒⠒⠒⠊⣱⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡔⠉⠉⠻⣫⢗⣣⡶⢶⣷⣶⠞⡏⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠱⣤⣤⣤⡽⡮⣏⠀⠀⠈⣛⢿⠇⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠒⠒⠒⠒⠁⠀⠀

late moon
#

I'm just a chill guy it's not spam

#

I COULD spam

rich adder
late moon
#

chill guy to you

#

I AINT READING ALL THAT🗣🗣🗣

copper crest
#

im gonna start tweaking

#

i was just watching brackeys and making my game by following him

#

and the ui JUST DOSENT SHOW UP WHEN I COLLIDE WITH THE FWEAKING END CUBE

#

ive used my final brain cells bruh

#
 using UnityEngine;

public class EndTrigger : MonoBehaviour
{
    public GameManager gameManager;

    void OnTriggerEnter ()
    {
        gameManager.CompleteLevel();
    }
}```

```cs
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    bool gameHasEnded = false;
    float WaitRestart = 0.5f;

    public GameObject completeUI;
    
    public void CompleteLevel ()
    {
        completeUI.SetActive(true);
    }

    public void GameEnd ()
    {
        if (gameHasEnded == false)
        {
            gameHasEnded = true;
            Debug.Log("GAME, OVER!!!!!");
            Invoke("Restart", WaitRestart);
        }
    }

    void Restart ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
#

someone hlep me plz 😭

teal viper
copper crest
#

im on my 8th brackeys video bro 🙏

rich adder
rich adder
copper crest
#

what r logs

#

🥺

rich adder
#

should be the first thing you should've learned

copper crest
rich adder
#

that would be the log function, yes

#

you need more of them, to verify each function and whats happening

copper crest
#

im used to the print statement cuz i used to code in lua

#

ok

rich adder
#

its the same exact thing as print

silent valley
#

Use debug logs to see if your collision is even being registered. If it is. You can then debug log your game manager script to see where the issue is happening.

copper crest
silent valley
#

What are you colliding your end trigger wiith?

copper crest
#

the player its a cube

#

i tried adding a log it did print after colliding

#

but it didnt show up the ui

#

OOP

#

now it dosent print

silent valley
#

Is your game manager script on your player game object?

copper crest
#

no

silent valley
#

You need to ensure both player and the end trigger has a collider. Box collider should work fine for both. Set the end trigger box collider as end trigger.

#

What's player collision?

copper crest
#

both hav a box collider

silent valley
#

Mind sending all the relevant code? Use one of these to send each. !code

eternal falconBOT
copper crest
#

ok

#
using UnityEngine;

public class EndTrigger : MonoBehaviour
{
    public GameManager gameManager;

    void OnTriggerEnter ()
    {
        Debug.Log("Its, Working!!!");
        gameManager.CompleteLevel();
    }
}
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    bool gameHasEnded = false;
    float WaitRestart = 0.5f;

    public GameObject completeUI;
    
    public void CompleteLevel ()
    {
        Debug.Log("ITS, WORKING!");
        completeUI.SetActive(true);
    }

    public void GameEnd ()
    {
        if (gameHasEnded == false)
        {
            gameHasEnded = true;
            Debug.Log("GAME, OVER!!!!!");
            Invoke("Restart", WaitRestart);
        }
    }

    void Restart ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
using UnityEngine;

public class PlayerCollision : MonoBehaviour
    
{
    public PlayerMovement playerM;

void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle")
        {
            playerM.enabled = false;
            FindObjectOfType<GameManager>().GameEnd();

        }
    }
}
silent valley
#

You have nothing to say that your player collides with the end trigger

#

You can use the link to the unity docs I provided and use CompareTag so the end trigger knows when it collided with the player.

copper crest
#

ok

silent valley
#

Yus

silent falcon
#

I would like to ask a question. I tried to use UI Toolkit in Unity 2022.3.52f1 version and used ImageElement to inherit Image, so that I can drag and drop it in UI Editor. The specific code is as follows. The effect is normal in Unity preview, but when packaging on Android, I encountered the following error. I tried to ask chatgpt or google, but they didn't solve it. I would like to ask if there is a feasible solution.

public class ImageElement : Image
{
public new class UxmlFactory : UxmlFactory<ImageElement, UxmlTraits>
{
}

public ImageElement()
{
}

}

teal viper
#

As for why it works in the editor, there could be several possible explanations. A likely explanation is that android build is il2cpp, while the editor is a mono/dotnet build.

copper crest
#

THE PROVIDES CONTACT BOX WAS UNCHECKED

#

💀

silent valley
#

All working now?

copper crest
#

yea

#

thanks for the help btw!!!

#

<3

silent valley
#

You're welcome 😊

silent falcon
somber herald
#

Hiya I have two vectors, transform.up and rb.velocity. How do I find the angle between them? (Ik this is trig but Im looking for some unity function idk)

#

wait sorry how do I find the vector imbetween them

#

If I dot and get the angle how do i turn that into a vector aswell

cosmic dagger
#

Vector#.Angle will give you the angle between both vectors . . .

somber herald
#

oo kk

#

how get the vector

final sluice
#

What should I use to calculate t he collision force between two objects ?

cosmic dagger
#

that is, subtracting the positions of each vector . . .

ivory bobcat
cosmic dagger
# somber herald how get the vector

actually, what do you mean by "vector?" do you want the position or the direction between both vectors because those two are different . . .

silent falcon
teal viper
#

Hmm... Maybe I'm wrong. I wonder how it works.

silent falcon
#

Thanks anyway, I'll search on Google again😀

elder raptor
#

I tried to make a Camera Following mechanic for the camera but for some reason, it shakes/vibrates a lot. Any idea why?

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target; 
    public Vector3 offset = new Vector3(0, 5, -10); 
    public float smoothSpeed = 0.125f; 

    private void LateUpdate()
    {
        Vector3 desiredPosition = target.position + target.TransformDirection(offset);

        transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

        transform.LookAt(target);
    }
}
burnt vapor
#

Smooth the lerp more

#

Also, this is not how lerping works

#

The third parameter is the intermediate between a and b so you only set it to a static 12.5% of the position using your current code

elder raptor
burnt vapor
#

There are functions that can do what you want, but I forgot the names

#

Or change the code so you always have the desired position somewhere and the current camera position, and create some sort of elastic movement where the camera loosely follows the car

#

Also don't use LateUpdate, just use Update

astral falcon
burnt vapor
#

I don't see why you'd have a visual camera be frame independent, you just need to fix the smoothing since there's no smoothing at all

astral falcon
#

the first part of the sentence is clearly self-explanatory, id say. You dont want to move it in different speeds at different fps, right. Still agree, that there is no smoothing at all but just setting the fixed percentage of the values. That time independence was just an add on on top of your answer

elder raptor
#

Okie lemme try

#

Okie it works now! Thanksss!

#

Vector3.SmoothDamp and using Time.deltaTime is what I did and it works better now. I also shifted back to Update instead of LateUpdate!

burnt vapor