#💻┃code-beginner

1 messages · Page 730 of 1

dense goblet
#

Yes

polar acorn
# dense goblet Yes

Then also notice that HingeJoint is a thing you can put on an object in the inspector

dense goblet
#

I understand what you mean

#

do Scripts count as Components though? Im assuming not?

polar acorn
rich adder
#

if script is on gameobject its a component, simple as that

naive pawn
#

and you didn't think to.. yknow, add a rigidbody?

dense goblet
naive pawn
dense goblet
# polar acorn

so a script isn't a Compoent at all, so would my line of code thoretically never work for what Im trying to do?

polar acorn
#

I feel like my screenshot shows precisely the opposite

#

Those boxes on an object in the inspector are components

slender nymph
#

if a script contains something that isn't a monobehaviour, then it isn't a component

naive pawn
dense goblet
polar acorn
#

the point was to show that those things are components

dense goblet
polar acorn
#

the boxes on an object

dense goblet
#

so I would be looking to add Camera_Move, not the object as a component then?

polar acorn
#

If you are trying to get a component named Camera_Move, then that is the component that you would get

dense goblet
#

Thank you

naive pawn
dense goblet
#

Maybe I added it in wrong? maybe I added in the raw model instead of the prefab?

naive pawn
#

that seems.. hard to accidentally do

dense goblet
#

so to get one step further, it'd be something like this (not correct but closer)

naive pawn
#

they're all in a folder called "prefabs" then "characters"

#

you should just go do the programmer essentials.

#

GetComponent is taught there.

dense goblet
slender nymph
polar acorn
#

int x is a variable named x that is of type int. You can set x to any integer.

dense goblet
polar acorn
#

GameObject Room is a variable named Room of type GameObject. You can set Room to any GameObject.

#

If you're trying to get a Camera_Move component, why are you trying to store it in a variable that holds GameObjects

dense goblet
#

I see what you mean

slender nymph
dense goblet
slender nymph
#

you're 100% wrong about booleans

dense goblet
#

Oh yeah I totally forgot that it was like that

#

just haven't been using Bools recently

polar acorn
#

But more importantly, everything is a Type

#

There's not a finite number of them

naive pawn
#

ehh i kinda feel the "everything" there is misleading

#

public is not a type, that kind of thing

dense goblet
#

So am I looking for a float, something similar to this? ``` float Room = CameraTrigger.GetComponent<Camera_Move>();

polar acorn
#

and think

#

and read the things I've said

#

Why

#

would you store

#

a value of type Camera_Move

#

in a variable

#

that holds floats

naive pawn
#

this isn't going anywhere

#

@dense goblet go do basics first.

polar acorn
#

What is the point of asking questions if you won't read the fucking answers

dense goblet
#

Im trying to understand this Im just very confused, Im sorry

naive pawn
#

stumbling around for 2 hours because you don't understand types is not a good use of time
go learn for 20 minutes and then solve the issue in 2 minutes once you actually understand the things you're writing

#

walk before you run.

#

learn the basics first. you're skipping over them right now.

polar acorn
#

GetComponent<Chungas>() will get you a value of type Chungas

#

Which you can store in a variable that can hold a value of Chungas

#

If you want to store the value of GetComponent<Chungas>()

#

you would make a variable

#

of type Chungas

#

Do you notice

#

how these are the same word

#

on both sides of the line

#

that is not an accident

#

that is, in fact, how things work

dense goblet
#

(give me a second my desktop is kinda chunking around rn because Im loading a lot rn* and a quick brb)

dense goblet
grand snow
#

perhaps learning c# properly would help instead of stumbling every 5 seconds

dense goblet
#

also, hes still looking for help on thios one*

dense goblet
silver fern
#

you did something wrong

naive pawn
#

the essentials pathway is set up fine, you did something wrong

dense goblet
#

yeah I did something wrong

#

I went to models Characters instead of prefabs characters

naive pawn
#

yeah you can see here actually. you did indeed put in the model. the tutorial said to use the prefabs. which are in the folder named Prefabs

grand snow
#

some tutorials and such may teach unity parts and describe some things but it wont tell you what generics do properly

dense goblet
naive pawn
#

there is also the fact that you don't need GetComponent in this situation anyways

#

you can just type Camera_Move as the thing you want to get

#

(but you'll still have to learn how to use GetComponent properly eventually)

dense goblet
#

yeah honestly I should have asked if there was global varables, I only asked about GetComponent because from everything Ive seen it was the most proper way to do the next step in my test project

grand snow
dense goblet
naive pawn
#

the point of a tutorial is to teach a specific thing in isolation, to see how that one specific thing works.
when you skip tutorials, you end up having to figure out everything all at once before it can work.

that's your current issue

dense goblet
#

I actually thought I was doing pretty fine up until then, even if it took me a long time for some basic stuff like refrencing other gameobjects in scripts to make trigger areas I thought I was doing fine

naive pawn
#

it wouldve taken you less if you took a break to actually learn them properly rather than trial & error

dense goblet
#

tbf I had already assumed that Unity Essentials was broken based off what I already asked and was told in another server.

naive pawn
#

it wasn't when i did it and i don't think anything changed

#

what did change was unity 6.1 changing the default input handler

dense goblet
#

well, as far as Im into it, it was because I didn't go to prefab 😓

naive pawn
#

go redo it with that new knowledge

dense goblet
#

already in it actually

#

already got to the part that previously broke

limber turtle
#

i'm having collider issues

#

is anyone here able to help?

#

i think i posted something about it earlier but you guys were busy so it's no fuss

dense goblet
#

here

limber turtle
#

yes, thank you

#

i can post a video if you need it

naive pawn
#

make sure layer interaction and their layers are set up appropriately.
the collision/trigger message will be sent to any components that are on the same gameobject as the collider, and a rigidbody if one is present, so, do you have a rigidbody?

mainly you'd want to distinguish the messages from each collider, here are some options

  • consider if it'd make sense for one of them to be a trigger
  • use separate scripts on each collider's gameobject (and rely on other objects' rigidbodies for collision)
  • check the thing you're colliding with in the message handler
polar acorn
#

If an object has multiple colliders, it basically melds them all into one. If you want different behaviors for different colliders they need to be on separate objects

#

Consider making one of them a child object

naive pawn
#

isn't one of them already a child

limber turtle
#

the child object is the trigger with the larger collider

limber turtle
naive pawn
#

is one of them a trigger and the other non-trigger?

limber turtle
#

let me just double check

#

i think so

naive pawn
#

then your messages should already be distinguishable

limber turtle
#

yeah

#

the parent object is the non-trigger and is smaller

naive pawn
#

so what's the issue exactly?

#

sounds like just a logical issue

limber turtle
#

it's saying this here

naive pawn
#

that would make sense with the NREs too

naive pawn
limber turtle
#

i think i already put it in the child object to ignore surface collisions

naive pawn
#

!code

radiant voidBOT
limber turtle
#

yes i am aware

#

i know how to do that

naive pawn
#

show SlingerCoinScript with one of the large codeblock things

limber turtle
#

you can just ask me for the code :)

naive pawn
#

for your convenience lol ¯_(ツ)_/¯

#

i wouldve said like, "show !code" before but the new bot doesn't support that yet, it turned into this

limber turtle
#

alright i can't share the whole thing, should i just share the collision handling parts

naive pawn
#

wdym you can't share the whole thing

limber turtle
#

ah alright

#

too big for discord

#

text limit

naive pawn
#

i said to use the large codeblock part

limber turtle
#

oh

#

mb

#

i guess i did need that

naive pawn
#

-# the bot command was necessary after all...

limber turtle
#

sorry

#

check the bio, buddy. i can't read

naive pawn
#

check your bio...? for the advertisement? chima_confused

silver fern
limber turtle
#

i just clicked the first one in line

#

should i download it as a text file and post it here or am i supposed to do something else with it

silver fern
#

click save then copy the url

limber turtle
silver fern
#

whats the error

limber turtle
#

i don't know

#

aside from the trigger/collider mixup thing which isn't completely gamebreaking, when a coin is hit against a wall and destroyed and i shoot another one, i get an error

silver fern
#

there should be a red sign in the unity console

limber turtle
#

yeah

#

that didn't tell me where the error was

silver fern
#

that is the error

#

what does it say

limber turtle
grand snow
#

now check the exception stack...

silver fern
#

it even says what to do

limber turtle
#
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren (System.Type type, System.Boolean includeInactive) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren[T] (System.Boolean includeInactive) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren[T] () (at <b6ea36b6733e4deea99187f144c6addc>:0)
SlingerCoinScript.RedirectCoin (UnityEngine.GameObject otherProjectile) (at Assets/Scripts/SlingerCoinScript.cs:52)
SlingerCoinScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/SlingerCoinScript.cs:32)
#

oh it doesn't format very well as a message

#

does it?

silver fern
#

slingercoinscript line 32

rich adder
#

we can read it fine, but did you read it

limber turtle
#

yeah

rich adder
#

so do you know where it tried to do that at?

#

make it not do that

limber turtle
#

i looked at line 32 and 52 of slingercoinscript

limber turtle
#

i commented line 32 to see if it was the issue but nothing changed, i'll look at line 52 now

silver fern
limber turtle
#

which is a single squiggly bracket

naive pawn
#

you aren't updating slingerScript.activeCoins when they're destroyed

#

or at least not properly

limber turtle
#
public class CoinProj : ProjectileProperties
{
    public GameObject coinOwner;
    public SlingerCoinScript childScr;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

    }

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

    }
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Surface"))
        {
            if (other.contacts[0].normal.y < 0.01f)
            {
                Debug.Log("Coin destroyed on surface");
                childScr.slingerScript.activeCoins.Remove(gameObject);
                Destroy(gameObject);
            }
            
        }
    }
}```
#

this is the code that makes the coin break against surfaces

#

it should be updating the list when it hits a surface before destroying itself

#

i'm looking through it all now and it's either the fact that it's 11pm or my lack of experience but i'm stumped

silver fern
#

according to the error, you are trying to access something that's already been destroyed

limber turtle
#

yes, i am trying to look for it

silver fern
#

that thing should be on line 32

clear pasture
#

Hoping anyone can help me with rotation math. I'm trying to find the angle between the mouse and player, and rotate the player. It seems to work when the player is at the bottom, but it breaks when the player moves.

    private void Rotate()
    {
        Vector3 mousePos = Input.mousePosition;
        angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
        angleDeg = (180 / Mathf.PI) * angleRad;
        transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
    }
limber turtle
#

alright. i looked at the layer inclusions/exclusions for my projectile and coin, tweaked a few things and now i think it's working somewhat

#

that solved everything ._.

silver fern
#

nice

limber turtle
#

all i had to do was change the collision rules for the bullet and projectile.

#

i didn't have to look through my scripts at all

#

thanks for putting up with me i guess

modest harness
#

so i made a character prefab using a Scriptable Object to keep track of important vars and call events

i was just instantiating SO at runtime and i thought everything will be fine
but now im realizing i cant change any single value for a given character!
because the instantiated SO doesn't exist while the game is not launched

what do i do? 😵

silver fern
#

what are you trying to do exactly

modest harness
#

im trying to make a universal agent that can act like a player, npc, enemy

#

so i can drop it, change a couple vars and it becomes whatever i need

#

in other words the problem is prefabs dont create their own permanent scriptable objects when you place them, and instead reference the main one (till you run them and tell to instantiate the SO)

limber phoenix
#

Is anyone able to help me debug a unity script? Im taking an intro to Programming class and cannot figure it out

robust mural
silver fern
robust mural
#

Is that an intended behavior

radiant voidBOT
limber phoenix
#

If anyone is able to take a look, this is my script. My issue is that I am trying to make a collectable block as I go along an infinitely spawning track and upon collecting this block a new one will spawn. However, when I collect this block, blocks rapidly spawn as long as I am inside the block and instead of the blocks continuing to spawn ahead of the user they all spawn in the starting position

#

if I sit long enough in the block itll spawn like 10k blocks and crash the client

#

long enough being like 5 seconds lmao

silver fern
robust mural
modest harness
silver fern
limber phoenix
#

@robust mural yes exactly like temple run

silver fern
limber phoenix
silver fern
modest harness
#

so like.. manually copy them?

silver fern
sour fulcrum
limber phoenix
#

@fast whale ok i’ll try this in a bit, driving home from school now. Would this also fix the blocks all spawning in the same location? because currently it just puts them all on the starting position

silver fern
modest harness
sour fulcrum
#

you can edit templateagentdata

#

if its per instance you'd want it on a monobehaviour on said instance or a base class that exists on a monobehaviour

clear pasture
modest harness
#

i see.. so cant go pure SOs then
thank you

robust mural
clear pasture
# robust mural Maybe if you put the point of rotation on the middle of the cube

The code I used is:

    private void Rotate()
    {
        Vector3 mousePos = Input.mousePosition - transform.position;
        angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
        angleDeg = (180 / Mathf.PI) * angleRad;
        transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
    }

I thought that subtracting the mouse position from the player position would make it the center. What can I change to make the player the centerpoint?

silver fern
#

try Camera.main.ScreenToWorldPoint(mousePosition)

#

to translate mouse position into world space

clear pasture
robust mural
#

or maybe try to normalize the vector

clear pasture
robust mural
#

where is the rotation then

clear pasture
dense goblet
#

I do wanna ask a small question, why would I ever make a custom variable private instead of public?

rich adder
polar acorn
#

If you aren't supposed to edit it from outside the class, might as well make it so it can't be

#

then you won't have to sift through a bunch of things in your autocomplete that might break the game if you pick the wrong one

dense goblet
#

So if I have 3 public Vars that I want to change, would that cause issues or is it just harder?

#

(I gtg, I'll read any follow ups when Im back, ty)

polar acorn
#

Do you need to edit them from another class?

robust mural
# dense goblet I do wanna ask a small question, why would I ever make a custom variable private...

It's essentially just good writing. Making a variable private or public doesn't do anything to the actual variable. HOWEVER, you make a variable private if it's not supposed to be edited in another class.

Let's say you have a variable X that is essential for the class X to work.

Let's say you used variable X in another class and it's not private. You accidentally edit the variable. Now class X doesn't work.
Now, if you had a long line of code, the trouble shooting would be a nightmare.

if it was private, you wouldn't be able to access variable X in the other class. only in class X

silver fern
dense goblet
#

I see I see, tysm

thorn kiln
#

So, I'm doing the unity pathway and one of the challenges is

Bonus: The game can go on forever
• Add a “Time: __” display that counts down from 60 in whole numbers (i.e. 59, 58, 57, etc) and triggers the game over sequence when it reaches 0.
The hint says
Hint - Google, “Unity Count down timer C#”. It will involve subtracting “Time.deltaTime” and using the Mathf.Round() method to display only whole numbers.
I decided to just do what I know instead. It seems to work, but tell me how stupid it is.

    IEnumerator Countdown()
    {
        while (isGameActive)
        {
            yield return new WaitForSeconds(1.0f);
            UpdateTime();

            if (time == 0)
            {
                GameOver();
            }
        }
    }

    public void UpdateTime()
    {
        time -= 1;
        timerText.text = "Time: " + time;
    }```
polar acorn
thorn kiln
#

Looks like a lot of people used coroutines to make the timer for this challenge, I can see them all talking about it in the comments section

polar acorn
#

It does work, but it's a lot more overhead and you're denying yourself the purpose of the task which is to actually gett an intuitive sense for what deltaTime means

thorn kiln
#

What's the value of Time.deltaTime? One of the forums has timeLeft -= Time.deltaTime as a solution

thorn kiln
#

Well, the timer is working, downside is that I don't know how to make it not be working before the game starts now

#

I guess an undeclared float is the same as 0

#

Wait, I can declare a float at the start

#

Ah, but that makes the timer start immediately instead of when I start the game

#

I'm getting the impression I can't do this with the Update function, but using a Coroutine also seems wrong if the point is to use Time.deltaTime

#

Maybe a nested if statement

#
    public void Update()
    {
        if (time > 0 && isGameActive)
        {
            time -= Time.deltaTime;
            timerText.text = "Time: " + Mathf.Round(time);
            if (time < 0)
            {
                GameOver();
            }
        }
    }```Well, that's my attempt using Time.deltaTime
#

It's another case of "it works, no idea if it's correct though"

limber phoenix
#

@silver fern A flag did not prevent multiple spawns of the cube

#

could this be an issue with my heirarchy structure and the inspector settings? I

#

if anyone else is interested in helping debug, I can paste my problem again

near wadi
#

you can probably just 'bump' to the message link

#

if it has been some time, reposting should be fine

limber phoenix
#

If anyone is able to take a look, this is my script. My issue is that I am trying to make a collectable block as I go along an infinitely spawning track and upon collecting this block a new one will spawn. However, when I collect this block, blocks rapidly spawn as long as I am inside the block and instead of the blocks continuing to spawn ahead of the user they all spawn in the starting position

#

I am also getting this error upon starting the program: ```NullReferenceException: Object reference not set to an instance of an object
CubeTrigger.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Base Level/CollectableCubes/CubeTrigger.cs:26)

#

I can also provide screenshots of my heirarchy or whatever you may need

wintry quarry
#

As for the infinite spawning you're probably spawning the cubes and they're immediately touching something which immediately causes another to spawn

#

You probably want to make sure cubes don't spawn inside other objects

limber phoenix
#

oh could just touching the track or the track walls cause it?

#

thats an interesting thought I didnt consider

wintry quarry
#

Well your code is checking for a specific tag but the only way to know for sure what's going on is to debug it

limber phoenix
#

@wintry quarry Unforunately neither things fixed their issues

#

changing start to awake didnt fix anything

#

and I moved my object to not touch anything and it didnt fix it

wintry quarry
random lodge
#

Half the time I'm not sure why something works and I have to keep going back to find the code I did it in and try to remember why.

#

"How did I do that again and why did it work?" lol

#

I refuse to paste anything from anywhere because I'll never get it

#

Was pretty happy recently when the game become intricate enough for things like enemy ships shooting destroyed any asteroids in the path of the shot as well as me

chilly vigil
#

!code

radiant voidBOT
chilly vigil
frosty hound
#

Why not try it and see?

worthy veldt
#

im trying to "construct" (assign initial values to fields) my monobehavior. I usually just call the "construct" method after instantiating the prefab but I wonder if i could do it in awake or start

#

this is due to multiple "item" with different quality sharing same prefab

slender nymph
#

if you don't need to pass data to it, then you can absolutely use Awake. if you do need to pass data then it must be a separate method

worthy veldt
#

i just dont like the look of it, this shouldnt have bothered me this much. maybe ill make a CustomInstantiate with many overloads instead just so i dont have to Instantiate..initialize..

#

but good to know it wasnt an option, thanks

frosty hound
#

Instantiating followed by an Initialization is as clean as it get 🤔

sour fulcrum
#

in some cases i like

disable prefab gameobject
instansiate instance
give instance data
enable instance
enable prefab gameobject

#

doing this means the instance's awake triggers after it's given data

polar acorn
# fast whale ? That's me

There's another person with the same display name and it looks like you caught a stray from someone who didn't double check their pings

sudden prairie
#

I'm trying to oscillate the piston, but it's failing to do so. Can anyone tell me why is that so?
Oscillator.cs: -


public class Oscillator : MonoBehaviour
{
    [SerializeField] Vector3 movementVector;
    [SerializeField] float speed;

    Vector3 startPosition;
    Vector3 endPosition;
    float movementFactor;

    void Start()
    {
        startPosition = transform.position;
        endPosition = startPosition + movementVector;
    }

    void Update()
    {
        movementFactor = Mathf.PingPong(Time.time * speed, 1f);
        transform.position = Vector3.Lerp(startPosition, endPosition, movementFactor);        
    }
}
polar acorn
#

That seems like it's correct. What is it doing instead?

sudden prairie
#

I doesn't oscillate

polar acorn
#

Try logging movementFactor and transform.position after you set it and see if it's actually giving you the numbers you expect

stuck charm
#

hi

sudden prairie
#

Idk why it didn't work instantly

ivory bobcat
#

Maybe you forgot to save.

sudden prairie
#

No, I saved it also

hardy otter
#

anyone know why

{
    Debug.Log("Working");
}```

in both update and fixed update will only trigger once every ~20 clicks

but setting up 
``` private void OnEnable()
 {
     playerInput.Player.Enable();
     playerInput.Player.Jump.performed += OnJump;
 }

 private void OnJump(InputAction.CallbackContext ctx)
 {
     Debug.Log("Working");
 }```
will work everytime?
keen dew
#

It's expected that it won't work correctly in FixedUpdate. It should work in Update though

hardy otter
#

weird

#

it isn't "bad" to use the callback right?

keen dew
#

No, that's how it's intended to be used

strange jackal
#

I am trying to change the opacity of a panel in my UI, but it doesn't seem to do anything

                tempColor.a = 0.1f;
keen dew
#

The color needs to be assigned back to the component after changing it

strange jackal
rancid ingot
#
        if(currentImage)
       {
           var tempColor = currentImage.color;
                tempColor.a = 0.1f;
           currentImage.color = tempColor;
           
       }

        
#
public class CommonUserInterfaceUtils
{
   public static void ChangeImageAlphaPrecisely(Image image, float alpha)
   {
      image.color = new (r: image.color.r, g: image.color.g, b: image.color.b, a: alpha);

   }
}

public class YourScript : MonoBehaviour
{
   void Start()
   {
      CommonUserInterfaceUtils.ChangeImageAlphaPrecisely(respawnPanel.GetComponent<Image>(), 0.1f);

   }
}
azure hemlock
#

how do i performance-debug very nested calls? they eat up my pc memory pretty quickly but also are difficult to tell which function is taking most, since all of them take a bit and their sum is what eats lots of cpu time. does unity have a solution for this case?

#

Unity’s is practically unusable for deep profiling btw, idk

teal viper
#

You can use profiler markers to debug specific code paths in details without deep profiling.

azure hemlock
teal viper
azure hemlock
teal viper
azure hemlock
#

Ok will try right now, hopefully it doesn't crash editor again.

teal viper
#

Non deep profiling one is fine

azure hemlock
#

useless without deep profiling

#

u get gc.alloc with nothing else

grand snow
#

If you run out of memory with deep profiling then yea you need to use custom profiling markers

azure hemlock
#

this is for just 1 unit

#

5 gb of profiler

teal viper
azure hemlock
#

yes ofc. i cannot tell whats doing it the problem.

teal viper
azure hemlock
#

u cant tell anything. the code is deep. it calls a event bus, which calls other event callbacks etc

teal viper
#

Having some idea of the method is gonna be helpful already

silver fern
teal viper
azure hemlock
#

yes

teal viper
# azure hemlock yes

I see. Did you try isolating the deserialization to see if it's the main cause?

azure hemlock
#

yes. and yes it is

grand snow
#

if this is json, why make your own solution?

silver fern
#

everything seems to be working, thanks for the help

azure hemlock
teal viper
#

Will need to add profiler markers in the serializer logic

azure hemlock
#

its pointless then? i wrapped it around the deserialize. if i cant get the deep calls whats the point

#

you mean i wrap a recursive function?

grand snow
#

Create an isolated test with deep profiling on?

azure hemlock
#

it is isolated

azure hemlock
#

its pathetic at this point

grand snow
azure hemlock
#

can performance marker not deep profie?

#

like i deep profile only a section

grand snow
#

or... different serializer thats not poo poo

teal viper
teal viper
#

You'll need something like a memory profiler to track the allocations precisely. Though I'm not sure how you'd capture that frame where the issue happens.
Maybe programmatically..?

teal viper
azure hemlock
#

i actually got 70% reduction in allocs by caching reflection

#

ofc the serializer is not good if i cant debug it. which is what im trying to do

teal viper
#

If it's like 5mb+ data it's a full fledged asset that needs to be loaded as an asset.

silver fern
#

are you using the visual studio memory usage diagnostics?

azure hemlock
#

no, does that work with unity?

silver fern
#

dunno, but if its just about serializing the json that seems to be unrelated to unity

azure hemlock
#

no sadly not supported

#

can i not set depth or profile only 1 call deeply or sth...

#

unity is making sure every experience is as painful as it can get. UnityChanSorry

midnight plover
forest river
#

hi

azure hemlock
midnight plover
#

Did you check the right side dropdown "No details", where you can enable calls?

mighty peak
#

Can someone send docs for when ui button down and up ? Couse i just find pointer down & up and I dont know if that's for mouse or buttons

teal viper
teal viper
# azure hemlock this is what i get

Since these are recursive calls it's pretty clear that something inside the call is the problem. If you can't figure it out, maybe share the code.

azure hemlock
#

i meant "1 call" deep, rather than "1-call-deep"

azure hemlock
#

and the custom converters code is trimmed from there

teal viper
# azure hemlock https://pastebin.com/kr0HZvsC

Well, it's basically all the new objects you're creating.

var state = new JsonReaderState(options);
        var reader = new Utf8JsonReader(jsonBytes, isFinalBlock: true, state: state);
        if (!reader.Read())
            throw new JsonException("Empty JSON");
        return (T)ReadValue(typeof(T), ref reader)
#

Don't have the time to look through all of it right now.

Also, adding markers in all the methods(or even several in a method) might help.

shell sorrel
#

why are you posting literally the ml model response?

chilly vigil
#

Idk because it suggested that I do it for my code but something still doesn’t work

midnight plover
exotic valley
midnight plover
# exotic valley

First debug your button. Make a simple log in your function that should fire off when you hit the button. If it does not, its not about your code yet

exotic valley
#

but i dont understand where

chilly vigil
#

What did the error message say in the console. Go to the line of the code and then do debug.log(“button not working”)

teal viper
# azure hemlock https://pastebin.com/kr0HZvsC

Had a bit of a better look. You're using a lot of Linq, which is gonna allocate tons of garbage. And you're also allocating a lot of temp objects and collections.

Also, not entirely sure if that works, but you could try adding profiler markers for each converter as well, if you suspect them being the issue:

        foreach (var converter in converters)
        {
            if (converter.CanConvert(this, targetType, ref reader))
            {
                var converterMarker = new ProfilerMarker($"Converter_{converter.name}");
                converterMarker.Begin();
                return converter.Convert(this, targetType, ref reader);
                converterMarker.End();
            }
        }
azure hemlock
#

i need to not alloc strings for prop names

teal viper
#

Yeah. Strings are a bit tricky. They don't always allocate afaik.
You can wrap the suspicious places in a profiler marker to confirm

shell sorrel
#

are ways to work around string allocations

#

like spans

#

depends on the exact use cases

chilly vigil
chilly vigil
real ferry
#

is there a way to generate dynamic meshes (if thats the name) using raycasts?

#

like draw a point where the raycast hits

#

and make a shape out of that

shell sorrel
#

@real ferry yeah can do that from the Mesh api

shell sorrel
#

yeah can be a little trickey to get used to it since you need to make complete triangles but i have used it before for building meshes from raycasts

cosmic dagger
real ferry
vital vault
#

how can i pause all audiosources on the scene?

shell sorrel
vital vault
#

i need for it to also start playing back

shell sorrel
#

or you mean pause mid clip, if its muting use the mixer of its an actual pause i would just keep track of all of your audio sources and do a loop and call pause on them all

#

or other way is via a event

vital vault
#

so how do i just mute them?

#

because i want to make pause pause sounds

shell sorrel
#

put a component on all sources that are part of the global pause, have to subscribe to a event that gets invoked when you want to pause all

red igloo
keen dew
#

Reduce or remove angular damping on the rigidbody

grand snow
shell sorrel
red igloo
grand snow
#

Ah no, a string is immutable

shell sorrel
grand snow
#

I think you can get a sub string view right?

keen dew
grand snow
#

Or is that c++ I forget 😅

shell sorrel
grand snow
#

Ah then yea that can provide a readonly sub string range with stack allocation only but

shell sorrel
#

have used it a few times where i needed to parse part of a string without a allocation

grand snow
#

I sometimes make use of stackalloc spans but many things just arent built for this

lunar coral
#

hello, I'm trying to animate some characters for my game but it doesn't work

lunar coral
# lunar coral hello, I'm trying to animate some characters for my game but it doesn't work
private void Update()
{
    // check for sight and attack range
    playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
    playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);

    if (!playerInSightRange && !playerInAttackRange)
    {
        Patroling();
        animator.SetBool("isWalking", true);
        animator.SetBool("isRunning", false);
        animator.SetBool("isShooting", false);
    }
    else if (playerInSightRange && !playerInAttackRange)
    {
        ChasePlayer();
        animator.SetBool("isWalking", false);
        animator.SetBool("isRunning", true);
        animator.SetBool("isShooting", false);
    }
    else if (playerInSightRange && playerInAttackRange)
    {
        AttackPlayer();
        animator.SetBool("isWalking", false);
        animator.SetBool("isRunning", false);
        animator.SetBool("isShooting", true);
    }
}
#

I'm animating them like that

#

but they just aren't getting animated

#

I've tried to debug like that : void Update()
{
Debug.Log(animator.GetCurrentAnimatorStateInfo(0).IsName("Walk"));
}

#

and it debugs true

#

but still doesn't work

exotic valley
hallow acorn
#

hey can someone help me with my state machine? im trying to implement dashing but for that ill need to check if the cooldown is ready and if im not already dashing. how would i do that? i can send my code if it helps

cosmic dagger
# exotic valley

It's best to send !code using these paste sites. Not everyone can see your file (if they're on mobile) . . .

cosmic dagger
hallow acorn
radiant voidBOT
sharp abyss
#

I have a script that adds torque to the thing Im holding. I want to use it to climb platforms like I do in this video but when I add torque while on ground it makes my player jump how can I prevent this? Also it makes me go up on air too as you can see.

dawn iron
#

how do i prevent the bullet to collide with the player? i tried to use physics.ignoreCollision and adding an offset but it didn't work

rich adder
#

or as you said Physics.IgnoreCollision also works, assuming you use the correct references

balmy vortex
#

hey so like how do you play an audio from an audio source without it getting cut off if the same sound is played again before the first one ends?

balmy vortex
#

wdym?

rich adder
#

PlayOneShot instead of Play

balmy vortex
rich adder
#

ok so now based suggestion I made, which part do you think I'm referring to

blazing solar
timid quartz
#

my terrain is getting weird when I try to paint on it. I'm using a default brush and the default terrain shader. the black artifacts can be painted over to be normal again but I have no idea why it's happening

timid quartz
#

ok!

random lodge
#

So when is if or a case preferred over one another if you're just checking something like .tag="whatever"?

#

I switched this to case, seems better.

cosmic quail
rich adder
random lodge
#

Components how?

#

tags are the only way I know to understand what hit the asteroid

rich adder
#
if(other.collider.TryGetComponent(out Player player)){
player.DoSomething();```
random lodge
#

Confused. lol (usually am for a while)

rich adder
#

Interfaces are the big one if you need a common "tag" to work with

random lodge
#

Just trying to understand why I need to look at components of an object collided with, Im confused

rich adder
#

I'm sure if you google it there's plenty of threads of the topic.

random lodge
#

but yea having a "common" tag among more than 1 gameobject would be nice (but since we can only have one)

#

at the moment this is how I had to do it

rich adder
#

yes one of the limitations of tags

#

but even calling it a "tag" would be doing injustice, its much better than that.. it will make sense soon enough

random lodge
#

I started with just naming enemies "Enemy" for example but I wanted a lot more complexity to it

#

At the moment the asteroid has this. Did the player hit the asteroid (with himself) or did any of the weapon types hit it, etc. And yea, 3 tags there just for that.

ivory bobcat
random lodge
#

at the moment nothing but there's a lot more to add

#

That's just the asteroid script

grand snow
random lodge
#

If a weapon projectile collides with the asteroid or a player or an enemy ship, etc

#

(it goes boom)

#

Just uses the trigger to know it's been hit

grand snow
#

right. If it was me id not use tags but check for a specific component (perhaps using an interface?)

ivory bobcat
grand snow
#

its okay to start off but as things advance, solutions that only work for 1 specific thing start to break down

sharp abyss
#

Problem is beads dont move like I want. Sometimes they collide with the sticked bead and cant turn past it so I cant stick other bead to platform.How can I solve it?It sticks by making the sticky static on collision ith tag "ground"

random lodge
#

I mean I could check if it has the enemy projectile script and then I'd know it was a weapon hit

#

That would kind of be like having a common tag

grand snow
#

well no because knowing it has a specific component or a component implementing an interface already makes things easier

#

e.g. making the player and enemies share the same "bullet" type

random lodge
#

Is that what you guys are saying by look at the object that hit it's components? The script being common between the things I want to check.

#

That's the only way I know I could identify it correctly at the moment with a component

grand snow
#

you use inheritance to share logic for taking damage and then the bullet uses this, allowing it to work on many types of objects

random lodge
#

Yea I haven't gotten to inheritance yet I'm about a week in

#

Eventually I'd have it behave differently depending on what exactly hit it, weapon type, object etc

#

As well as asteroid mass, etc

quick urchin
#

hello, I'm trying to make a stealth detection system using Physics.CheckBox, and i set the center at the position the AI is in. Basically the box should move with the AI, and if an object with the Player layer enters the box, then the AI should chase the player. the only issue is that the AI wont chase me when i'm within the box. I dont want to use raycasts as I want the AI to detect me from all directions. I also dont want to use CheckSphere as I dont want the AI to detect me past a certain height since it scales uniformly.

#

I'm kinda lost lol

cosmic quail
#

maybe BoxWidth_Sight and those other variables are 0

#

or maybe the player is not on the right layer

quick urchin
cosmic quail
#

<@&502884371011731486>

ivory bobcat
#

<@&502884371011731486> spam

quick urchin
cosmic quail
ivory bobcat
quick urchin
ivory bobcat
#

You're going to need to if you want to assure folks that you've got it set up correctly

cosmic quail
quick urchin
ivory bobcat
quick urchin
#

the warnings aren't affecting it btw, its just some code i havent deleted

ivory bobcat
#

Log to see if check sphere and box are ever true

cosmic quail
#

🤔

quick urchin
quick urchin
#

only for attacking

#

but not for seeing my player

cosmic quail
quick urchin
#

PlayerInSightRange is false

quick urchin
cosmic quail
#

from all of your numbers

quick urchin
#

ok

cosmic quail
quick urchin
#

yeah it works thanks

#

silly mistake

slow blaze
#

So I'm trying to make the localscale.x reach the value MaxScale with the rate of scaleFactor, now from my understanding of lerp (and the debugging of the infinite loop lmao) that sincee scaleFactory is constant it'll not truly reach the value unless I set t=1, or scaleFactor = 1. am I correct?

The overall goal is I'm doing a melee attack that stretches the weapon forward (and then return it but I didnt do that yet)

silver fern
#

at t = 1 lerp will return the max scale vector

grand snow
#

well that lerp is flawed anyway

#

you should use Vector3 MoveTowards instead

grand snow
#

using this will let you step better towards your goal

#

or do a lerp properly that has a fixed start + end and moves lerp from 0 to 1

thorn kiln
#

Man, my brain just does not hold information. I just wanna make an enemy rotate to face the player, and I'm sure I've done that exercise at some point during the course I'm doing, but man, brain just empty

#

enemyRb.transform.LookAt(player.transform);
I am often in disbelief that some solutions are so simple when I google them

#

Small issue however that my enemies are now doing the limbo when I jump

rocky canyon
#

in your look at, for the y part of the vector just feed in the enemies y position

#
Vector3 lookPos = player.transform.position;
lookPos.y = transform.position.y; // keep enemy's Y the same
transform.LookAt(lookPos);```
#

practically clamps that axis

thorn kiln
#

That does work, so I should probably take the time to figure out why

#

I should also make it so the cops colliding with the dog destroy it like it did when they were cubes

rocky canyon
#

if u use a Debug method to debug the positions (each one) you'd see they just stack on top of each other (ignoring) ur up and down movement

thorn kiln
#

I think I get it

#

That's gonna be hard to like, keep in my head though

#

My brain doesn't like the solution not being one line. It sucks, but it's what it is.

#

Just instinctually it's not gonna think to make variables instead of doing it all inside LookAt

rocky canyon
#

u can make variables if u want..

#

"modifiedLookPosition" is normally wht my LookAts() target

#

theres other ways i imagine.. thats just the one i learned to use

#
Vector3 modifiedLookPosition = new Vector3(
    playerTransform.position.x,
    transform.position.y, // clamp Y
    playerTransform.position.z
);

transform.LookAt(modifiedLookPosition);``` its like doing this
thorn kiln
#

I was just about to ask if you could do it with a new vector3, but I was worried I'd look stupid

rocky canyon
#

nah its just shorter to copy the whole transform and then modify the y afterwards

#

looks cleaner imo

thorn kiln
#

I think if modifiedLookPosition is on a single line it might be easier to read, imo

rocky canyon
#

do it whatever makes the most sense to you

thorn kiln
#

player.position.x is wrong isn't it? Shouldn't it be player.transform.position.x?

rocky canyon
#

yea. if player isn't a transform

#

ya, my naming coulda been better..

thorn kiln
#

Yeah, I'd assume "player" would be a GameObject

vocal quiver
#

Hello guys im having problems with ragdolls. Basically my issue is that my ragdoll dies, i disable the animator and then the ragdoll has some weird issues such as it goes through the ground or sometimes acts violently.

However, when I turn off the animator from the window, the ragdoll falls down normally and naturally as I intend to do it. I tried to troubleshoot the issue and I can say that the issue does not arise from the colliders on the body overlapping. Please help>

Here is a video to show what I am taking about.

vocal quiver
#

I fixed it guys nvm

random lodge
#

Is there a way for lines like this in code which will cause the build to fail, to have them ignored on build? UnityEditor.EditorApplication.isPlaying = false;

sour fulcrum
random lodge
#

There are certain things smilar to that in scripts that can cause the build to fail. Just wondering if the build process can ignore them.

sour fulcrum
#

well yeah UnityEditor.EditorApplication.isPlaying does not exist in builds

polar acorn
#

<@&502884371011731486> spam

sour fulcrum
#

it's editor exclusive

#

the best way to solve this issue kinda depends on why your touching it

frosty hound
#

Change the Collision Detection property on the rigibody component to something else like continuous dynamic.

random lodge
#

Nice, thanks. It was mostly an educational question that I was curious about. I use the Pragma lines sometimes to stop filling my log and figured something similar worked for compile.

tulip relic
#

When Unity builds a game, what happens to Debug.Log statements? They can't do anything in a build that I know of, so are they discarded at compile time?

rich adder
#

when done debugging those are usually cleaned / taken out . Usually you have a custom logger anyway

tulip relic
rich adder
sour fulcrum
frosty wren
#

For the healthbar over the enemy's head, I not only want it to always face the camera (billboard like) but also stay horizontal to the camera. Is there a simple trick I am missing to do this?

stiff ocean
#

So then, one way is to find the vector from the enemy's head to the camera, create a second vector using the first one's x and z coordinates, use atan2 to find the angle, convert it to degrees, then set the GUI's rotation using euler angles

teal viper
#

Learn something new every day.

random lodge
#

Looks up how to format C# beautifully because he hates looking at anything less

#

Hmm, or does VS Community have a button for that lol

#

Nothing changes. Guess I'm a pro formatter already. 😂

rugged beacon
#

is there a supported api let me deep clone a reference type object like classes

eternal needle
#

Unless its entirely out of your control, you should implement a copy constructor

sage mirage
#

Hello, guys! I’m working on a cannon in Unity. The cannon’s initial rotation in the Editor is -183° on the Y axis.
When I try to rotate it via script using transform.localEulerAngles or Quaternion.Euler, the Y value sometimes shows -360°, instead of the original -183°.
Why is Unity converting it like this?

#

Basically, it does this with every game object I am trying to rotate. I have tried to initialize the rotation of it and it worked. I am just curious and want to know the source of the problem?

bright reef
#

can a experienced guy help with smthin in unity?

sage mirage
#

Just shoot your question bro

#

What is it?

bright reef
#

so so

#

am making a simple game

#

in which a like a circle is hanging from a chain and i can move it with mouse and release it

#

i cant get the script to work i really need help

sage mirage
#

You want to make this functionality you are describing?

#

Where is the script and what you do ?

keen dew
#

The same rotation can be represented as different Euler angle values. Rotations are stored internally as quaternions and converting a quaternion to an Euler angle can produce any one of the possible representations

elder hearth
#

How would one destroy every child from a script in their parent

random lodge
#

That's ruthless 😛

elder hearth
#

good thing i added script in there...

keen dew
#
foreach(Transform child in transform)
{
    Destroy(child.gameObject);
}
elder hearth
#

yh i did that but i just saw that the if statment that its in was not working lol

#

i forgot to debug(like usual hehe)

random lodge
#

It's always something that you think "Oh geez. Duh."

elder hearth
#

fr

green owl
#

Hi does anyone know maxbe a fix for this camera rotation problem

elder hearth
#

whats wrong?

green owl
#

You see this kinda lie jittering and object tearing

#

when rotating fast

#

This is the script that is being called in LateUpdate but I dont htink the script is a problem

elder hearth
#

What version of unity?

green owl
#

6.2

#

But I had the same problem in 2018 and 6.0

elder hearth
#

Why are you not using the new input system?

green owl
#

Like the old more

#

but it should not be input system problem

elder hearth
#

If you plan to add multiplayer you will have problems(from what ive heard)

green owl
#

Nah it is a singleplayer game

elder hearth
#

Also no runtime keybind changes(the keybinds are hard coded)

green owl
#

I mean it is mouse rotation

#

I dont think there will be any change in that

elder hearth
#

But for the rest of the keybinds

green owl
#

So... do you maybe know why that thing with camera is happning?

elder hearth
#

I mean it cuz the sense is high(atleast thats my assumption)

green owl
#

It should be allowed to rotate this fast

elder hearth
#

also check the camera object and its compontent

green owl
elder hearth
#

Also ive had to look really close to see any problems, im sure it wont effect gameplay

green owl
elder hearth
#

I dont have that problem and my AA is disabled

#

the rest is the same for me

keen dew
#

Turn on vsync in the quality settings and in the game preview window

pallid forum
#

Hello! so, I am trying to make a interactive chess piece following a tutorial video but.. I run the game and clicking on the chess piece object and nothing happen. I have no clue why.
I check everything out.
Here is what I checked:
the object attached Box collider 2d ✅
I attached the script to the object ✅

here's the part I wrote in the script to run

OnMouseUp()
private void OnMouseUp()
    {
        Debug.Log("You clicked on " + this.name + " at position: " + xBoard + "," + yBoard);
        DestroyMovePlates();
        InitiateMovePlates();
    }```

The debug I wrote didn't even shows up in the console when I try to click on the chess piece.
keen dew
cunning bramble
#

hey i need help and it is complicated

#

So i have an NPC self made in blender with an rig and i have animations fo it and it work bc i have it on my player and i want that this NPC walks with nav mesh and it does already but the animation parameter thing dosent work can someyone help me? PLEAS notlikethis

cunning bramble
#

Yes i know but the code is wrong not the animation

frail hawk
#

post your code then

cunning bramble
#

how

#

!code

radiant voidBOT
cunning bramble
umbral bough
#

Hey, I tried doing this in order to be able to validate the value(similar to what odin offers) in the editor, however, the second line crashes the editor.
Is this not what I am supposed to do or something?

var capacity = _shotVFX.GetParticleSystemInfo(0).capacity;
var spawnCount = _shotVFX.GetSpawnSystemInfo(0).spawnCount;
#

I can temporarily work around it by making the spawn count a variable, but this is quite odd regardless.
Please @ me and thanks in advance!

ivory bobcat
cunning bramble
ivory bobcat
#

So it isn't a code issue?

cunning bramble
#

Thats what i dont know

#

but no wait it must be

umbral bough
ivory bobcat
cunning bramble
ivory bobcat
#

Explain why it's a code issue.

cunning bramble
#

ohh yes

#

okay give me 1 min

#

@ivory bobcat

ivory bobcat
#

I've got no audio so I'm not understanding what the video is illustrating. Assuming your animation is set up correctly, I'd try logging some values to see if they're what you're expecting them to be. These in particular: cs // Normalisieren basierend auf Agent-Speed float normalizedZ = Mathf.Clamp(moveZ / agent.speed, -1f, 1f); float normalizedX = Mathf.Clamp(moveX / agent.speed, -1f, 1f); // Animator-Parameter setzen animator.SetFloat("MovmentZ", normalizedZ); animator.SetFloat("MovmentX", normalizedX);

#

The move values, speed and normalized values

cunning bramble
#

i have an idea but how do i active the preview window in the right low corner? where i could see the animations

blissful jungle
#

Guys how do i add jumping

#

To 2d

#

Unity

naive pawn
#

have you tried googling for that?

cunning bramble
#

me?

naive pawn
#

no, my internet is currently shit and i can't load your video lmao

cunning bramble
#

trust me you will be lost when you see this

#

it is very wierd

#

and yes i have watched like 20 tutorials but nothing works

mortal gale
#

can someone please help? how to make 8 directional sprite 3d????

#

i searched for every vid on ytube and everywhere but cant find this guides

naive pawn
thorn kiln
#

The course I'm doing is trying to teach me variable attributes, but I'm not really sure I get them. I've tried to make them simple to understand rather than the very jargon-y ways that they tend to be explained

**Public **- Visible in inspector and can be accessed by other scripts
**Private **- Not visible in the inspector and can't be accessed by other scripts
**[SerializeField] **- Visible in the inspector but can't be accessed by other scripts
**Protected **- Not visible in the inspector but can be accessed by other scripts(?) (ones that inherit the same class? Since I've only ever seen MonoBehaviour I don't really know what this entails)
**const **- Makes it so a value can't be changed, this was in JS so I understand it (I hope)
**readonly **- You set the variable when you create the object but then never again. Not really sure how this is different to const? Does that mean you can only define it once? Like you declare a bool and then can initilize it as true/false later, but then it's locked forever after?
**static **- I honestly have no idea. "If you want to have a global variable to use anywhere in your code at all times", I don't know what that means or how it'd be used.

frank moon
#

hello guys, im a bit new to unity and to c#. What do you recommend me to do to learn c# ?
Thanks

naive pawn
# thorn kiln The course I'm doing is trying to teach me variable attributes, but I'm not real...

a few notes:

  • most of these are modifiers, not attributes. SerializeField specifically is an attribute, as indicated by using [ ]with it.
  • access modifiers are also in lowercase
  • const isn't js const, readonly is more like js const
    • readonly is for a variable that doesn't get reassigned.
    • const is for a variable with a compile-time constant value.
  • static is also in js, it's an OOP thing. it means the member belongs to the type rather than an instance.
thorn kiln
#

Blame the unity course

bright reef
#

can somone tell me how to use layers in tile maps?
Image

modern meteor
#

how do I make my player move?

thorn kiln
#

It's also now trying to teach me event functions. So tell me if I've got this right.
**FixedUpdate **- For use with physics, called before Update
**LateUpdate **- For use with cameras, I presume it's called after Update
It's also trying to teach me Awake, but with no context it doesn't really make sense how and when to use it.

cosmic dagger
thorn kiln
#

The documentation is really hard to read though, it explains stuff in the most jargon-filled unsimplified way it can

#

So Im trying to boil it down to a level that I can understand it

cosmic dagger
keen dew
#

FixedUpdate isn't called before Update (or at least it's not a useful mental model to think that it does.) It runs at its own cycle

thorn kiln
#

Why does the Unity Pathway lie so much then? 😂

cosmic dagger
keen dew
#

If it says that it runs before Update, that's technically true but not useful information at least to a beginner

cosmic dagger
#

FixedUpdate runs before Update in the Unity lifecycle . . .

keen dew
#

It does but that's not its defining characteristic

cosmic dagger
#

Yes, you can set how often it's called, but during the same frame as Update it will always run first. That's the important characteristic . . .

keen dew
#

No it isn't

#

If someone who doesn't know Unity asked a one-sentence description of FixedUpdate, that sentence wouldn't be "it runs before Update"

thorn kiln
#

What would it be then?

keen dew
#

"It runs at fixed time intervals instead of every frame"

thorn kiln
#

What defines the time intervals?

#

Like if I'm literally just changing Update to FixedUpdate

keen dew
#

It's set in the project settings. 50 times/second by default.

naive pawn
modern meteor
cosmic dagger
modern meteor
cosmic dagger
modern meteor
#

alright sounds easy enough

cosmic dagger
#

What matters is actually starting. Dive right in . . .

modern meteor
#

hey what if I just used if statements and move.x

#

wouldn’t that be easier

fringe frost
#

i came back to unity after like 4 years and faced my worst enemy so far: ONTRIGGERENTER. no matter what i do it just... doesnt work.
my setup: two rigidbodies, two colliders, one is trigger. the enemy box has a boxcollider2d and a dynamic rigidbody, the bullet also has a dynamic rigidbody but circlecollider2d set as trigger.
in the script for the bullet i listen for triggers enters but it just doesnt work. tried that on the enemy too but didnt work.
im... not sure what to do. i also clearly remember struggling with the exact same thing before but i dont remember what fixed it.

cosmic dagger
fringe frost
#

tried mishmashing everything too: enemy as trigger and bullet as trigger, nope. both triggers, no (makes sense because two triggers wont collide and wont make an event)

cosmic dagger
fringe frost
#

what

cosmic dagger
#

One method is for regular 3D physics. The other method is for 2D physics . . .

#

Look at what type of colliders you have on your objects . . .

fringe frost
#

ah..........

#

i actually

#

thought about doing this

cosmic dagger
#

Are you making a 3D or 2D game? These are the signs you have to pay attention to . . .

fringe frost
#

YAY it worked

remote fable
#

Does anyone have an Idea why my player movement "lags" when I dont have my player open in the inspector? this also happens in builds qwq
I have my Movement in FixedUpdate and my camera movement in LateUpdate

keen dew
#

You'll have to show the code

remote fable
# keen dew You'll have to show the code
    void HandleCameraMovement()
    {
        mouseX = lookInput.x * cameraSensitivity * Time.deltaTime;
        transform.Rotate(Vector3.up * mouseX);

        mouseY = lookInput.y * cameraSensitivity * Time.deltaTime;
        currentCamAngle -= mouseY;
        currentCamAngle = Mathf.Clamp(currentCamAngle, -maxCamAngle, maxCamAngle);

        cam.transform.localRotation = Quaternion.Euler(currentCamAngle, 0f, 0f);
    }
    void HandleMovement()
    {
        if (isSprinting && currentStamina >= sprintMinStamina && isMoving)
            {
                movementSpeed = sprintSpeed;
                currentStamina -= sprintStaminaUsage * Time.deltaTime;
            }
            else
            {
            movementSpeed = baseSpeed;

                regenRate = isMoving ? staminaRegenRateWalking : staminaRegenRate;
                currentStamina = Mathf.Min(currentStamina + regenRate * Time.deltaTime, maxStamina);
            }

        Vector3 forward = cam.transform.forward;
        Vector3 right = cam.transform.right;
        
        forward.y = 0f;
        right.y = 0f;
        forward.Normalize();
        right.Normalize();

        Vector3 targetVelocity = (forward * moveInput.y + right * moveInput.x) * movementSpeed;
        
        movementControlFactor = IsGrounded() ? 1f : airControl;

        currentVelocity = Vector3.Lerp(currentVelocity, targetVelocity, (moveInput.magnitude > 0 ? accelerationSpeed : decelerationSpeed) * movementControlFactor * Time.fixedDeltaTime);

        rb.linearVelocity = new Vector3(currentVelocity.x, rb.linearVelocity.y, currentVelocity.z);
    }
keen dew
#

Don't multiply mouse input by deltatime. You'll have to then lower the sensitivity after removing it

remote fable
keen dew
#

With deltatime the mouse movement depends on framerate and things like that can change the editor's framerate

remote fable
#

That makes sense yeah qwq
Thank you!

remote fable
dense goblet
#

I do wanna ask real quick, in scripting, when is it ever ok to use Numbers instead of Variables?

fickle plume
thorn kiln
#

Can someone explain why my secondary camera isn't in the right position?

fickle plume
thorn kiln
#

Okay, this is how the camera works. Better?

public class FollowPlayer : MonoBehaviour
{

    public GameObject player;
    public Vector3 offset = new Vector3(0, 5, -7);

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}```
naive pawn
#

have you tried debugging player.transform.position or the full result of the addition

keen dew
#

What's the initial position of the vehicle?

thorn kiln
#

Not 0,0,0, which might be the problem

cosmic quail
thorn kiln
#

Yeah, but the one in the inspector is the offset for the secondary camera

#

It does seem to have been that it was adding together the players initial position in-game and the offset

naive pawn
#

why wouldn't it be that

#

that's what you told it to do

keen dew
#

If you want the positioning to stay where it is in the editor you can set the offset at start:

void Start()
{
    offset = transform.position - player.transform.position;
}
#

or make the camera a child of the vehicle and set the rotation in code instead of position

thorn kiln
# naive pawn that's what you told it to do

That's what the course had me write. The guy in the video changes the same things as me and it works fine. This is like, the first prokect they have you work on. It's not my fault it's using jank code.

thorn kiln
#

One of the Unity Pathways

keen dew
#

The guy in the video has the vehicle at (0, 0, 0)

sacred cradle
fickle plume
sacred cradle
hot wadi
#

Do u guys usually use state machines to switch between character status like walking, crouching, jumping etc. ?

sacred cradle
cosmic dagger
sacred cradle
hot wadi
queen adder
#

Why doesn't Application.targetFramerate change the FPS cap in the editor's game view?

thorn kiln
#

How do I make a camera active with code? enabled doesn't seem to do anything, setactive doesn't even come up as an option, active is apparently obsolete

naive pawn
#

SetActive is for GameObjects rather than components

#

so you would do camera.gameObject.SetActive

rich adder
naive pawn
#

enabling a component on a deactivated gameobject won't do anything, so that might be why that didn't seem to do anything

rich adder
#

oh just saw you edited about SetActive.. also you should either SetActive gameobject or disable/enable component itself

#

.enabled comes from behaviours not Gameobjects so GameObject.enabled doesn't make much sense

queen adder
#
public void setFramerateCap()
{
    QualitySettings.vSyncCount = 0;
    Application.targetFrameRate = targetFrameRate;
    Debug.Log("Changed target framerate to " + targetFrameRate);
}
thorn kiln
#
    void Start()
    {
        camera1.enabled = true;
        camera2.enabled = false;
    }```Well that's what I have in my Start, and it doesn't seem to do anything. Keep getting console messages about 2 listeners.
rich adder
naive pawn
#

are the camera's gameobjects deactivated

rich adder
#

so you should just deactivate the gameobjects in this case

#

Cinemachine makes this such a nice process

#

usually, Virtual Cameras > Multiple Camera components

#

Cinemachine keeps 1 Main camera componen but switches the view / setting through Cinemachine Cameras

thorn kiln
#

Well the overall of what Im trying to do just isn't working, nothing seems to be affecting the cameras

naive pawn
#

are the camera's gameobjects deactivated

thorn kiln
#

Ive tried both

naive pawn
#

both what, exactly?

thorn kiln
#

The script doesn't seem to change anything either way

rich adder
#

did you put a log to see if the code is even running

thorn kiln
#

Both turned on, both turned off

naive pawn
#

do you see the checkbox beside the camera component changing

slim tiger
#

Hello people!
Lil' question; What would you consider to be a simple (code-wise) yet impressive - looking game to make?
I have very little coding experience yet, but I'm about to start my TDR (long-ass paper on something (theory and practice) and I want to use it as an opportunity to learn a bit more :]! However, I have limited time (around 7 months, more or less) and I want to make something that takes some effort without it consuming my life

queen adder
#

Because my player jumps higher at higher fps

#

In the build I have higher fps compared to the editor

naive pawn
#

perhaps try to fix the fps dependency then

queen adder
#

Well I want to be able to see the difference

rich adder
naive pawn
rich adder
#

did you verify that code is running ?

queen adder
# rich adder show code for that
if (Input.GetKeyDown(KeyCode.Space) && isTouchingGround)
{
    float jumpForce = jumpStrength * rb.mass;
    Vector3 jumpVector = normalVector * jumpForce / Time.deltaTime;
    rb.AddForce(jumpVector);
}
#

This is in update

#

I'm dumb

rich adder
#

you probably want a Impulse

queen adder
#

I'm dividing

#

by Time.deltaTime

naive pawn
#

that / Time.deltaTime definitely doesn't make sense

rich adder
#

why not just
rb.AddForce(jumpStrength, ForceMode.Impulse)

queen adder
#

Impulse?

naive pawn
#

btw, you could also use forcemode velocitychange to make it so mass isn't taken into account

rich adder
#

impulse already takes into account mass

naive pawn
queen adder
#
rb.AddForce(jumpVector,ForceMode.Impulse);

What's the default ForceMode?

naive pawn
thorn kiln
#
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            if (camera1.isActiveAndEnabled)
            {
                camera1.enabled = false;
                camera2.enabled = true;
            }

            if (camera2.isActiveAndEnabled)
            {
                camera1.enabled = true;
                camera2.enabled = false;
            }
        }
    }```Okay, I messed around a bit more, but this doesn't seem to be working.
rich adder
#

AddForce should not be called in Update unless you use Impulse

slim tiger
queen adder
#

okay i still want to be able to cap the fps

naive pawn
thorn kiln
#

Yes

naive pawn
#

...and the result was..?

rich adder
thorn kiln
naive pawn
#

ok, we don't know what those logs are

#

buddy if you want help you have to provide adequate info

thorn kiln
#

Can you not infer?!

naive pawn
#

you have 5 booleans here

rich adder
naive pawn
#

im not gonna assume which ones you chose to log and in what order

thorn kiln
#

One is true, one is false, and it's about switching cameras. Guess.

rich adder
#

we can see the result, we have no idea where you placed these..

#

something called context

naive pawn
#

you've been providing lackluster, inadequate info for a long while

#

you need to get better at asking questions

#

support is a 2 way street

polar acorn
#

So, guess

naive pawn
#

we are not psychic, and what you assume are "obvious" logs are not guaranteed. we deal with a bunch of bullshit. you can't be bothered to write out 1 sentence clearly explaining the thing you so badly want us to magically infer?

thorn kiln
#

Becuase if I write out the full context of everything it becomes a massive text dump and then you also get annoyed about that

polar acorn
#

I mean it's fair to ask us to infer what their logs are. I choose to infer they put them in exactly the places that would tell them the obvious problem, so I don't even need to answer it any more!

Isn't inference grand?

rich adder
#

should work fine if its a build on PC platform

naive pawn
queen adder
#

It works fine

polar acorn
#

Is it mobile? Mobile had some fucky third thing you have to do to quit IIRC

queen adder
#

I was trying to call it from a button and it wasn't being called. That was the problem, not Application.Quit()

#

I'm just trying to figure out why Application.targetFramerate doesn't actually cap the fps

polar acorn
#

Sometimes you find the answer the moment you hit send on the question

queen adder
polar acorn
thorn kiln
#

Okay, I found the problem on my own. It's not that pressing C isn't changing cameras, it's that both things become true as it runs the script so it is doing something, just so fast it's inperceptible.

polar acorn
thorn kiln
#

Basically, the problem was that I needed an else if statement

thorn kiln
naive pawn
#
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            if (camera1.isActiveAndEnabled)
            {
                camera1.enabled = false;
                camera2.enabled = true;
            }

            if (camera2.isActiveAndEnabled)
            {
                camera1.enabled = true;
                camera2.enabled = false;
            }
            Debug.Log(camera2.enabled);
            Debug.Log(camera1.enabled);
        }
    }
```something like this would not be out of the ordinary, especially so in a beginner channel. again, *we aren't psychic.*
slow blaze
#

hey I want to mak a timer that does a specific code block for 3 seconds continously until if finishes
this executes way too fast (the function is called on a button press not in update)
how can I do something likee this? can I run the code continously with a coroutine?

thorn kiln
#

I'm not talking about the logs, just looking at 2 if statements one after the other that switch the enabled status of the same things, people who aren't me could see why that's wrong

naive pawn
#

also for future reference,

#

!code

radiant voidBOT
polar acorn
rich adder
polar acorn
#

Putting logs in both if statements would show you that both were running and demonstrate to you what the problem was so you actually understood it and came to the conclusion on your own

#

Which worked by the way

slow blaze
naive pawn
#

yeah.. then don't do that

rich adder
cosmic quail
naive pawn
#

you would use a yield return null; to wait 1 frame and then continue with the action

slow blaze
#

Oh I see thanks

random lodge
#

How do you do this inside the animator script? Doesn't appear to work the same way.

naive pawn
#

that's not how setbool works nor how it's spelt

random lodge
#

Irrelevant. It's there to show what I'm doing.

rich adder
naive pawn
#

you have an Animator, you have a name, you know it's a bool, and you have a value you want to set.

how exactly does it "not appear to work the same way"?

naive pawn
random lodge
#

I'm just going to ignore you. You are annoying.

naive pawn
#

what is going on today, damn

rich adder
#

you have to assume people you show problem to are 6 year olds that have no idea what you're showing (no really its a technique), the more you explain it the better...hell you might even end up rubber ducking the problem and solving it all on your own..happens often..

random lodge
#

Think I got it anyway.

naive pawn
#

wonder what this was about 😆

Doesn't appear to work the same way.

polar acorn
slender nymph
random lodge
slender nymph
#

lol someone's mad

rich adder
slender nymph
#

examples usually need to make sense though

random lodge
#

Consistent arrogant answers do become annoying.

slender nymph
#

show me where i was being consistently arrogant to you

polar acorn
random lodge
#

Well if you are unintelligent enough to figure out what I'm trying to do from an example that's on you buddy.

#

Or you could ask.

slender nymph
#

ah yes, i'm the one being unintelligent here

rich adder
#

ah yes, good way to get help around here.. insult the only ones with the patience to entertain your foolishness

naive pawn
# random lodge Consistent arrogant answers do become annoying.

please, do point to where the arrogance was.

seriously though. you asked about a thing that "apparently didn't work as usual"

it turns out that it works exactly as usual. if you'd just wrote the actual code rather than the weird pseudocode you'd see that it does, in fact, work

random lodge
#

You won't get any civility from being arrogant.

naive pawn
#

where was the arrogance

#

or are you just throwing around words

rich adder
#

had people actual put effort first learned the actual basics instead of running here with every basic things , we would probably avoid half these questions..

naive pawn
#

to be blunt here: no-one here is being arrogant. you're ignoring advice everyone's trying to give on basic skills.

the sooner you realize that you're lacking, the sooner you can start to improve them.

random lodge
#

If you can't handle questions attempting to get pointed in the right direction you might as well not say a word if you can't respond with an answer that doesn't make you come off as arrogant. You're in #code-beginner.

polar acorn
random lodge
#

If that doesn't make sense to you, you'll never be helped.

naive pawn
naive pawn
#

digiholic pointed out researching the things you're trying to do and docs.
me and nav pointed out what info you did have available.
boxfriend pointed you to rechecking your skills.

#

everyone here is trying to help. none of us can if you don't accept it.

random lodge
#

There's that arrogance. He still hasn't learned.

naive pawn
#

ok, point out to me where the arrogance is. perhaps i can learn then

rich adder
#

this has to be a troll right?...right?..

naive pawn
#

huh, that's not a bad explanation.

slow blaze
polar acorn
naive pawn
polar acorn
#

Then they can't desync

naive pawn
#

(also with how you've set it up, they can't finish at the same time. timer takes 3 seconds, but fillAmount takes 10/3 ≈ 3.333 seconds)

slow blaze
rich adder
#

maybe you want to Lerp if you want it to take exactly 3 seconds to get to Full

sacred cradle
naive pawn
#

yeah just lerp instead of trying to figure out the math tbh

radiant voidBOT
naive pawn
#

the math isn't hard, but lerp makes it way easier (and harder to mess up accidentally)

slow blaze
#

the lerp would be like
Lerp(1, 0, timer * deltaTime);

#

I think?

naive pawn
#

no, you wouldn't be using deltaTime there

rich adder
naive pawn
#

i usually use this pattern

float elapsedTime = 0;
do {
  elapsedTime += Time.deltaTime;
  value = Lerp(MIN, MAX, elapsedTime / LIMIT);
} while (elapsedTime < LIMIT);
#

does that make sense?

slow blaze
#

yeah it does

slow blaze
#

the closer the elapsedTime is to the limit the more it fills

#

I get it thanks

naive pawn
#

yknow thinking about it now that probably is wrong. the += Time.deltaTime should probably be after taking the current value.

rich adder
#

Lerp wants t to be 0-1

fickle plume
#

!warn 356111028213383170 If you are not using the channel for Unity questions don't spam the channel with off-topic. If you continue insulting people you'll be gone from here very quickly.

radiant voidBOT
sacred cradle
# rich adder aside from Learn sent, check the pins here too for the general c# stuff you will...

i have a question which i couldnt solve in 15 hours its more than 2 weeks tough did 10 hours of chatgpt youtube etc replaced code many times still not fixed.
the problem is i made a joystick on left side for playermovement and the right side 60% of screen i gave it to touchpanel where i can rotate screen but when my first finger is outside of that touchpanel area(on joystick) then the 2nd finger which i use for controlling the camera movement does not works

naive pawn
rich adder
#

yea

#

not sure if its correct or not though lol

naive pawn
#

i mean like 🤔 on the frame it's called, it should be t = 0, right?

#

not sure if i am right though

#

if you start it with a high deltaTime it'll be done immediately instead of the next frame

#

maybe that's better.

rich adder
#

ha yeah goes above my basic brain, definitely something to test I suppose

naive pawn
#

maybe it doesn't matter lol

rich adder
cosmic dagger
sacred cradle