#archived-code-general

1 messages · Page 136 of 1

leaden ice
#

I don't see any entities related code here

outer juniper
#

obviously it isnt there yet. Because dont know how exactly to work with it. No guides

void basalt
#

You don't need 3rd party tutorials. If you understand why ECS is performant in the first place, and what it's doing with the memory, it's very easy to dive into.

#

both of which the unity docs show very clearly.

lean sail
#

by not storing it on the device at all

#

Maybe then using the android keystore, although i dont know much about it

#

I think the only other option would be hiding the key, or writing it to a place where your application only has read permissions

#

I see something about internal storage, where users cant just access the file from your phone. but yea someone could just open it up in other ways

#

I mean regardless of how u store it, if this information is important enough, someone would break apart your app and find how its stored no matter what you do

#

if its just local game data, with no online highscores or purchase system then i wouldnt really worry about this

#

Yea i wouldnt waste time on this if its not real money or online at all

#

most wouldnt even know how to edit their files in the first place, even if they were handed the encryption key. Anyone who wants to edit it and is dedicated enough to even find the key in the first place to edit data for a local game is desparate enough id probably help them edit their file

#

im unsure what you mean tbh

#

you would be encrypting when saving.. if that answers the question. I really dont know what manually would even involve here

tulip fjord
#

hey, ```` barrel.transform.RotateAround(barrel.transform.position,barrel.transform.right,Time.deltaTime*rotationSpedRad);

#

transform.rotate is also translating the object to much

#

i guess i have to set the transform.position afterward, or add a joint. but i really dont get it. i thought rotateAround should fix this, but its not

spiral dagger
#

I have a question, can we invoke an event from another class? suppose an event is written in ClassA and we are trying to invoke it in ClassB, is that possible?

spiral dagger
#

Because I am getting an error
The event 'ScriptB.UpdateScoreUIEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ScriptB')

#
using System;
using UnityEngine;

public class ScriptB : MonoBehaviour
{
    public static event Action UpdateScoreUIEvent;

    private void OnEnable() {
        UpdateScoreUIEvent += UpdateScoreUI;
    }

    private void OnDisable() {
        UpdateScoreUIEvent -= UpdateScoreUI;
    }

    private void UpdateScoreUI() {
        print("Updated Score UI");
    }

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptA : MonoBehaviour
{

    private void Start() {
        Invoke("InvokeEvent", 3);
    }

    private void InvokeEvent() { 
        ScriptB.UpdateScoreUIEvent?.Invoke();
    }

}


royal pulsar
#

I've made a finite state machine via interfaces. I have a StateController monobehaviour and two IStates: RoamState and ChaseState. The problem is the states have a lot of logic and require data from other scripts to work. As they are just IStates and not monobehaviours they cannot reference the needed scripts in Awake() so the references have to be acquired in StateController and then passed to the states as a parameter in the OnEnter() and UpdateState() functions. At this point there are lots of parameters being passed in and it feels quite messy. Is there perhaps a better approach that circumvents this issue?

tulip fjord
tulip fjord
tulip fjord
#

@royal pulsar you can stores your dictionaries inside a list

tulip fjord
spice cave
prime sinew
spiral dagger
digital coyote
#

I a trying to make my Player able to lean left and right (like in Rainbow 6 siege as an example) but I can figure out how. Can some please help me.

frosty pawn
#

Will asset be included to build if it was linked in field like below?

#if UNITY_EDITOR
public GameObject Prefab;
#endif
trim schooner
#

No

quartz folio
#

It's a bad idea to exclude serialised data using preprocessor ifs

#

The engine dislikes you doing it and it can cause random warnings to be present in your project, along with miscellaneous things going wrong

frosty pawn
quartz folio
#

Don't serialize the field in a runtime object if it's intended for the editor only

frosty pawn
#

How then I access to this asset in editor?

quartz folio
#

Asset database is one option

frosty pawn
#

Ok, what if I want it to development build but not to production?

quartz folio
true bramble
#

our naming convention for commits is beyond professional.

languid hound
#

Is there any way to add / remove triangles to meshes at runtime? What about bones too? If so is there anywhere I can read up on this

#

Wanted to make a snake that changes dynamically in length but connected capsules just ain't gonna do it lol

steady moat
languid hound
#

I see. Is there a way I can add objects to deform the mesh though?

#

Like not just the bones

steady moat
#

Sure

#

I never done it, however that would be strange if it was not possible.

#

At the end, you could implement your own API if needed.

warm stratus
#

is there a way to add outlines to a ui sprite but not that?

heady iris
#

just extra transforms that deform the mesh?

languid hound
#

Yeyeye

heady iris
#

when you say "objects to deform the mesh", I think of actual softbody physics

#

ok, that's simpler

steady moat
#

He is doing a snake.

heady iris
#

I have also not done this, but fundamentally, you just need to make sure that the mesh has vertex weights that correspond to these new "bones"

#

that's the part I'm not sure about

languid hound
#

That's fair enough I'll look about on the docs. Thank you for the advice

wide dock
#

Loading resources is about to drive me crazy.
LoadAll<> didn't work so now I'm specyfying where exactly the asset is so that it can load it and yet it fails once again.
Does anyone have any idea why does this happen (and how to fix this)?

sacred vault
#

I need to refer a custom file on my script

leaden ice
wide dock
knotty sun
wide dock
knotty sun
wide dock
#

No, there haven't been any problems with loading from Scriptable Objects so far if I remember correctly

#

The issue is only with loading an "instance" from Scriptable Singletons

#

The thing is, loading from Scriptable Objects only takes place if loading from Scriptable Singletons ends up successfully, so I can't really tell if there wouldn't be any problems with loading them separately

#

Worst case scenario I'll just place a "Scriptable Singleton Holder" GameObject into the scene and reference my libraries there, but I'd preferably like to just Load them from the files as I mostly need to do that while not in playtest mode.

knotty sun
#
        AttackLibrary_SS al = Resources.Load<AttackLibrary_SS>("Scriptable Singletons/AttackLibrary");

works for me

wide dock
#

Welp, I've switched to

public class AttackLibrary_SS : ScriptableSingleton<AttackLibrary_SS>
``` and deleted my `instance` definition to let Unity handle this
So far it works, we'll see how it goes.
wide dock
valid solar
#

quick question, if i had a variable field which accepts a Class, any script that inherits from said class should be accepted into that field right?

#

i cant figure out how it works, and i probably have it wrong, but thats what was logical to my brain

#

Currently have a script called AltarBuffEffect, and a script called HealthBuff which inherits from AltarBuffEffect, but I cant drag it into a field of type AltarBuffEffect

craggy veldt
#

and it's Editor-only

#

and you don't need to loadResources at all

#

MyScriptableSingleton.instance is all you need

wide dock
golden flume
#

Hello, if i have an OnTriggerStay2D
that call a function that turn a boolean true
and start coroutine

#

while boolean is true playertakedamage
will i call the coroutine multiple time?

valid solar
#

if OnTriggerStay2D invokes the coroutine, yes.

golden flume
#

oh i see

valid solar
#

If you enable it through OnTriggerEnter, and disable the coroutine itself when the bool is set to false, you wont have multiple instances of the coroutine, and it wont continue unless the bool is true

golden flume
#

Ok pretty simple, thx !

valid solar
leaden ice
#

why does it need to be encrypted exactly?

#

The easiest thing to do here is to just include the json file in the assets as a TextAsset. It will automatically be compiled into the main game binary blob

#

this is a plus in my opinion as a gamer but

#

¯_(ツ)_/¯

#

I know

#

I also mean that

#

it does get compiled into the binary blob

#

unless you very specifically place it into a StreamingAssets folder

#

exactly, so why do you care?

#

yes

#

I'm saying:
It is going to be compiled into the game data packed binary so it isn't going to be plain text anyway. But even if it was I wouldn't worry about it.

#

As a game developer I don't care if users cheat at solitaire.

#

it only hurts thmeselves

valid solar
leaden ice
#

or they have fun doing it

valid solar
#

if they want to cheat they'll cheat

leaden ice
#

either way - the user is having fun why would that upset me

plush sparrow
#

getting this error when trying to add a package from github

  Could not clone [https://github.com/itisnajim/SocketIOUnity.git]. Make sure [HEAD] is a valid branch name, tag or full commit hash on the remote registry. [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()```
leaden ice
#

Exactly - you only hurt yourself

leaden ice
plush sparrow
#

yes

#

it worked for another guy who sent me this link

#

not wokring for me

leaden ice
#

that should work

#

as per^

plush sparrow
#

yeah it says to add the link in the package managaer

#

but the package isnt getting imported

leaden ice
#

well yeah you;re getting an error

plush sparrow
#

yeah anyone knows how to fix it?

#

i read a thread about editing the manifest file , i will do that now. if theres any other way let me know

#

ok i tried some other packages as well

#

wont import any package from url

rigid island
plush sparrow
#

add package from url

leaden ice
plush sparrow
#

i think issue is because of git in my system

#

yes

#

i am reinstalling git

leaden ice
#

also check for .gitconfig in your home directory

#

you might have some weird stuff in there

plush sparrow
leaden ice
#

your computer

#

like - your user folder

#

/home/Username on mac or C:/Users/Username on windows I think?

plush sparrow
#
    helper = manager-core
[filter "lfs"]
    clean = git-lfs clean -- %f
    smudge = git-lfs smudge -- %f
    process = git-lfs filter-process
    required = true
[user]
    name = *******
    email = *******
    name = *******
#

thats all there is in the .gitconfig

leaden ice
#

hmm that should all be fine I think

exotic burrow
#

Hi, I'm currently using the A* pathfinding algorithm for my zombie ai. However, I'm facing an issue where the pathfinder does not recognize tilemap collider with a composite collider as a collider. As a result, the zombie clips into the tilemap. Is there any solution or fix for this problem?

rigid island
exotic burrow
mossy shard
exotic burrow
#

im not pretty sure

mossy shard
#

different from*

mossy shard
#

ye then you used A*, not dij, a star is like a remade version of dij

mossy shard
exotic burrow
#

oh

#

nvm i fixed it

heady iris
#

well, it sounds like you need to examine how you decide what areas are and aren't walkable

mossy shard
#

K gfu

exotic burrow
#

thanks

gaunt blade
#

Hey so I have a really weird issue. There's no errors being thrown, so it's got to be a bug somewhere with the logic of the code. Thing is it was working previously and now suddenly it doesn't anymore.

#
  triangle.getCircumcircle().render(.05f);```

The issue is somewhere along this line of logic
#

The triangle.render() works absolutely fine, yet for some reason the render function for the circle objects do not work, despite the fact that they both use the same underlying render function within the Line objects used to represent edges.

#

You can see that all the triangles here are rendering despite the fact that the circles called immediately after them, are not.

heady iris
#

have you confirmed that GetCircumcircle works correctly

gaunt blade
#

circumcircle = new Circle(this.getCircumcenter(), Vector2.Distance(this.getCircumcenter(), this.getVertices()[0])); This is the line that creates the circumcircle, it's in the Triangle class in the link I posted. It doesn't throw any errors, and I know that the Circle class does work because the triangle generation is based on those circles.

heady iris
#

sure, but that doesn't mean that circles are rendering correctly, or that the circumcircle is being generated correctly

#

verify both of these things

#

render a circle by itself, and do something to prove to yourself that the circumcircle contains valid points

gaunt blade
#

I'm unsure what you mean by "generated correctly". The circumcircles are being generated correctly because if they weren't, the triangles would not be getting generated correctly.

#

The generation of the triangles is based on the circles of previous triangles

#

This is part of a delaunay triangulation algorithm.

heady iris
#

well, you're currently in a situation where the circles aren't working

#

so you should rule out as many issues as possible

gaunt blade
#

The rendering isn't working

heady iris
#

i don't know how the rest of your code works, so I don't have any information beyond what that file contains

gaunt blade
#

The circle class works fine

#

That file contains all the classes

heady iris
#

triangulator.getTriangles(); is where the triangles come from, presumably

rigid island
steady moat
heady iris
#

you need to rule out problems.

#

start ruling out problems.

gaunt blade
heady iris
#

yes, and so i see no reason for "triangles work" to be proof of "circles work"

steady moat
heady iris
#

you can spend all day trying to convince me that X isn't the problem, but it'd be much more useful to just prove that X isn't the problem...

gaunt blade
steady moat
gaunt blade
#

As stated, the issue is not with the delaunaryTriangulation class.

gaunt blade
heady iris
gaunt blade
#

That isn't relevant because of how the classes are designed, but you guys haven't looked at the classes because that code paste is long and you responded immediately.

#

If you could actually take a look at the logic

#

That'd be great

heady iris
#

you should always simplify as much as possible

gaunt blade
#

Cause I already stated the issue is with the rendering

heady iris
steady moat
gaunt blade
#

Oops

#

Highlighted the wrong one

steady moat
#

We are trying to eliminate issues.

heady iris
#

again, simplify as much as possible

#

just try to draw a circle. nothing else.

#

no intermediates, no extra work.

heady iris
# gaunt blade

i did, indeed, see that this was how the circumcircle was generated

steady moat
#

The issue could potentially be from the: setSteps function.

heady iris
#

oh

#

you set radius and center after calling setSteps

#

the circles have a radius and center of zero

gaunt blade
#

Yes

exotic burrow
gaunt blade
#

That might be it actually

rigid island
exotic burrow
#

a custom solution

gaunt blade
#

that was definitely the issue. I knew it was some minor logic error somewhere.

#

Thank you.

heady iris
exotic burrow
#

the first thing i do is generate a grid

#

and for each node*check if it is walkable or not

#

but with a composite collider

#

the check is always true

#
        for (int i = 0; i < sizeX; i++)
        {
            for (int j = 0; j < sizeY; j++)
            {
                // ...

                var walkable = !Physics2D.OverlapCircle(nodeCenter, nodeRadius - .1F, obstacleLayer);

                // ....
            }
        }
gaunt blade
heady iris
#

no, since they're fields

#

fields get a default initialization

#

only local variables can be uninitialized

gaunt blade
#

Interesting.

heady iris
#

I think it's equivalent to writing T fieldName = default;

gaunt blade
#

Well, thanks. One step closer to getting my triangulation algorithm working.

#

I hate algorithms. Hopefully I don't have to work on too many more after this.

rigid island
#

i usually just use the obstacle tilemap to tell algo where obstacles are

#

or exclude them from the algo entirely

rigid pine
#

Hey guys, need help finding the positions of 4 corners of the rectangle drawn in red, i am trying to confine the view to the collider visible, currently i am using the far clip planes corners to confine the space but it is not giving me accurate results, if i can find the the points intersecting the cameras viewport extents and ground , i think i could achieve the result i want

civic carbon
#

are all uniquely decodable codes prefix codes?

heady iris
#

consider a language with two symbols, a and b, encoded as 0 and 01

#

0 is a prefix of 01

#

but it's still uniquely decodable as long as we can look ahead at least one character

#

I think you do have to have a prefix code to be able to uniquely decode without lookahead.

steady moat
gray mural
#

I have this class in the script with another class withing the same namespace. Script called TypingField and first class called TypingField too. This TypingFieldHelper's Update method is not being called.

public class TypingFieldHelper : MonoBehaviour
{
    private void Update()
    {
        print("nice");
    }
}
swift aspen
gray mural
swift aspen
#

no, you need a second file for it

gray mural
gray mural
#

Is it possible to get all methods that execute in the certain period of time?

tropic quartz
#

I've made a method return a bool just so that I can check for it's completion.
And I think I used some weird lambda thing for coroutines in one spaghetti filled game.

But I dunno if Unity keeps track of all methods that execute somewhere.
Oh, maybe you could use event system for that sort of thing, dunno.

mental rover
sage latch
#

I have this base class that saves data to a save manager when the scene is unloaded. I have to access other components during this process, but they are destroyed before the method runs, resulting in a missing reference exception. No luck with execution order or SceneManager.sceneUnloaded :/

#

Is there a solution to this?

radiant maple
sage latch
radiant maple
#

Will try that

sage latch
#

also dont crosspost

radiant maple
#

Ok, it didnt work but here is vid of issue

sage latch
tropic quartz
#

Also I noticed that your first function is Update, so you are adding those listeners on every frame, dunno if that could mess up something but ye

radiant maple
#

I changed it to OnEnable

vagrant blade
radiant maple
#

ok

sleek hedge
#

is it worth it to pool objects that i use to send damage info?

sage latch
sleek hedge
#

yeah

leaden ice
#

And what is their lifecycle

#

(also are they structs? classes?)

sleek hedge
#

anytime anything that takes damage aclass with info like the sender, reciever, damage, location... etc and

#

and they have a short lifetime

sage latch
#

A struct should be fine

sleek hedge
#

should you have mutable data in a struct?

leaden ice
sleek hedge
#

idk just thought yo werent supposed to

leaden ice
#

Why would they be mutable if you shouldn't mutate them

sage latch
#

If the struct is very big and you're passing it to functions often, a class might be better to avoid copying

crisp flower
#

Hiya, I did some codey things using AssetDatabase functions and then lo and behold you can't compile that to android.... Obviously. So, I've moved to using Resources.Load which works to load the right assets, however I have a line to get the path/filename of an asset and use that later to load things....

    path = AssetDatabase.GetAssetPath(asset);

Essentially I just want the filename of an asset I have exposed as a public variable in the editor. Any way to do this? Perhaps a script that when it's building just runs that AssetDatabase command and saves the output to a string in the component instead?

leaden ice
#

If you want immutable structs look into records

leaden ice
sage latch
#

or readonly structs 🙃

sleek hedge
#

i do agree however there is a field for the damage that i need to modify based on stuff

leaden ice
#

just use it directly

crisp flower
#

It is for a localisation system and I have different folders for different languages.

#

So when I change language I want to load the same filename thing but in a different language folder

leaden ice
#

Have you thought about using Unity's built in localization package?

sage latch
#

Why not put it in a Resources folder?

crisp flower
#

we are using the localisation package for audio/visual assets but not for subtitles

#

so it is in a resources folder, but I still want to be able to ie:

Resources.Load(subtitles\EN\file.txt
Resources.Load(subtitles\ES\file.txt

etc

sage latch
#

So why do you need to use assetdatabase instead of resources?

#

Oh wait I read the original question wrong

crisp flower
#

because, I need to GET the filename of the linked asset, in order to load the same named one in the resources folder.

I am using resources.load to get the assets, and this works, but I need to replace the AssetDatabase function which gives me the filename of the asset linked in the inspector

sage latch
#

Yeah, you probably need to chose a different approach

neon junco
#

Hey all so i am about to work on a game for Uni but trying to figure out how to do something that i can't seem to get my head wrapped around.

How would I go about making a fence prefab that during run time i can put into the scene to make a fence around a garden but I would want to implement it to be a free form kind of making your own fence due to the garden being a custom garden.

My best thoughts around making this happen is putting in a pole and then instantiate the fence prefab from that pole and allow it to be stretched by modifying its transform scale but clamping the x & z values so it can't go to far. Then once its finished being placed it drops another pole and the process repeats.

crisp flower
#

is there a function that calls when you update a particular field in the inspector? Like when I drag in an asset it just writes a private string which is the filename of that asset

#

and then use that instead

sage latch
#

OnValidate

crisp flower
#

ooh

sage latch
#

Remember the private field has to be serialized in order to be "remembered"

crisp flower
#

that might work. Thank you

leaden saffron
#

Anyone know how I can get one end of my line renderer to stick to my player as it's moving and the other end to stick to the grapplePoint?

#

it makes the line when i click it but it doesn't continue following the players movement

#

also if i switch to a different grapplePoint object it will make a line from my player to the last grapplePoint that i used, not the new one

heady iris
#
    private void DrawGrapple() {
        lr.enabled = grappler.enabled;
        if (lr.enabled) return;
#

this only updates the points if you AREN'T drawing the line

#

that seems backwards...

wide terrace
#

I can't believe I missed that earlier 🤦‍♂️

leaden saffron
#

thanks i missed the ! part before it lol

soft shard
#

Is there a faster way I can check if an array (or any other collection, im fine with changing it) contains a type than using .Exists? I have an array of a base class and a function like this - is using Exists the fastest option in this case? Looking online, .Contains was suggested, but id need the object and I only have the type so im not sure how I could use contains without Linq (which would be more expensive), I also looked at a HashSet<SomeBaseClass> but same issue, I dont think I can check the type through it - normally this isnt a problem, but profiling suggests the number of AI using this function contributes the most to alloc

SomeBaseClass[] arr;

public bool HasClass(Type someType)
        {
            return arr.Exists(x => x.GetType().Equals(someType));
        }
misty blade
#

Hello, I noticed that Physics2D.RacastAll does't hit colliders that have offset the collider component. So for exaple a BoxCollider2D with offset (0, 0) is being detected by RaycastAll just fine, but the same collider with offset (-6.1875, 0.34375) is not detected. Is there a way to get around this? Is it a bug or should it be like that?

misty blade
soft shard
sage latch
#

Dont crosspost and not a code question

misty blade
#

The raycast is damaging enemies so I can easily see when it hits. But to better understand the issue I also logged raycasts outcomes. (the blue ray hitted both player and enemy but not the collider that is between them. The green lines on the picture is the box collider 2D)

eager yacht
misty blade
soft shard
eager yacht
#

Can even do a for/foreach and do a manual check as well instead of linq. Really whatever works lol

misty blade
#

I removed the layer mask and got same results. Seems like collider's offset is the only thing thats effecting raycast outcome

static matrix
#
 public void EnableColliders(GameObject Which, bool state)
    {
        var Cols = Which.GetComponentsInChildren<Collider>().ToList();
        if (Which.GetComponent<Collider>())
        {
            Cols.Add(Which.GetComponent<Collider>());
        }

        foreach (Collider c in Cols)
        {
            c.enabled = state;
        }
    }

rate this function/10
looking for tips

eager yacht
#

GetComponentsInChildren already gets the collider on the initial object

static matrix
#

good to know

eager yacht
#

It's very dumb

sage latch
#

You also dont need to convert it to a list (because you dont need the check)

eager yacht
#

^

static matrix
#

alright cool

eager yacht
#

I think it's due to how it does recursion to where it isn't avoidable, but just a weird thing

static matrix
#

i mean
GetComponentsInChildrenAndSelf
is pretty clunky

sage latch
#

the parameter Which doesn't follow naming guidelines either

eager yacht
#

Yeah but at least you would know it includes self smart

sage latch
#

also it's kind of a weird name, but I guess it's fine

static matrix
sage latch
#

what confuses me is that the second parameter is not CamelCase

sage latch
#

You can do that in rider

static matrix
#

im in too deep
it'll mess my code up

#

....probably

sage latch
#

it should rename references usages too

#

what might screw you over is serialized fields

static matrix
#

oh god
I
I public everything
its a very very bad habit
ill stop ranting about my bad code practices

sage latch
#

oh god, that probably increases the size of your project and builds by quite a lot

#

maybe not project as it's already really big

static matrix
#

im so sorry

sage latch
#

🫠

static matrix
#

basically

sage latch
#

Love the random delegate declaration

static matrix
#

what where

sage latch
static matrix
#

oh
I dont even use that 🤦

#

ill remove it

sage latch
#

Also this is crying for some separation

#

I see UI combined with gameplay

static matrix
#

where?

sage latch
#

And visual effects

static matrix
#

it just controls the bars, because the health is stored here

#

oh VisFatigue isn't a visual effect

#

its
uh
worse

sage latch
#

Vignette is though

static matrix
#

yes it is used to show damage

sage latch
#

Best coding practices would tell you to split these things up to minimize coupling

static matrix
#

vis fatigue is separate from actual fatigue, so it can look like fatigue is going up but apply the change after so that the player doesn't drop below fatigue and stop sprinting

sage latch
#

This is not even coupling, it's just a pot of stuff

static matrix
#

it could be worse
I could have all the player things in this script

#

movement, inventory

static matrix
#

🥰

#

yaaay

#

in my first big project, I lumped ALLL the player things into the same script

#

health, movement, damage, attacks

#

it was just one script

sage latch
#

Wait

#

What does your inspector look like

static matrix
#

uhhhhh

#

which parts

sage latch
#

oh god

static matrix
sage latch
#

Meanwhile my projects xD

static matrix
#

yeah
instead I just have less scripts but make them thicc

spring carbon
#

You can use headers to better organize inspector

static matrix
#

its split up a little bit

static matrix
#

curlevel manager does footstep noises I believe

sage latch
#

How did it get to this point?

static matrix
#

yes it does
keeps track of them and plays them

#

this is just
how i tend to do things

sage latch
#

why do you have a manager on your player??

#

dont tell me its a singleton as well

static matrix
#

wdym

#

curlevelmanager is a misnomer, all it does it get told the next level's footstep noise when you go thrrough a level transition, and then play that as the player walks

#

I thought I would use it for more but I ended up not

sage latch
#

alright

static matrix
#

It was being used for footstep effects like splashing and stuff but the splashes were too laggy so its no longer used for that

sage latch
#

How do you handle the inventory between scenes?

static matrix
#

wdym

sage latch
#

keeping the data

static matrix
#

its attatched to the player and I dontdestroyonload the player

sage latch
#

Ah, so I'm guessing it's a singleton your UI then uses

static matrix
#

???
Its probably very bad that i do not know what you are talking about

soft shard
sage latch
#

How does your UI get access to the player's inventory?

static matrix
sage latch
#

Wait, is your UI attached to the player?

static matrix
#

yes

#

it just keeps getting worse

sage latch
#

I dont know what to say

#

So the player carries a canvas on its back?

static matrix
#

yup

#

a few actually

sage latch
#

It's good to split up canvases at least

static matrix
#

one for settings, one for inventory, and one for statbars

sage latch
#

That's fine great, if you're hiding them the right way

static matrix
#

I am
the worst thing about all this is the game runs perfectly fine
which is why I haven't seen the need to mess with stuff

sage latch
#

If it works it works 😄

static matrix
#

yeah basically

#

I do use abstracts tho
which are nice

sage latch
#

Well, good luck on your spagetti dish disguised as a Unity project

#

I will proceed to sleep

static matrix
#

cool

wheat chasm
#

Hi, how do I stop a client by the server with the client's ID in netcode?

warm stratus
#

Hi, i have to store in a file json format that is encrypted, which file type should i use? .txt or .json? what s the best and why?

vestal turret
heady iris
#

make up an extension

warm stratus
heady iris
#

you can name it whatever you want

#

it's not going to be something that the user can meaningfully use

wheat chasm
#

@vestal turret Thank you, I will try it!

warm stratus
heady iris
#

if you have to ask that question, then I don't think you should be relying on encryption to protect anything

#

if the key is stored on the user's device, then the user can trivially decrypt and encrypt data at will

dapper flower
#
    public class UnityEventAsset : ScriptableObject
    {
        protected readonly List<BaseUnityEventListener> Listeners = new();

        public void RegisterListener(BaseUnityEventListener listener)
        {
            if (!Listeners.Contains(listener)) 
                Listeners.Add(listener);
        }

        public void UnregisterListener(BaseUnityEventListener listener)
        {
            if (Listeners.Contains(listener)) 
                Listeners.Remove(listener);
        }
    }```
```cs
    public class UnityEventListener : BaseUnityEventListener
    {
        [Tooltip("Event raiser to listen to")]
        public UnityEventAsset UnityEventAsset;
        
        [Tooltip("Response to event raising")]
        public UnityEvent Response;

        private void OnEnable()
        {
            UnityEventAsset.UnregisterListener(this); // WORKAROUND
            UnityEventAsset.RegisterListener(this);
        }
        
        private void OnDisable() => UnityEventAsset.UnregisterListener(this);

        public void OnEventRaised() => Response.Invoke();

        private void OnValidate()
        {
            if (UnityEventAsset != null)
                UnityEventAsset.RegisterListener(this);
        }
    }```
I'm having a problem where when switching to PlayMode and Raising an event, it gives me a `MissingReferenceException: The object of type 'UnityEventListener' has been destroyed but you are still trying to access it.` when trying to access a listener in the list (they come as `null` after hitting play). The workaround is to, OnEnable, remove and add the listener. What's actually going on behind the scenes?
civic berry
#

im getting a weird error every time my player touches an enemy can anyone help please

ArgumentException: GetComponent requires that the requested component 'Player' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[T] () (at <4746c126b0b54f3b834845974d1a9190>:0)
PlayerHp.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/PlayerHp.cs:27)

hollow hound
#

Is multiple .Where() on List is less optimal than one .Where() with united cndidtion in terms of performance?

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in C# or For Each in Visual Basic.
Is it mean that list condition will be gathered and executed only once?
Or multiple .Where() will stride multiple times through the list?

heady iris
#

i believe each one will run the previous enumerator until it finds a value it can use

#

i would expect this to be worse than just using one large condition, still

#

i guess you could measure this by doing something goofy, like 100 consecutive wheres

warm stratus
true python
#

Does anyone here have experience with Ink integration for unity? I'm trying to code a dialogue system and everything works fine except when after choosing a choice and it should jump back to the choices and show them again (everything works fine in the Inky editor), it doesn't show the choices when playing through the dialogue and nothing happens for "two steps", then the dialogue ends

glossy basin
#

Hello there, I assume this is sort of a newbie question, I have a parallel job where I am doing some calculations and right now I am refactoring my code to modify a struct value; The problem right now is that I have some conditionals on my job and in those I want to modify a value inside my struct at the current index, but for some reason the struct does not change at the specified index unless I call the function outside of those conditionals, what am I doing wrong?

 //back
            if (blockBack == 0)
            {
             //Does not work
                AssignData(index, blockPos, BackFace);
            }

            //front
            if (blockFront == 0)
            {
                 //Does not work
                AssignData(index, blockPos, FrontFace);
            }

//Does work outside of conditions
 AssignData(index, blockPos, BackFace);

  private void AssignData (int index, half3 blockPos, NativeArray<half3> face)
    {
        _VertexData[index] = new VertexData
        {
            Position = AddQuad(blockPos, face),
            index = index,
            //  Normal = _VertexData[index].Normal,
            //  Uv = velocityPosition.Uv,
            // Tangent = velocityPosition.Tangent
        };
    }

hollow hound
modern creek
crisp flower
#

Hey, so can I use Resouces.Load in this situation?

Resources.Load("A\thisfile")
Resources.Load("B\thisfile")

where the filenames are the same but the path is different?

modern creek
#

(I'm assuming _VertextData is a private [] that you're not mistakenly re-initializing or overwriting elsewhere, too)

modern creek
#

\t is tab

#

eg: A hisfile and B hisfile

crisp flower
#

thanks

glossy basin
#

It remains at 0 either at Position or Index

#

But when I take AssignData(index, blockPos, FrontFace); outside of the conditions, it does assign the value I expect

#

I have also placed a debug before doing _VertexData[index] = new VertexData and I do receive the input values

echo plaza
#

Hey there, I was wondering if anybody knows how I could use Text Mesh Pro with the Input System Rebinding sample. The only idea I have is to take the text from the regular text component and put it into a TextMeshPro UGUI component.

leaden ice
#

(other than just changing the type in the code and replacing the objects and references in any prefabs/scenes of course)

echo plaza
#

The reason I can't replace the text variables with TextMeshPro is something to do with this:

The new input system cannot yet feed text input into uGUI and TextMesh Pro input field components. This means that text input ATM is still picked up directly and internally from the Unity native runtime.

I have no clue what that means besides I can't change the text components.

leaden ice
#

is the sample using UGUI, or is it using IMGUI?

leaden ice
#

it's talking about where you "type" the new binding into

echo plaza
leaden ice
#

change it everywhere you see Text to TMP_Text

#

and change all the objects in the scene to TextMeshPro-UI objects

#

none of this has anything to do with input fields (which is what that known limitation is talking about)

leaden ice
# echo plaza :|

yes you need to change that variable (m_actionLabel) to TMP_Text too

echo plaza
#

Maybe this is what I'm missing:

leaden ice
#

yes

#

see how it says Text

#

you must change it to TMP_Text

echo plaza
#

It was at the very bottom of the page and I didn't notice it.

leaden ice
# echo plaza :|

the error here was telling you the variable was the wrong type. That's your cue to go to the variable declaration

echo plaza
leaden ice
cobalt flint
#

I'm trying to capture specifically a "rotational" input, with the example of Spin the input in a circle to simulate a fishing rod reel. Anyone got any ideas here? Or previous examples? I've been pondering this idea for a few days now. No idea where to even start.

leaden ice
cobalt flint
#

Mobile

leaden ice
#

So you mean a touchscreen?

cobalt flint
#

Well yes, the input capture isn't as important, but the method I would handle capturing a continued rotation?

leaden ice
#

Are we talking about a virtual joystick, or are we talking about rotating your finger around the center of the screen, or what?

#

well it depends on the input device hence the question

cobalt flint
#

I think for simplicity, a virtual joystick as that is what it currently uses

reef garnet
#

Hi I have an eventManager that keeps throwing a NullReferenceException and I'm not sure why

Event Manager Here:

{
    // Bus Events
    public Action OnBusTakeDamage;
    public Action<float> BusTemperature;
    public Action<float> BusHealth;

    // Debris Events
    public Action OnDebrisDestroyed;
    public Action OnDebrisSpawned;

    // Hero Events
    public Action OnHeroShoot;
    public Action OnHeroDash;

    // Game Events
    public Action OnGameStart;
    public Action OnGameWon;
    public Action OnGameOver;
    public Action OnGamePaused;

    protected override void Awake()
    {
        base.Awake();
    }
}```

Inhereits from my Singleton Abstract Class
```// A static instance is similar to a singleton but does not destroy any new instances,
// Instead overwriting the current existing instance.
// Good for resetting states.
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance { get; private set; }
    protected virtual void Awake() => Instance = this as T;

    protected virtual void OnApplicationQuit()
    {
        Instance = null;
        Destroy(gameObject);
    }
}

// A Basic Singleton. Will destroy any new instances created.
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        if (Instance != null) 
        {
            Destroy(gameObject);
            return;
        }

        base.Awake();
    }
}```

NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/_Scripts/Managers/GameManager.cs:32)

```private void Start() 
    {
        EventManager.Instance.OnGameStart.Invoke(); // THIS IS LINE 32
        
        SetValues();
        
        fallHeight = Vector3.Distance(startTrasform.position, endTransform.position);

        currentHeight = fallHeight;
    }```
leaden ice
leaden ice
cobalt flint
leaden ice
#

and of course if you want to know the rate per second it'd be:

float angleDiff = Vector2.SignedAngle(previousInputVector, currentInputVector);
float rotationRate = angleDiff / Time.deltaTime; // in degrees per second
#

so you'd either accumulate these angle difference over time or look at the rate of change.. It depends what you're looking for

cobalt flint
#

I believe the rate of change is what I'm after, as that will correspond with a counter.

reef garnet
leaden ice
#

right but it was not clear which file was GameManager.cs and which line 32 was

cobalt gyro
#

Can Coroutines be used in a static non-MonoBehaviour script

leaden ice
cobalt gyro
reef garnet
wide terrace
leaden ice
reef garnet
#

oh ok Well that explains things

#

Thanks

leaden ice
#

assuming it was the no listeners thing

reef garnet
#

Not at the moment no. Thanks for the solution

#

@leaden ice @wide terrace Thanks that fixed it I totally forgot about checking for null

hollow hound
#

What is the best way to manage ui events like button onClicks?
Dragging files in unity events seems very tedious and unreliable.
With GetComponenting buttons from script of the same object it is impossible to subscribe for multiple butttons

leaden ice
#

I prefer to assign the listeners in the editor whenever possible

hollow hound
leaden ice
hollow hound
leaden ice
#

there would be no point in doing that since you can just assign StartGame to the button from the inspector

#

but sure you could do that

hollow hound
#

Then what you meant by "you can add subscribers from code if you really want with AddListener"?
Dragging scripts into unity events seems unreliable and I wonder if it would be better to subscribe to events in code

leaden ice
#

the most common case for adding subscribers in code is when you're instantiating button prefabs and want to add a listener from the instantiating script to the button instances

hollow hound
#

So the best ptractice for managing ui events for static elements is configuring them through inspectpor like this?

leaden ice
#

I would say so, yes.

#

it keeps your code hierarchy-agnostic

#

which allows more code reuse

hollow hound
#

But it breaks if I simply rename my function

leaden ice
#

sure and the other way breaks if you simply rearrange your hierarchy

hollow hound
#

Hierarchy? I attached script to the button it subscribes to.
If I'm draging script from folder to event field, there is no functions to select.

leaden ice
#

the arrangement of GameObjects and their components

#

if you, say, move the script to a different object, or move the Button component to a different object, it breaks

hollow hound
#

But I can Require the button component, right?

leaden ice
#

Sure

#

Which, again, locks you into a particular hiararchy configuration

#

if you're fine with that then go for it

hollow hound
#

Ok, thanks

mighty plinth
#

hey! i was wondering if someone could help me with a maths related coding problem?

im trying to spread out a hand of card gameobjects in unity, like in the pic, but cant seem to find much help online, and am unable to nudge chatgpt into providing a workable answer

maybe you could do some circle related magic? youd position a card on the circles edge depending on your hand size / its location in hand, and have its transform.up equal to the normal of the edge at that cards position, giving you both the rotational and y-positional effect in one swoop? as a non mathsy person ive got no idea where to even begin with this though

in case it helps at all the second pic is my current solution to positioning the cards on their x axis. thanks :)

hollow hound
mighty plinth
echo plaza
#

Hey there again, I'm having a problem with the Input System rebinding where it only works in one scene and not in any others. I'm not sure what the problem could be, but it happens with the actual key rebinding since every type of rebinding script I used had this problem.

mighty plinth
#

i might be able to fix that actually 1 sec

hollow hound
#

Seems like you should rotate cards vertically

mighty plinth
#

so now as i add more cards they move downwards and to the right lol (also the rotations gone)

#

quaternions arent my strong suit

heady iris
#

to get a "spread" like that, you want stack all of the cards on top of each other, then use transform.RotateAround to rotate them slightly around a far-away position

#

that'll get the arc shape

fluid lily
#

So question on Unity serialization and nested classes. I have a component with an instance of a class that has its own class as a variable. Only the top level instance of the class is showing in inspector. How would I have it so I can have it serialize another step down at will?

nova moon
opaque vault
#

uhh. I dont know why my sprite is clipping through

#

ello?

nova moon
#

Hi

fluid lily
#

value is showing up, but not next

#

Also getting this in logs XD
Serialization depth limit 10 exceeded at 'IsAHasA.next'. There may be an object composition cycle in one or more of your serialized classes.

nova moon
fluid lily
#

If I make next an array I can get one more layer, but it is cutting it off pre-emptavly.

fluid lily
#

I thought array would work(which it does once), as Unity doesn't auto generate values there

nova moon
limber agate
fluid lily
wintry crescent
#

Hi, this is how my FBX object looks in the editor. How can I create a reference field in which I can put the root object, instead of specifically to the mesh and only the mesh? I'd love to have the reference to the mesh and the materials in one go

rigid island
#

it has acess to all that

#

if you want the mesh itself you do need mesh filter

wintry crescent
# rigid island reference the mesh renderer

yea but I need specifically the reference to the file, because I'm swapping the mesh and the materials on it, with a script.
And that script needs references to all that.

wintry crescent
# rigid island reference the mesh renderer

I should be more precise: this isn't hierarchy window, this is the Project window. I need to reference the object in the project window. Not some mesh renderer that has this mesh and materials attached.

rigid island
#

maybe resource folder?

wintry crescent
#

No, I need to make a field in the inspector on a gameobject, where I can drag this root object

#

I'm asking what type the field should be - if I do a mesh field in my script, I can drag the mesh itself, not the root object that holds the mesh and the materials

wintry crescent
# rigid island GameObject

Thanks, I can assign it now. But I'm confused, how can I get the mesh and material now, from that gameobject? Does that gameobject have a mesh filter now, or something?

rigid island
#

I recommend you just make a prefab that has all that setup already

wintry crescent
#

if I destroy and recreate that object, those references would become null. If I disable/enable objects, those scripts won't work. Hence I need to alter the mesh filter on those objects directly.

orchid surge
#

Working on a 3D game with a ton of hand placed enemies. To help with hand placement, I want to be able to see the various enemy models standing where I placed them in scene view. So simply dragging enemy prefabs in would be nice. But because there are so many, I think it will be important to pool and spawn them. So I can't just drop prefabs in. Any advice on this issue?

I have two ideas. Either I make a spawner that uses graphics.draw to preview what I placed, or I can place prefabs in and they can zorch themselves and leave behind spawn points when the game starts. Neither sound that great, so I'd appreciate some outside perspective.

spark spire
#

I'm looking for some insight or resources about world state systems and how they implement catching up a default state to a desired state.

modern creek
# spark spire I'm looking for some insight or resources about world state systems and how they...

I use a state system for my turn based battle game (I can provide a steam/google link if you want). Basically there's a state object that has the "true" state, and a list of battle actions that modify the state as the turns come in over the network. There's also some pretty deep equality checking and the ability for the server to send the "post" state in addition to all the change events for debugging help.

Any time a new turn comes in, I also copy the "true" state into a before state that can be modified by the turns slowly (ie, to allow animations to happen and not need to worry about things like showing the hit points before the attack has finished).

Not sure what specifically you're looking for, but hopefully that's useful?

spark spire
#

It it, i think the bit im missing out on is a state having entry and exit data, which is closer to a state machine than my simpler style of just a dictionary of state names and a boolean if its done

smoky pike
#

https://paste.ofcode.org/zn8wz4aJp9PY3bSkvw7sh4
In my game, dots instantiate on a screen, and you have to click them in the order they came in and avoid clicking the bad dots.

Problem: The error is in the randomizeArray() function which randomizes the "dots" array to ensure that the dots instantiate in a random order. It's saying that the dots[i].name is invalid for some reason

somber nacelle
#

what is the actual error you are receiving

somber nacelle
#

well those line numbers don't line up with the code you've shown. but a null reference exception means that the entry in the array is likely null if it isn't throwing when you access the Length property of the array

somber nacelle
#

just breezed on past the rest of that message that told you the issue then, eh?

smoky pike
#

the content of the array are dots(sprites) that are not in the scene. I instantiate those dots in the scene, and then destroy them whenever the user presses on the dots .

somber nacelle
#

seems like one or more of your colored dots variables are not set in the inspector. also why not just populate the array directly in the inspector instead of these separate variables?

#

i also feel like i've given you this advice before . . .

leaden ice
somber nacelle
smoky pike
somber nacelle
#

pretty sure you said that last time

smoky pike
somber nacelle
somber nacelle
#

take that code i gave you last time and add it in again and show me what it prints. again.

smoky pike
#

ok

somber nacelle
#

actually wait, let me modify it a bit real quick to make it nice and obvious for you

#
for(var i = 0; i < dots.Length; i++)
{
  Debug.Assert(dots[i] != null, $"Array entry is null at index {i} on {name} - {GetInstanceID()}", gameObject);
}

put this in Start before you call that randomize method or even at the beginning of the randomize method, either option is fine

leaden ice
#

Add a log before the loop and print the length

somber nacelle
somber nacelle
#

do you perhaps have some extra line of code somewhere (or even a blank line) in your code editor that is not being included in the code you pasted in the site? because it seems your line numbers are off by 1 from what you indicated before. also please use the updated code that i provided that will print the name and instance ID of the object.
you should also move it directly above that loop where your error is happening

smoky pike
quartz folio
#

Presumably you destroy some "bad dots" and then keep trying to use them, causing an NRE when you read the name.

smoky pike
#

even though Destroy the "bad dots", they still appear on screen for some reason

somber nacelle
#

the array is filled with the prefabs not the instances that were spawned in the scene. you don't even bother storing references to the instantiated objects

swift falcon
#

man. trying to make an fps controller is making me feel extremely stupid

#

i'm on the verge of just following some shitty yt tutorial since doing it myself is just resulting in headaches

rigid island
#

Anyone familiar with the new Splines know how to get the nearest point on the spline itself based on a certain position? Not sure what I'm doing wrong

As you see from video, the Utility function they provide does seem to follow the spline but the offset seems really off?

btw their function is using float3 from UnityMathematics
Here is the utility function I'm using
https://docs.unity3d.com/Packages/com.unity.splines@2.2/api/UnityEngine.Splines.SplineUtility.html

My code

 void Update()
    {
        SplineUtility.GetNearestPoint(spline.Spline, transform.position, out float3 xyz, out float t, 3,2);
        nearestPoint = new Vector3(xyz.x, xyz.y, xyz.z);
        Debug.Log($"x: {xyz.x} y: {xyz.y} z: {xyz.z}"); Debug.Log("t: " + t);
    }

    private void OnDrawGizmos()
    {
        if (Application.isPlaying)
        {
            Gizmos.color = colorDebug;
            Gizmos.DrawSphere(nearestPoint, 0.2f);
        }
    }

night sparrow
#

is there any easy way to find all gameobjects in an area? ( not colliders, gameobjects whose origin is inside said area )

quartz folio
rigid island
quartz folio
#

transform.TransformPoint and transform.InverseTransformPoint

rigid island
#

I will try this, would this go on the In V3 or the xyz result

quartz folio
#
splineTransform.InverseTransformPoint(worldSpacePoint) // get the query point in local space of the spline, used in SplineUtility.GetNearestPoint
splineTransform.TransformPoint(result) // get the result in world-space.
rigid island
keen solstice
#

I have a slight problem, I have a scriptable object that displays text, and the PC's name on top of the text box.

Is there a way to, on a mouseclick on the scriptble object, cause the UI textbox to pop up and the text to play, then close the window?

leaden ice
#

Look into IPointerClickHandler or the EventTrigger component

keen solstice
#

thanks

#

Also, are there any tutorials on developing a save point system?

#

Where you can only save on the correct savepoint?

spare dove
#

Are you supposed to be able to just remember how your code works, even as it gets larger and larger? I find myself having to reread my own code to remember function names etc all the time

lean sail
narrow wolf
#

Been suffering from 2 days while trying to make jump buffer and Hold jump to jump higher work together... But it doesn't.

#

What a pain

#

Trying to get jump similar in Hollow Knight

swift falcon
#

hi. i’m trying to conceptually break down the fundamental requirements for a fps controller instead of just throwing it together. i would appreciate if anyone could point out any glaring flaws in my logic here :3

-gravity - subtract from the character collider’s y velocity (applied in world space) up to a limit (terminal velocity)
-ground check - cast a short ray from the bottom of the capsule to slightly below it. this should hopefully mean it can tell when it is grounded. when grounded, set y velocity to -1 so it stays on the ground
-velocity - have this be a vector2 that’s applied in local space to the transform’s x and z components in FixedUpdate (y vel is separate since it should be applied in world space i think.)
-velocity decay - on the ground your velocity should decrease quickly (possibly exponentially according to your speed) which would serve as a movement speed cap
-input - saved in Update and added to the player’s velocity in FixedUpdate to ensure it gets processed asap
-jump - if grounded, set y velocity to 10 and give a small window where y velocitu cannot be set to 0 (seems to not let you jump and overrides the jump velocity otherwise)

wall and ground collisions seem to be handled by the character collider so i think that should be everything i need :)

#

this has been giving me headaches for a while so i decided to step back and consider it as a whole

swift falcon
mystic yoke
# spare dove Are you supposed to be able to just remember how your code works, even as it get...

As you get more comfortable, patterns emerge that make it easier to keep track of more of what's going on. You can also learn to write code in a manner that is easier to understand when you read it again.

Commenting is also useful but ideally should convey intent or explain architectural decisions rather than describe what each line of code is doing. The code can speak for itself if you write it to be easy to read.

night sparrow
#

how can i get the real rotation of an object?
( say his parent is rotated to 30, the object itself is -10 then i want 20)

night sparrow
#

it calculates parent rotation?

#

or at least gives me the correct rotation?

mystic yoke
#

.rotation is the global rotation

night sparrow
#

oh cool, thought it's relative

mystic yoke
#

localRotation is the local rotation

night sparrow
#

thanks1

mystic yoke
#

Np

vocal fulcrum
#

hey, can you read the tEXt chunk of a png file at runtime?

mossy snow
#

why wouldn't you? the file format is pretty straightforward

dense vessel
#

Hello!
I generated a mesh with square faces (like in Minecraft) at runtime.
The mesh has a mesh collider and the player has a mesh collider and a cylinder mesh.
My problem is when I walk against walls, it does something weird, as if the player was slightly going inside the collider and then getting expelled.

I'm quite new to 3D and physics in Unity so I have no idea what could be causing this and how to fix it 😦

#

I also tried with a box collider for the player and it was even worse : the player was getting stuck when walking against walls.

night sparrow
# dense vessel Hello! I generated a mesh with square faces (like in Minecraft) at runtime. The ...

there are a couple of causes that can be the reason for your problem. Since i don't have enough info to help you i'll list some of them:

  1. Your player's collider may be uneven.
  2. your movement system needs an overhaul - this may be the real cause behind your player getting stuck on box colliders
  3. you are trying to push yourself into the geometry, which causes unity to pull you back (movement system again)
  4. you are using physics based movement and didn't account for friction
dense vessel
# night sparrow there are a couple of causes that can be the reason for your problem. Since i do...

Thank you!
For the movements I set the rigidbody velocity so the player is "pushed" into the walls I guess, could this be the problem?

private void FixedUpdate()
{
    float x = 0;
    float z = 0;
    if (Input.GetKey(KeyCode.W)) z += 1;
    if (Input.GetKey(KeyCode.A)) x -= 1;
    if (Input.GetKey(KeyCode.S)) z -= 1;
    if (Input.GetKey(KeyCode.D)) x += 1;
    rb.velocity = z * 8 * transform.forward + x * 8 * transform.right;
}

But I don't really see what else to do, shouldn't the collision system prevent any movement into the wall (instead of allowing it and then pushing the player back) 🤔

#

Also I set friction to 0 for both colliders

#

And for the player collider I simply used the default cylinder mesh and a mesh collider

night sparrow
#

the main problem is that you're setting the velocity and then entrusting unity to handle the rest, this will cause some major problems, especially later on when you want to implement slopes.

My suggestion is that you take a look at a couple of open source movement systems to learn from them. As to why this is happening. In unity's eyes, you clipped into a wall with a specific vector, after a physics update. It pushes you back to where you should've impacted the wall, in box collider, it happens to be where you were but slightly forward (resulting in you almost staying in place). For mesh collider, since it isn't a perfect wall, you get the bouncing motion.

As for a quick fix, you should check first if you're going to clip a wall, and if yes. You should cancel that vector.

dense vessel
#

But basically that's the same as recreating a collision system 😭

idle saddle
#

i have an UI Image (a world map). I want to move another object when the player moves through the world.
I have a relative world spaced position to the top left corner of the map, but as the UI anchor coordinates aren't translating to world coordinates 1:1 I somehow need to calculate a conversion ratio. I have no idea how though... I tried using referencePixelsPerUnit along with the images pixels per unit, but its still off

#

currently doing:

var camPos = (Vector2) UnityEngine.Camera.main!.transform.position;
_rectTransform.anchoredPosition = (camPos - _mapCorner) * (canvas.referencePixelsPerUnit/pixelsPerUnit);
peak halo
#

Hey, hope y'all are doing great. I got a problem that I am struggling to come up with an approach to.

So basically, I am making a strategy game where the player will be controlling their pawns from above and there will be these NPCs that will fundamentally do the same things involving combat. Most of these are irrelevent though. So I am trying to come up with a system that can give me points in my procedurally generated map that are good points to take cover in a combat. (mostly props stitched together. So not a procedural terrain.) In the case of the player's pawns, I just want them to check if their current position is a cover to play a specific animation and maybe crouch. But for the NPCs, I will need to find these points from scratch and send them there.

So I came up with several approaches that didn't exactly satisfy my needs so I did a little research and saw this video: https://www.youtube.com/watch?v=t9e2XBQY4Og

This is exactly what I need but unfortunately I am using the AStar Path-Finding Project (https://arongranberg.com/astar/) and to be honest, I didn't really understand how this approach fundamentally works. I tried going over the code, watching the video at 0.5x. But no, I do not seem to understand, I don't know if I just lack some key information here or if the video is actually hard to understand but when I tried to slowly review the code myself and just get how it works then do it myself a little differently, I still don't understand much because of the lack of documentation.

Has anyone tried achieving something like this or knows the fundamentals of a system like this? I have several years of experience so not a total beginner but there are just some things that I don't get about this. I just need the fundamentals of this then I'll code it myself to fit my case.

Thanks a lot!

Learn how to make NavMeshAgents find valid cover spots from another target object. In this video we'll specifically use a Player, but this can be applied to hide from any object - a grenade for example. Together we'll create a configurable script that allows us to refine which objects are valid to hide behind, and exclude those that are not.

W...

▶ Play video
vagrant blade
#

@waxen spruce !collab

tawny elkBOT
hollow hound
#

I spawn Player in Awake. Objects that are dependent from player initialising in Awake too. Like:

public void Awake()
{
   _weaponsController = ReferenceManager.Player.GetComponent<PlayerWeaponsController>();
} 

I can't do this initialisation in start, because I have events I want subscribe to in OnEnable:

public void OnEnable()
{
    _weaponsController.onWeaponChange += HandleWeaponChange;
}

So I'm getting null reference errors because some objects trying to access player before it is spawn.
How can I resolve this issue?

#

I can move initialisation to start, move subscriptions to start with the check for enabled and isSubscribedForX flag. And then add another subscription in Enable that checks for null on target and checks isSubscribedForX before subscription.
But I'm sure there is a better solution for such common flow.

ashen yoke
#

that is the solution you are not supposed to use Awake for accessing external objects

waxen spruce
ashen yoke
#

Awake/Start are not just methods they are part of phased initialization, first phase will call Awake on all objects, second phase will call Start

#

within a phase there is no guarantee of order

#

unless you fiddle with SEO

hollow hound
ashen yoke
#

OnEnable happens after awake right before Start, should be fine

hollow hound
ashen yoke
#

pretty much

mossy shard
#

i simply set the destination of my ai (im talking about enemies) based on the agro

#

i do agro by a radius check

ashen yoke
mossy shard
#

and i block the radius on the point it detects collision with anything rather than player

ashen yoke
#

but it means from now on you are relying on manually setting your whole architecture in SEO and maintaining it there

mossy shard
#

and if i block for an estimate amount of time the enemy losses me

#

@peak halo hopefully i helped

#

i didn't neceserally played with the A* i played with the way it gets it's targets

hollow hound
hollow hound
#

Thanks. I'll try to avoid that and change where I am accessing objects.

normal hedge
#

I am having an issue, wherin I have a Canvas that holds a game over screen, and is disabled by default. It has a button that reloads the scene. However, afterwards when the screen is needed a second time, it just throws a MissingReferenceException instead. I have looked around the internet, and the solution I found there was to mark it as DontDestroyOnLoad - but when I did that, the Canvas got duplicated on Scene Reload (and is not hidden). Is there a way to fix this?

The class responsible for showing the Canvas:

public class GameEndBehavior : MonoBehaviour
{
    [SerializeField] private Canvas gameEndCanvas;
    
    void Start()
    {
        PlayerHealthBehavior.OnPlayerDeath += OnPlayerDeath;
        DontDestroyOnLoad(gameEndCanvas);
        Utils.SetVisibilityRecursivly(gameEndCanvas.transform,false);
    }

    private void OnPlayerDeath()
    {
        Utils.SetVisibilityRecursivly(gameEndCanvas.transform,true);
    }

    public void OnGameRetry()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}```
PlayerHealthBehavior:
```csharp
public class PlayerHealthBehavior : HealthBehavior
{
    public delegate void PlayerDeath();
    public static event PlayerDeath OnPlayerDeath;
    public override void OnDeath()
    {
        Utils.SetVisibilityRecursivly(transform,false);
        OnPlayerDeath?.Invoke();
    }
}```
Utils:
```csharp
public static void SetVisibilityRecursivly(Transform transform, bool visible)
    {
        foreach (Transform child in transform) SetVisibilityRecursivly(child, visible);
        transform.gameObject.SetActive(visible);
    }```
hard viper
#

Q: how expensive are unity’s collision checks? Does the CPU time scale quadratically with the total colliders in scene at once? Or is unity smarter than that?

ashen yoke
#

100 rigidbodies piled up will result in combinatorial explosion for the solver

#

100 in sleep state far apart wont participate in any solving at all

hard viper
#

interesting. is there an article in documentation or something?

ashen yoke
#

physx docs

hard viper
#

could you help guide me a bit more to the right spot? googling unity physx just sends me to a bunch of wrong places

#

is it in the normal documentation database?

hard viper
#

so PhysX is not a Unity/C# thing, but a system thing?

ashen yoke
#

physx is a library by nvidia

#

unity integrated it into its component model

hard viper
#

gotcha

ashen yoke
#

you use components as a intermediate interface

peak halo
hard viper
#

I will read that document to educate myself. ty for helping

leaden ice
#

Look up OctTrees

#

And KD trees

#

And BVH

#

It's using some or all of these optimizations

hard viper
#

ok. also if I understand cache’s explanation, let’s say I have a tilemap. That tilemap has a bunch of masses of ground tiles in one layer.

  1. Composite collider groups areas.
  2. Every tile gets a separate box collider (very dumb).
    If I understand properly, Unity will not take a performance hit by switching from 1 to 2. Is this accurate?
cobalt gyro
#

if a raycast is spawned inside of a collider will it return that collider as well

ashen yoke
#

rigidbodies are what impact performance, when 2+ rigidbodies touch they form a local group which is using a solver to resolve collisions

leaden ice
#

The distribution of boxes and objects that might collide with them may also be relevant

hard viper
#

I’m assuming memory is free. Just thinking about CPU time

ashen yoke
#

the more rigidbodies are interacting within that group the bigger the perfromance impact, depending on how much time it takes the solver to stabilize the whole group

leaden ice
#

But management of memory takes CPU time

#

They're never totally independent

ashen yoke
#

so if you have a tall box filled with spheres which is near impossible to stabilize you will bring your game to a crawl

#

and there yes it grows non linearly

mossy shard
hard viper
steady moat
mossy shard
#

furthermore i can get the object itself as a transform, rb and it's tag

ashen yoke
#

i cant say exact complexity, i dont think it is clearly defined

mossy shard
#

if it's let's say an obstacle i prevent the radius detecting past it and in it

hard viper
#

well, let’s say I have a jar of jelly beans, like you described. The cost of the jar would be more like ~rigidbody^2 in the jar, and not ~collider^2 in the jar

#

so if I had a jar of jelly beans and all the beans are colliders, then we are totally ok. But slowly changing jelly beans to rigid bodies is what will quickly raise the cost.
Would that be accurate?

steady moat
ashen yoke
#

yes, static moving colliders also have a small cost but if its static its one less object for the solver to iterate on

#

they still produce contacts but for the rigidbodies

vernal plank
#

So can you change the texture of an HDRP material in unity with C# ?

#

its working for normal material

vernal plank
#

can i show my code and ask for what am doing wrong then @rigid island ?

mossy shard
#

i used the term agro because i specifed that i do this for my enemies

hard viper
#

Follow up question: Let’s say we have a jar of jellybeans. Every bean is a rigidbody with 1 sphere collider.
Would giving every jelly bean a second sphere collider quadruple the total cost per frame?

vernal plank
#
using UnityEditor;
using UnityEngine;
using System.IO;



public class AssetDatabaseExamplesTest : MonoBehaviour
{
    [MenuItem("AssetDatabase/printmat")]
    static void SubFolderExample()
    {
        var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
        string foldvar = folders[3];
        string[] files =  Directory.GetFiles(foldvar+"/", "*.png", SearchOption.TopDirectoryOnly);
        string wellyay = files[0];

        string materialPath = "Assets/Silex-Materials_Pack/Materials/test/Mat_test.mat";


        string texturetest = "Assets/Test/bltest-1.png";
        Texture2D extexture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturetest, typeof(Texture2D));
        // Debug.Log(extexture);

        Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
        // Debug.Log(material);
        material.SetTexture("_MainTex", extexture);
        // Debug.Log(extexture);
        EditorUtility.SetDirty(material);
        // AssetDatabase.GetAllAssetPaths()
    }
}

mossy shard
#

since my NPCS are literally just talking statues or walking from point A to point B rarely

vernal plank
#

material.GetTexture("_MainTex"); did return the proper value

#

also Texture2D extextur is returning the proper value

#

but material.SetTexture("_MainTex", extexture); is not returning or showing any error also not working

#

note for non HDRP material it did work

#

and if unity version matter its 2020

ashen yoke
# hard viper Follow up question: Let’s say we have a jar of jellybeans. Every bean is a rigid...

probably not, it depends on how many contacts were produced, both single and 2 spheres can produce roughly the same amount of contacts, but what can affect performance the most is the shape,
think of it as the classic fitting problem, how many things you can fit in an enclosed space, when you do that example you are asking the solver to resolve this, and it can result in a very long or infinite amount of work,
every iteration every object in the jar is offset by a little, in an attempt to separate them, in case of a single sphere it can be relatively easy, in case of 2 the amount of possible positions they can be in can become astronomical

#

so its not about the amount of colliders its about the shape

#

problem also arises from the iterative nature of it, for example solver does 5 iterations in an attempt to move the object away from any contacts, since the object is sandwiched between bunch of others, it still ends up overlapping, so it has to be processed again next frame

#

object will stop being processed when its found a stable position, it switches into sleep mode

hard viper
#

I see. So if the jar of jellybeans is left completely undisturbed, and if the solver ever gets the beans to all have zero speed, then framerate will go back up

#

But if the shape sucks, that second “if” is unlikely to happen (quickly if ever)

ashen yoke
#

possibly, there can be some fallback code that breaks out of it even if its not solved

hard viper
#

ty for taking time to explain. I think I get it now. I will read more of that documentation to learn

hollow hound
#

I have:

        void Awake()
        {
            Debug.Log("spawn");
        }

And in another component:

        public void OnEnable()
        {
            Debug.Log("access");
        }

Both components exist in the scene, they are not spawn after game start.
Logs looking like this:

#

Why Awake is called later then onEnable?

steady moat
#

You might want to use Start instead of OnEnable.

#

However, this is not good practice

#

You should make your dependence explicit and not implicit.

hollow hound
hollow hound
steady moat
#

It kinda hard to know what is the best in your situation as there is multiple factor.

hollow hound
steady moat
#

You can also get an explicit reference through a Singleton. MyObject.Instance

hollow hound
steady moat
#

It requires something to hold the current player.

#

That can be a static (Which is not recommanded) or a GameManager script of the sort.

hollow hound
#

Why static classes for such things is not recommended?

thin aurora
#

For example, there is no way to pass dependencies to static methods

steady moat
thin aurora
#

A better way to create a "static" context is to make a singleton

hollow hound
#

Thanks

hollow hound
digital coyote
#

i am trying to make leaning like in rainbow six siege and it works kinda but when i rotate the camera it leans in to wrong places and has the wrong rotation. can someone pls help

private void Awake()
    {
        motor = GetComponent<PlayerMotor>();
        onFoot = new PlayerInput().OnFoot;

        headPosition = camHolder.transform.localPosition;
    }

    private void Update()
    {
        //Debug.Log(isFreeLook);
        camYRot = cam.transform.localRotation.y;
        cam.transform.position = camHolder.transform.position;
    }



public void LeanStop()
    {
        leanAngle = 0f;
        isLeaning = false;
        leanDistance = 0f;
        Debug.Log(isLeaning);
    }

    public void LeanLeft()
    {
        leanAngle = maxLeanRotation;
        leanDistance = -maxLeanDistance;
        isLeaning = true;
        Debug.Log(isLeaning);
    }

    public void LeanRight()
    {
        leanAngle = -maxLeanRotation;
        leanDistance = maxLeanDistance;
        isLeaning = true;
        Debug.Log(isLeaning);
    }

    public void ProcessLean()
    {
        if(isLeaning)
        {
            Quaternion leanRotation = Quaternion.Euler(cam.transform.localRotation.eulerAngles.x,cam.transform.localRotation.eulerAngles.y,leanAngle);
            cam.transform.localRotation = Quaternion.Lerp(cam.transform.localRotation,leanRotation,leanTime);

            Vector3 cameraOffset = cam.transform.right * leanDistance;
            Vector3 adjustedCameraOffset = Quaternion.Euler(0f,player.transform.eulerAngles.y,0f) * cameraOffset;
            Vector3 targetPosition = headPosition + adjustedCameraOffset;
            camHolder.transform.localPosition = Vector3.Lerp(camHolder.transform.localPosition,targetPosition,leanTime);
        }
        else
        {
            Quaternion leanRotation = Quaternion.Euler(cam.transform.localRotation.eulerAngles.x,cam.transform.localRotation.eulerAngles.y,0f);
            cam.transform.localRotation = Quaternion.Lerp(cam.transform.localRotation,leanRotation,leanTime);

            camHolder.transform.localPosition = Vector3.Lerp(camHolder.transform.localPosition,headPosition,leanTime);
        }
    }
leaden ice
vernal plank
#

@rigid island hey i dont wanna take much of your time but you said yeas about changing HDRP with unity i found out in the docs there is HDMaterial unity 2020 didnt recognize it, can you point out for me what am missing ?

#

btw i shared the old code above

normal hedge
#

is there a event that fires after Start?

leaden ice
normal hedge
#

I need to build a node graph (for a perk system) - and to build the graph I need to be sure all nodes exist, so I wanted to create a seperate class handling all the graph building, but that would need to happen after the rest of the nodes all exist - hence me looking for something after start. (The nodes would be already in the scene, and no new nodes would come to exist while running).

leaden ice
#

or do this somewhre

void Start() {
  CreateNodes();
  BuildGraph();
}```
digital coyote
leaden ice
#

it's part of a quaternion

normal hedge
leaden ice
#

not the rotation around the y axis

digital coyote
sterile linden
#

Yo! Trying to store my spline data somehow so it's reachable within jobs. Is there any easy way to do that? I just want to evaluate a point along the spline to set a position

peak halo
leaden ice
steady moat
sterile linden
peak halo
leaden ice
#

Assuming you're talking about Unity's spline package

sterile linden
leaden ice
#

or how easy to sample that is

#

I've always just found it easier to use the M4x4s

peak halo
normal hedge
sterile linden
tropic quartz
# normal hedge I hope its not too early bring this down, but does anyone have suggestions regar...

Basically, normally when you load a scene all the stuff in the old one is destroyed.
What "DontDestroyOnLoad" does is it prevents it from being destroyed, so you end up with a double since you are loading the same scene and not destroying the version you had in the old one.

You could use a singleton pattern to prevent the double.

I think there might be something funky going on with the statics here?
Static variables and methods are shared between all instances of the same class so maybe something stays from the "old" scene and doesn't get updated for the new one.

Or it could be a timing issue.
Maybe something is trying to get a reference from it while it's still disabled.

normal hedge
#

I would have expected DontDetroyOnLoad to be smart enough to stop the duping issue - welp.
How would a singleton prevent this problem?
The static stuff - how would I transfer an event without having it static?

tropic quartz
#

Singleton pattern is basically just a system that makes sure you only ever have 1 copy of something in a scene.
I like throwing it on things liek music players along with Don'tDestroyOnLoad to keep music playing between scenes without having duplicate music players.

#

I'm not entirely sure if it has some weird interactions with events though.

ashen yoke
#

most likely you are just not clearing events

#

consequtive invocation raises dangling delegate referencing dead object

normal hedge
#

so, when I load the screen, I unsubscribe from the event?

ashen yoke
#

whatever subscribes should unsub

#

OnEnable/OnDisable

#

or OnDestroy

night sparrow
#

anyone knows a vs code extension that automatically generates documentation like this?

#

i hate xml documentation

normal hedge
tropic quartz
#

.cache knows way more about code stuff than I do, he's probably right. I dunno that much about events, but seems you have static events yea.

night sparrow
eager yacht
# night sparrow i hate xml documentation

Well the xml doc is there for a reason. IDEs and text editors with intellisense support use it to actually give you information when you hover over something, or when going through quick actions. Not using it is very weird.

night sparrow
ashen yoke
night sparrow
ashen yoke
#

hm doxygen supports c# out of the box

stoic ingot
#

Is there a way to use OnButtonClicked for all interactable Buttons of a Canvas? As in, I got 4 buttons and want the same thing to happen, no matter which Button you press atwhatcost

night sparrow
ashen yoke
fervent furnace
#

find all buttons on canvas and add listener?

#

maybe there are better ways to do this

eager yacht
night sparrow
stoic ingot
eager yacht
fervent furnace
#

find object of type

ashen yoke
#

if you only have same button behavior everywhere, i guess you can just GetComponentsInChildren<Button>

night sparrow
ashen yoke
ashen yoke
#

i.e. while editing you get raw xml view, while not editing you get it formatted for display

eager yacht
#

Then yeah, it's probably just taking the existing xml and converting it to that. Since that format won't give intellisense hints in VS or Rider. Just tested with VSCode too and it doesn't get any info from that type of structure either.

night sparrow
eager yacht
#

Makes sense

night sparrow
#

but it's soo good 😦

eager yacht
#

Oh it's bascially markdown, that's why

ashen yoke
stoic ingot
#

dont know what an event bus is XD

steady moat
civic folio
#

is there a way to use an int variable as a float in calculations? Just like 1f but instead of 1 having a variable

eager yacht
#
int foo = 2;
float bar = 1f / foo; // will be converted to a float due to a float being in the operation
float bar = 1 / (float)foo; // can manually convert
leaden ice
civic folio
#

cast?

leaden ice
#

yes - as in Nom's third example above^

#

(float)foo casts the foo variable to a float.

ripe bloom
#

Accidently used a while loop in my update function and now my game is fozen! How do I stop play mode if I can't interact with the program? the bg sound plays

#

Or how do I save/recover the progress of the currently open scene?

#

nvm closed it. so sad

leaden ice
#

and throwing a breakpoint inside the loop

#

from there use your debugger's immediate execution mode tools to throw an exception or something

#

e.g. throw new Exception("blah");

#

that will break you out of the loop

#

ofc if it's in Update it'll go right back into the loop next frame - so if you can set something in the loop to null to cause exceptions that would be better

static matrix
leaden ice
#

I'm interested in throwing an exception to break out of an infinite loop

static matrix
#

if the infinite loop is with for or while you could use break

#

ohhhhh

#

odd

leaden ice
#

would break work in immediate mode in a debugger?

#

I have no idea

#

i always just throw an exception but it might work too

narrow blaze
#

I would like to enable the canvas with a click event. Without having to use "public GameObject canvas"

#

i want find the childcomponent with code

#

so i could reuse the script for other objects

#

Currently i have this

leaden ice
#

you need to assign the reference somehow

#

it depends where this script lives (which GameObject in the hierarchy?)

narrow blaze
#

The script lives in the parent component

leaden ice
#

Castle?

narrow blaze
#

yes

leaden ice
#

Then you can do like:

void Awake() {
  canvas = transform.Find("Canvas");
}```
ashen yoke
#

just use GetComponentInChildren<T>(true) ?

leaden ice
#

or transform.GetChild(1) < second child

leaden ice
narrow blaze
leaden ice
#

you should do it in Awake

ashen yoke
#

you shouldnt use OnMouseDown at all

#

its outdated legacy concept

narrow blaze
#

I want to open a ui when i click on the "castle" object. That's why i ask

leaden ice
#

get the reference in awake

#

use the reference in OnMouseDown

#

OnMouseDown is fine for now but there's a newer more flexible version of it if you're interested for later

#

it's called IPointerDownHandler

#

or IPointerClickHandler

narrow blaze
echo plaza
#

Hey there, I'm having a known issue with the Input System where if you rebind a key, it won't update the generated C# classes. One of the Unity developers said you can still use the generated C# classes, but you'll have to dynamically set the action references. I'm not sure what this means exactly and how I could go about doing this.

echo plaza
# leaden ice You just use https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/api/Uni...

I've got those two in a separate script and they work. The issue I'm having is that the rebinding only works in the main menu and not in a game. In the game it does save and show the correct key, but the player's controls stays exactly the same, until I go back to the main menu and into the game again.

Reading the person's post again, he says it works best with the Player Input (Which I'm using) or .inputactions directly. So I'm not sure what's going on.

leaden ice
#

and you're only loading the binding overrides into one of them

#

If you have a PlayerInput component - that component has its own InputActionsAsset copy

#

and so would a standalone instance of the generated C# class

#

also if you have a new scene being loaded and you are therefore discarding the PlayerInput from the previous scene, you will have to load the binding overrides again since you now have a new instance of the input actions asset

echo plaza
leaden ice
#

although I can't say I ever tried to do that at runtime. It should probably work

#

the other option is to just do cs void Start() { myPlayerInput.actions.LoadBindingOverridesFromJson(bindingsJson); }when the new PlayerInput is created

echo plaza
#

I'll try it.

chilly beacon
#

so guys i have my player movement script which was working comepletly fine and all of a sudden it doesnt move the player

using System;
using System.Collections;
using System.ComponentModel.Design;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float playerSpeed = 10.0f;
    public float playerSpeedBuff = 5.0f;

    bool isDashing = false;
    public float dashSpeed = 50.0f;
    public float dashDuration = 0.4f;
    public float dashTime = 0.0f;
    public float dashCooldown = 0.10f;

    Vector2 mousePosition;
    public Animator animator;
    public Rigidbody2D rb2d;
    public Camera cam;
    private Vector2 moveInput;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        cam = Camera.main;
    }

    void Update()
    {
        Debug.Log(Input.GetKey(KeyCode.W));
        Debug.Log(Input.GetKey(KeyCode.A));
        Debug.Log(Input.GetKey(KeyCode.S));
        Debug.Log(Input.GetKey(KeyCode.D));

        moveInput.x = Input.GetAxisRaw("Horizontal");
        moveInput.y = Input.GetAxisRaw("Vertical");

        animator.SetFloat("Horizontal", moveInput.x);
        animator.SetFloat("Vertical", moveInput.y);
        animator.SetFloat("Speed", moveInput.sqrMagnitude);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            isDashing = true;
            dashTime = dashDuration;
            rb2d.velocity = playerSpeed * moveInput.normalized;
            dashCooldown = 0.10f;
        }
    }

    void FixedUpdate()
    {

        if (isDashing)
        {
            rb2d.AddForce(dashSpeed * moveInput.normalized, ForceMode2D.Force);
            dashTime -= Time.fixedDeltaTime;
            dashCooldown -= Time.fixedDeltaTime;
        }
        else
        {
            rb2d.velocity = playerSpeed * moveInput.normalized;
        }
        if (dashTime <= 0)
        {
            isDashing = false;
            dashTime = dashDuration;
        }
    }
}```
delicate plank
#

This is my current code for a 2d game I wanna make, some1 pls help me add player rotation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
Rigidbody2D body;

float horizontal;
float vertical;

public float runSpeed = 5f;


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

// Update is called once per frame
void Update()
{
    horizontal = Input.GetAxisRaw("Horizontal");
    vertical = Input.GetAxisRaw("Vertical");
}

private void FixedUpdate()
{
    body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}

}

vague slate
#

Do MonoBehaviour's InstanceID match it's GameObject one?

delicate plank
#

how

steady moat
atomic iris
#

hi! i plan to have tons of canvas' in my game and im wondering at the performance impact of it. for reasons, the canvas' always need to remain on but i can disable the elements in the canvas. will these canvas' that dont have any active objects to render still have an impact on performance?

ashen yoke
#

if they are completely empty then no

leaden ice
ashen yoke
#

canvas is a way to optimize transform hierarchy, canvas stops update transform event propagation

#

so the more the merrier

atomic iris
#

cool, thanks for the answer!

echo plaza
#

Not sure how many people use visual scripting here, but I'd like to access its scene variables with C#. Here is a snippet of my code which almost works, besides it isn't wanting to use the Unity.VisualScripting API.

using Unity.VisualScripting;

private GameObject player = (GameObject)Variables.ActiveScene.Get("PlayerGameobject");
leaden ice
echo plaza
leaden ice
#

Just showing a red underline is not useful

echo plaza
leaden ice
#

what version of the Visual Scripting package are you using

echo plaza
#

I am using the latest one; Version 1.7.8 - May 10, 2022.

leaden ice
#

Are you seeing that error in Unity too, or only in VS?

echo plaza
#

It is also in the editor.

leaden ice
#

Seems like you're trying to edit them?

echo plaza
#

Yup.

leaden ice
#

My guess is the input system samples have an assembly definition

echo plaza
#

OH RIGHT!

leaden ice
#

(if you show the top of your VS you'll see the assembly you're in)

echo plaza
#

I had to add TextMeshPro to have it work!

#

Hmm, there doesn't appear to be an AssemblyDefinitionAsset just for Unity.VisualScripting. There are different variants like Unity.VisualScripting.Core.

leaden ice
#

Most likely core is what you want

echo plaza
#

Alrighty, it was the core one. Now I have a lot of errors, but they all explain what I need to do to fix them.

vague slate
#

Does setting rotation to AudioSource's game object make any difference at all?

modest pawn
#

Hey, any suggestions of libraries to send/receive events from a server(asp.net) ? It's not performance-critical so I just want something that works and looks clean.

half sparrow
#

Hello. I am struggling with something in Unity 2D. I am spawning some tiles (square sprite) via code in order , to form a grid 5x5 in positions x=0, y=0 to x=4 y=4. The code is

 //Initialize grid to 0 values and spawn tiles
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                int rgb;
                GameObject g_tile = new GameObject($"Tile x: {x} y: {y}");
                g_tile.transform.position = new Vector3(x, y);
                g_tile.transform.parent = gridManager.transform;
                var sRenderer = g_tile.AddComponent<SpriteRenderer>();
                sRenderer.sprite = sprTile;

                rgb = (x + y) % 2 == 0 ? 1 : 0;

                sRenderer.color = new Color(rgb, rgb, rgb);
            }
        }
    }

The Result is a grid with black and white squares. like a chess but in grid 5x5.
What i want to do?
I want to each of these tiles to have a child TextMeshPro in the center with a number (any number this is not the problem). How can i spawn TextMeshpro inside these tiles?

Ignore the apples and the owls and the beaver

soft shard
# vague slate Does setting rotation to `AudioSource`'s game object make any difference at all?

If the pivot is not centered (and its Spatial Blend is set to 3D), it could, but the audio is affected by the min and max ranges of the source, if those ranges move further from the listener due to rotation, then it could affect it - in most cases, I would imagine this wouldnt have any affect on how the sound is heard (maybe except for the doppler levels in one ear or the other, if the rotation is fast or instant)

vague slate
soft shard
vague slate
#

for 2d it seems to be irrelevant either

soft shard
#

Right, for 2D, its always played at the (headphones) level, and not from the world so the distances woulnt affect the listener

vague slate
#

oh well, g ood stuff

fast belfry
#

Is there a way to completely create and initialize animator controller inside of code?
I want to store my animation clips serialized on a weapon and on start initialize a controller and dynamically create it, with states and transitions, which are the same for all weapons.
The key goal is to avoid manually creating controllers for each weapon. Is there a good way to do this?

steady moat
ashen yoke
#

create a prefab for text, spawn that prefab

fast belfry
steady moat
#

You can also make your transition with Animator.Play instead of the Animator transition from the StateMachine.

half sparrow
leaden ice
#

check out why it's not visible

half sparrow
#

i was thinking if i could add a textmeshpro component but i get an error. For example

var tileText = g_tile.AddComponent<TextMeshProGUI>();
tileText.text = "my number";

But this does not work.

leaden ice
#

you can only have one graphic/renderer on an object