#archived-code-general

1 messages · Page 451 of 1

naive swallow
#

Is there a utility method or general easy way to get a "Sub-matrix" of a 2D array? Like, I have a 100x100 array of floats, and I want to get the 10x10 array starting at some arbitrary x,y point? I feel like there's a way to write this neatly with a Linq query but I just can't get the brain jusice flowing enough to figure out how

steady bobcat
#

Why not do it with 2 for loops yourself?

#

Sometimes it can be done with 1 for loop if its not using the 2d array syntax but depends on the range of data you need.

naive swallow
#

Yeah, that's the brute force way but I feel like there's a good way

#

And I wanted to see if anyone could come up with some obvious method I had overlooked

steady bobcat
#

If its [] instead of [,] and you want say 3 "rows" of data then it has a start and end index
else you kinda need to use 2 for loops to correctly index some xy min max range

naive swallow
#

It's an actual 2D array with [,], not an array of arrays

steady bobcat
#

no, [] is not [][]

#

[][] is an array of array pointers
[,] and [] are 1 array

naive swallow
#

Yes, one array, two dimensions. That's what I've got. Linq should work on it, but I just can't come up with a query that'll do it in one line

#

I'll just use a loop and if I have a brainwave I'll change it later

steady bobcat
#

you cant do generic stuff properly on a 2d array

scenic heron
#

Hello, Does anyone have a good yt video on a simple player controller? like moving around and looking around. ty :)

steady bobcat
#

i once experienced this issue and it pushed me to only a normal array and calculate index myself

#

int index = (y * width) + x;

late lion
#

You can save a little code and time by iterating over the y range and copying the whole x row with Array.Copy. Due to the memory layout of a multi dimensional array, there's no way to do it in one copy.

scenic heron
#

does anyone know how to fix this? i want the character to still be standing up even if it's looking down or up

hexed pecan
#

Dont rotate the player on its x axis

analog talon
#

I have a gameobject that is present on screen but I can't click on and don't see in the hierachy (the tree trunk circled in red). How do I remove it? I added this object right as the editor was reloading and it kinda bugged there. Restarting the editor didn't fix it.

outer plinth
#

Hey, I am trying to intersect the yellow sphere (defined on the GPU) with a number of rays (also defined on GPU) with the origin being the white wireframe sphere, however, I'm really struggling to understand the coordinate spaces which everything should be in, does anyone have any pointers?

currently I am intersecting the sphere, however, when I try to display the hitPoint via Gizmo the coordinate matrix is incorrect

#

"Note that camera space matches OpenGL convention: camera's forward is the negative Z axis. This is different from Unity's convention, where forward is the positive Z axis."

steady bobcat
#

Gizmos from the Gizmo class use world space, is this stuff currently done in view projection?

sharp temple
#

I fixed my character controller issue. So turns out when max step offset is a low value then the max slope angle starts glitching out

#

Lower the step offset it more it glitches/you can go on higher slopes

fiery bough
#

Yeah, idk if this is the channel for this, but..

recently i switch OS to "linux mint" and when i installed unity a tried to open a project this error shows:

mellow sigil
#

It's not the right channel but if you google the error message there are plenty of solutions

steady bobcat
#

pretty code related to me

steady bobcat
steady bobcat
#

strange. does it give more info about what tried to use it?

fiery bough
#

Oh sorry, I mean it's x64

steady bobcat
#

my only idea is its linked to a newer libssl version that you have. I've experienced annoying issues before with glibc versions ✊

steady bobcat
#

i dont know enough about linux to say tbh, i know that some distributions are behind. Ideally you want the full error if it has more information

#

ideally an error like this: /usr/lib32/libstdc++.so.6: version `GLIBCXX_3.4.29' not found

fiery bough
#

mmm, I alredy install "libssl-dev" and restart the editor but nothing

steady bobcat
#

try adding openssl and libcurl4

#

openssl has been enough for me to use libcrypto in the past (ubuntu + debian)

fiery bough
#

YEEI, NOW I HAVE ANOTHER ERROR

#

WOHO

steady bobcat
#

yay

fiery bough
#

FINALLY

#

Thanks

steady bobcat
#

np, my struggles with openssh have paid off 😆

sleek bough
#

@livid inlet This is a code channel, not for promotion or whatever this is. If you have a question then !ask a question.

tawny elkBOT
old elk
#

this isn't really a question but I'm working on the UI side of my game at the moment and just realized I accidentally implemented the MVC pattern

#

i really can't escape MVC even outside of WPF or Java 😔

old elk
#

...why the link lmao

#

i didn't say it was a bad thing

i'm just getting war flashbacks to CRUD applications

rigid island
bleak tree
#

Hi, I'm having a pretty major issue with Scene loading/unloading.
In the main menu of my game, when I load into the game, there is no issue, everything works as expected and intended, however, once inside the game, if I go back to the menu, be it by using the pause menu or by dying, the GameManager component that exists in my game scene will seemingly remain loaded, causing the pause function to break once loading back into the game

#

For some reason, it also causes the code that runs the pause menu to work twice even in the main menu, where no GameManager exists

rigid island
bleak tree
#

No it's not a DDOL

rigid island
bleak tree
#

Scene switch

#

By Game Manager component you mean inside of Unity?

rigid island
bleak tree
#

It's messy and I have redundant functions cuz I made changes recently but havent gone back and removed the old unnecessary code, but these are all the functions that deal with loading scenes

tawny elkBOT
bleak tree
#

oh

#

apologies

rigid island
#

more interested in seeing how you deal with assigning a Instance to Game Manager

#

sounds like you might not be handling possible duplicates

bleak tree
#
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }```
shadow wagon
#

how did you type this character using your keyboard?

bleak tree
#

I did not

#

that's supossed to be an accent in Spanish (está) but some programs can't cope with stuff that isn't English

shadow wagon
#

i know it would be á

bleak tree
#

As someone who has both and accent and an Ñ in my full name I struggle a lot with this

#

idk why it happened or how

#

But it's everywhere lol

shadow wagon
#

oh, so pressing the key does that?

bleak tree
#

nope

#

Again I don't know how that happened

shadow wagon
#

did you not write that comment?

rigid island
bleak tree
#

There is a chance it's a chatgpt comment but chatgpt is fully supported in Spanish so that should not be it

#

I wrote this code like over a year back now

#

I barely remember how it works

rigid island
bleak tree
#

No don't worry lol no a single line of code is from gpt

#

I had little time to comment the code (I was on a deadline) so I resorted to it for comments

#

Double checking to make sure my code wasn't murdered in the process (it was and I had to pull a backup to save the whole enemy spawn system lol)

rigid island
#

you could put maybe inside Game Manager the OnSceneLoaded event from Scene Manager and see if it persists for real

#

if its not something else is jammin up your pausing

bleak tree
#

the thing that confuses me the most is that it seems 2 instances of the GameManager exist after loading the scene back from the main menu

#

I have setup a couple Debug.Log with "Pause" and "Resume" on them and they fire at the same time once reloaded

#

But only once on a fresh load

rigid island
bleak tree
#

Yeah ik

#

There's also no visible duplicate in the hierarchy

#

So im just left wondering if it's a Unity moment

#

I've had those in the past

rigid island
#

much more likely something in the logic itself not unity

#

hard to say much from this point of view because we cannot see the full setup

mossy snow
# bleak tree Scene switch

this fragment of code is a little suspicious. You are enabling the cursor and assigning variables just before a new scene is loaded? If this is in a singleton, I would expect a yield or other wait logic right after the load. Even synchronous non-additive scene loading like this isn't instant; the load is scheduled to happen at the end of the frame

bleak tree
#

Removing those lines of code doesn't fix anything though

old elk
#

but that's minor

mossy snow
old elk
# bleak tree ```cs private void Awake() { if (Instance == null) { ...

this is not a great method of handling singletons that derive from MonoBehaviour, you should use something like this instead https://github.com/UnityTechnologies/InputSystem_Warriors/blob/master/InputSystem_Warriors_Project/Assets/Scripts/Utilities/Singleton.cs

GitHub

Example Project for the new Unity Input System. Contribute to UnityTechnologies/InputSystem_Warriors development by creating an account on GitHub.

#

I adapted this for my own game, works fine. Will probably help if the issue is a "zombie" singleton.

#

from what I'm gathering, the way you're using this singleton runs antiparallel to the concept of a singleton - at no point should you ever be doing new Singleton outside of the actual Singleton class, instead you should have your getter/accessor (in this case the Instance property) return the existing instance or create it if it doesn't exist

bleak tree
#

Hmm well, for the time being I have managed to fix the issue I was having, pausing now works correctly when the game scene is reloaded

old elk
#

re: events, Unity behaviours have an OnDestroy message that you can use to unregister event handlers and whatnot when the object is destroyed as well

in regular C# you can just overload the destructor (at least, you should be able to)

bleak tree
#

I do think I'd like to try redoing this entire project down the line

#

It's way too messy and needlessly complex as it stands

old elk
#

welcome to all game dev

#

"spiderweb code" is kind of a norm

bleak tree
#

I am decently proud of a couple of the systems I put together but they for sure could be much improved

old elk
#

doesn't have to be, but it often is lmao

old elk
bleak tree
#

I would also like to redo it since I want to turn it into a multiplayer game, but with the current code that seems next to impossible

#

I already tried

old elk
#

generally speaking if you want to make something multiplayer you can start by trying to make it singleplayer but with an internal game server

that's how Hatsune Miku handled Minecraft's multiplayer way back in like...1.3

bleak tree
#

Somehow my enemy spawning system ended up spawning "ghost" entities in the client server that can be "killed" but never actually "die" server-side so you have the server having all enemies while the client has killed them all

#

But if the host kills them, then they also despawn in the client after the despawning time has passed

#

It's.. weird

old elk
#

sounds like your server isn't updating non-host clients

#

your host should just be another client btw

bleak tree
#

They just dont seem to be syncronized at all

#

They don't follow the same target

old elk
#

yeah that's a netcode issue

bleak tree
#

They are the same entities but function as separate ones

old elk
#

no enemy logic should be occurring clientside unless it is completely deterministic

bleak tree
#

It's kind of amusing, in a way

old elk
#

2013 warframe energy

#

stuff that can be clientside is like

particles, ragdolls, etc.

#

though serverside ragdolls are funnier becase everyone sees the same dumb physics

bleak tree
#

getting the player movement to work and be synchronized was already a mess lmfao so I think I'll leave the MP idea for a rewrite

#

If I even end up doing it

old elk
#

yeah multiplayer is always a challenge

bleak tree
#

But I really want to do it cuz it's a cod zombies clone and where's the fun if it's not a 4 player coop

old elk
#

i'm not planning on it anytime soon for that reason, huge pain in the ass

bleak tree
#

Speaking of things that were a pain
FUCK coding the perks god that was an awful experience i HATE speed cola (I probably made it way harder than it had to by virtue of adding perks after the game was ""done"")

old elk
#

despite having worked on CoD I've never played it

#

i have no idea how the perk system works lmao

bleak tree
#

Speed cola increases reload speed

#

I ran into an issue where it seemed to be exponentially increasing reload speed so it just ended up being instant..?

old elk
#

were you using an "attribute" model for stats like reload speed?

bleak tree
#

I do not know what that is

old elk
#

or were you just modifying the value in place

bleak tree
#

I just use good ol variables

#

The major issues was actually the actual reload speed and the animation being sped up properly

old elk
#

attribute is like...you have an "Attribute" class (C# calls annotations "Attributes" which is confusing as shit if you're new to it) that stores the base value of the attribute, like strength/speed/etc., and then you have modifiers and a final value

#

that's the simplified version

#

but that lets you easily do stuff like temporary buffs and bonuses from perks or equipment

#

well, "easily" - it's more work to set up, but you can reliably remove those buffs/equipment/perks and have everything work as intended lmao

old elk
bleak tree
#
                case 2:
                    if (!speedcola_Active)
                    {
                        //Quick revive
                        speedcola_Active = true;
                        player_PerkCount++;
                        player_ActivePerks.Add(Instantiate(perkIcons[perkID], perkContainer.transform));
                        foreach (GameObject gun in weaponHandler.playerWeapons)
                        {
                            gun.GetComponentInChildren<GunController>().IncreaseReloadSpeed();
                            Debug.Log("debug_speed cola " + gun.name);
                        }
                        GameManager.Instance.ReduceScore(perkCost);
                    }
                    break;

    public void IncreaseReloadSpeed()
    {
        //gunAnimator.speed = 1 * speedMultiplier;
        gunAnimator.SetFloat("speedMultiplier", defaultSpeed * speedMultiplier);
        reloadTime /= speedMultiplier;
        emptyReloadTime /= speedMultiplier;

    }

    public void DefaultReloadSpeed()
    {
        gunAnimator.SetFloat("speedMultiplier", defaultSpeed);
        reloadTime *= speedMultiplier;
        emptyReloadTime *= speedMultiplier;
    }
old elk
#

ah, switch statements.

bleak tree
#

This ended up working

#

So this way it stayed

old elk
#

mood

bleak tree
#

I remember when I first coded the reload function

#

My smartass decided to use if statements to check the different possible states a gun could be reloaded in

old elk
#

ideally your game would not understand your UI's existence and the UI would just read your game data, so you wouldn't have to do that Instantiate for the perk icon

bleak tree
#

And fought with that decision for a few hours

#

Until I realized for loops exist

#

And just used a for loop

old elk
bleak tree
#

It's a super basic classic cod style reload where reload cancel is possible and reloading just adds the missing ammo back to the mag

#

So if you are 21/90 you end up 30/81

#

It's quite literally just a for loop

old elk
#

...yeah this is the exact reason you want to use a class to hold stats + modifiers instead of just modifying a value in place

bleak tree
#
IEnumerator ReloadWeapon(float weaponReloadTime)
    {
        isReloading = true;
        yield return new WaitForSeconds(weaponReloadTime);


        // Llena el cargador con munici�n de reserva
        for (int i = ammo; ammo < ammoCapacity && reserveAmmo > 0; i++)
        {
            ammo++;
            reserveAmmo--;
        }
        isReloading = false;


    }
old elk
#

i have to ask

bleak tree
#

the script im most proud of is the barrier destroying and repair mechanic that I nailed 100% first try

#

I was amazed

#

Had no troubleshooting cuz it just worked

old elk
#

why not just do reserveAmmo -= ammoCapacity - ammo then ammo = ammoCapacity

#

that's so many instructions

#

i oversimplified a bit but you can still account for the player not having enough reserve ammo pretty easily

bleak tree
#

Cuz I didnt think of that

#

Simple as

#

the for loop worked and did exactly what I needed it to, so I just left it there

old elk
#
int reloadAmount = Math.Min(reserveAmmo, ammoCapacity - ammo);
ammo += reloadAmount;
reserveAmmo -= reloadAmount```
#

well for future reference lmao

old elk
#

the todd howard memes are actually very accurate

bleak tree
#

it just works

old elk
bleak tree
#

the game is super light anyway so I don't need every optimization possible

#

actually i havent tried it on like super low end hardware

old elk
#

yeah i mean don't sweat learning projects too much

bleak tree
#

I probably should do that

bleak tree
#

Wouldnt still be working on it otherwise

old elk
#

honestly my game isn't even a learning project and i still overthink everything without even performance testing it first

bleak tree
#

I'd like to release it on Steam and all but it's so barebones and janky that I'd feel bad doing so

#

it has like 8 weapons and 1 tiny map

old elk
#

i would take a serious, long look in the mirror before trying to release anything on steam

#

ask yourself if you're fine with it basically not selling

bleak tree
#

yeah I am

old elk
#

unless you've got a genuinely unique idea most people will pass up an amateur single dev game

bleak tree
#

It's like 100 bucks to upload to steam isn't it

old elk
#

I have no idea. I've never looked into it

#

my shit's nowhere near far enough along lmao

#

I'm sure there's a fee somewhere

lean sail
#

i believe you do get the money back if it makes 1000 (or whatever amount they said)

old elk
#

interesting

#

Also remember that you'll probably only end up with ~50% or less of profit from sales, pre-tax

#

i don't mean to say the only factor in game dev should be whether or not it'll sell, but if you're trying to make a go of it as an indie dev you do need funding sadly

bleak tree
#

This is more a hobby rn

#

I'm currently aiming towards entering the industry as a 3D artist

#

I like coding and 3D about equally much so im kind of torn

old elk
#

honestly - and i don't mean this as a commentary on your programming skills, i just mean the job market sucks - you're better off doing art than code

#

it's rough getting your foot in the door in software

bleak tree
#

it's also rough in art notlikethis

#

it's rough in general especially in the current landscape with all the layoffs

old elk
#

yeahh

#

i got laid off a bit under two months ago

bleak tree
#

that sucks

old elk
#

not looking to go back in

#

wasn't a fan of working in AAA

bleak tree
#

I just want to start working right now I need that experience

old elk
#

i wasn't exactly the best engineer to begin with and the demands kept ramping up across the board to the point where we had people walking out lmao

#

maybe keep an eye on smaller studios that make games you like and see if they have openings/an email, smaller companies typically just have a jobs@company.com type email where they accept resume/portfolio submissions rather than a more formal application process through a website

#

though they will typically post general role requirements for each role

bleak tree
#

I've often looked at those and rarely do they need entry/junior level unfortunately

old elk
#

that's kinda the other issue with the job market in general, nobody wants to hire new grads/entry level

bleak tree
#

I'm starting an internship next week so at best I could have a job after that is over but that is highly unlikely

old elk
#

oh shit, nice. good luck, some places do internships to scout new hires tbh

#

...others do it for tax breaks

bleak tree
#

It's a master's internship so idk if they want new people

merry forge
#

how should I go about starting a coroutine from a script that is not monobehaviour?

lean sail
#

choose one related to your object, or one that doesnt get destroyed, and just call StartCoroutine on it

merry forge
#

hm, ok

#

that should work, actually

#

thanks

#

actually now that I think about it, coroutines still block the main thread don't they

#

so I'm going to have to use async either way

rigid island
# merry forge actually now that I think about it, coroutines still block the main thread don't...

It is important to remember that coroutines are not threads. Synchronous operations running within a coroutine still execute on the main thread. If the goal is to reduce CPU time spent on the main thread, it is just as important to avoid blocking operations in coroutines as in any other script code.
https://docs.unity3d.com/2017.2/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity3.html

merry forge
rigid island
#

most Unity functions are on the main thread

#

Awaitable lets you switch threads on fly so you can potentially go back n forth on main vs other, depending on the code you call in that function

#

also you could potentially look into Jobs

#

thats multi threading

merry forge
#

got it

#

ok I'm not sure how to write this

#

basically, I need to run (on another thread) a function that blocks for a few seconds, then use its return value on the main thread upon competion

cosmic rain
#

Async or thread sleep or something

#

Maybe both

inland comet
#

does someone know real quick if Init() or Awake() happens first?

#

I can't find Unity docs on Init()

rigid island
#

are you confusing Start & Awake?

inland comet
#

Init() happens on prefab creation is all I understand but it does exist

rigid island
inland comet
#

That's what I want to know too 😅 I have so far gathered it seems like it's from a framework so not technically Unity which is why it's there and I can use it to pass arguments but there's no docs...?

rigid island
rigid island
#

and what exactly are you trying to do

rigid island
inland comet
# rigid island and what exactly are you trying to do

It would probably take me too many paragraphs to explain 😅 Dynamically growing plants is hard apparently. I need to grab a variable from an object when it's created via a prefab but only change that variable if it was Init() with a specific game object

sharp garden
#

sorry for the random ping but what unity version are you on?

even though we are doing the same thing it has different results, wondering if it might be a bug that has been fixed in a newer unity/spline package version 👀

rigid island
#

prefabs are nothing more than assets as template for what a gameobject will be, think of it similar to a blueprint to gameobject

#

anyway if thats the case you could create your own Init Function to run if you instantiate
var myInstance = Instantiate(prefab, pos, rot)
myInstance.Init(someObject)

inland comet
#

Yeah I know what a prefab is, that doesn't answer if Init() or Awake() happens first

#

I think it's Awake() I just ran some debugs

rigid island
#

right easily testable, and "cretae a prefab" means something completely different to me

#

creating a prefab happens usually in the Editor , what you are talking about is Instantiation

inland comet
#

Yes the Init

rigid island
#

"the init"

#

no idea what you mean literally no such function exists until you create one

#

Instantiation and Initialization, different things

round violet
#

in unity is there a update dependency concept ?

#

aside having a direct reference and calling a function, making an object always tick after another one

swift aspen
round violet
#

thanks

last quarry
round violet
#

in my case its something that must run early

#

shouldnt ReadValue on a input action return a value ?
i have a touchscreen "swipe" (delta binding path), it wroks correctly if i use the performed callback, but if i read the input value on update i get 0,0

#

from the docs and comment on the function i should be able to get the current value for the last captured input stack

steady bobcat
#

there is version 2.8.1 actually which has nice extras (2.7.1 added spline extrude profiles for roads!)

round violet
#

when creating a new mono instance with the new keyword, is it attached to a gameobject ? if yes, how does it determine which one ?

tender ice
#

any ideas on how to make the wall not be rendered behind the glass?

#

not even sure if this is the correct chat but yeah

steady bobcat
night harness
steady bobcat
#

I presume StartCoroutine() would throw an error as Unity is who is continuing their execution over time

#

async functions would work still

last quarry
#

It just doesn’t compile

#
You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()
ItemClass:.ctor()
inventoryV1:.ctor()
#

Well either that or it throws. Can't tell from the forum post

steady bobcat
#

should be a runtime exception

#

we already knew it was a bad idea

night harness
#

lives via activator.createinstance

#

even calling the gameObject getter throws an exception tho lol

#

(and coroutines unfortunately do not work)

steady bobcat
#

dunno what you are trying to do but stop 😆

night harness
#

the best way to learn is to fuck around and find out 😄

steady bobcat
#

In this case its just a bad idea. Use async instead or a random object to run coroutines on (they can be started on any Component)

round violet
#

is there a way to reference a prefab with a specific script on it (root) ?

#

and not a plain GameObject

night harness
#

yeah

#

same way you'd do a gameobject just with the type you want

#

unity will be smart and let you drop in a prefab if it has that type on the root

round violet
#

whats the meta attribute for that ?

night harness
#

what do you mean

round violet
#

im talking about a serialized field that only accepts a GO that has a given component

night harness
#

yeah just the type

round violet
#

well it doesnt show anything if i just put the type

night harness
#

it should? is the type inheriting from MonoBehaviour?

steady bobcat
#
[SerializeField]
ParticleSystem particleSystem;
round violet
#

yeah

steady bobcat
#

you are over thinking it

round violet
night harness
#

yup

steady bobcat
round violet
#

okay so its just the unity object selector thats broken

#

sad

night harness
#

show stuff

#

Oh are you looking by pressing the circle

young yacht
#

you mean this?

round violet
#

well this is not picking the projects prefabs wit hthe script at the root

#

you have to manually drag and drop it

night harness
#

yeah the default search is dumb

young yacht
#

you cant put stuff from the hierarchy on a prefab

night harness
young yacht
#

ah xD

#

my bad

round violet
#

yeah i wanted the viewer to display this

#

which has the script at the root

night harness
#

@round violet if you turn on the adv. one in prefs it works like how you'd expect

#

but that search mode requires caching/indexing your project which isn't instant

#

it's better in my experience but your results may vary

round violet
#

i dont mind a initial indexing

#

thanks for the tip!

night harness
#

And just in case you don’t know this also means you can instantiate and return the type rather than gameobject

#

Saves the getcomponenting

round violet
#

thats good to know

#

what happens if i try to edit the prefab ? would unity prevent it or will i just edit the asset ?

night harness
#

as in edit it via code?

round violet
#

yeah

round violet
night harness
#

It would edit the asset yeah. Same would happen if you were doing gameobject too

#

Gotta be careful but can be handy in some cases. Eg if you turn off the prefab, instansiate it then turn the instance and asset back on you can delay Awake()

sonic bloom
#

I have two files:
one is command sender
one processor ( process happens frame by frame ( in update loop ) )
i want first file lines to wait until certain flag is turned false in second and then execute next line
but my game frezzes
can anyone pls help me solve this?

mellow sigil
#

You have an infinite loop. If you can't find it yourself you'll have to show the code

sonic bloom
#
using UnityEngine;

public class RobotMovementController : MonoBehaviour
{
    public Traj trajectoryController;
    public URInverseKinematics ikSolver;
    public GripperController gripperController;

    public void goto2(float[] targetAngles, float velocity = -1f, float acceleration = -1f)
    {
        trajectoryController.Goto(targetAngles, velocity, acceleration);
        while (trajectoryController.isTrajectoryActive)
        {
            // Wait for trajectory to complete
            System.Threading.Thread.Sleep(10);
        }
    }
}

i know it is this one but i dont know what to replace it with

mellow sigil
#

Thread.Sleep pauses the entire game. You'll have to use coroutines or async or just check the condition in Update

sonic bloom
#

but if i use it in update then, i will have to set flags to each of them so that they dont run again
and
coroutins i ll try thanks

mellow sigil
#

There are other ways to make one-off events in Update but coroutines are the easiest in this case

steady bobcat
#

async and coroutines are the way to go for this

round violet
#

for a bullet pool system, i wonder if its better that i check for overlaps with a sphere cast on each frame (no collider on the bullet), or if i should use a collider and use trigger/collision detection

#

idk the physics overhead in unity

#

(i have hundreds of bullets)

last quarry
#

2D or 3D?

round violet
#

3D

last quarry
#

You'd have to test it yourself to find out which is faster

round violet
#

they use OverlapSphereNonAlloc

#

its written

hexed pecan
#

This would also give you continuous detection so you dont get tunneling (projectiles missing collisions at high speeds)

round violet
#

would this work fine on mobile ?
i dont know much about jobs in unity

#

idk if async stuff is power expensive on mobile

#

also, would scheduling a new job each frame fine ?

leaden ice
round violet
#

well since its async it could take more than a frame ?

#

i dont mind receiving the job result a few frames late

paper lotus
#

Hello quick question, For small turn-based RPG, is it better to create a persistent Scene that has Managers, PlayerData, Camera, etc..

latent latch
#

Looking just for conformation before I just implement my own

last quarry
#
Unity can't serialize Dictionary so here's a custom wrapper that does. Note that you have to extend it before it can be serialized as Unity won't serialized generic-based types either.
#

Sounds like what you want, but I'd be hesitant to build on top of the render pipeline like that.

latent latch
#

I'm so confused why it's in the render namespace

#

they must be using it for some modules inside of it

somber nacelle
#

they need to update the docs because that last sentence about serializing generic types hasn't been true for a couple of years now

#

and by "a couple" i of course mean since 2020 because that was only like 2 years ago, right?

latent latch
#

If the generic type has a constraint yeah, but otherwise you need those SerializeReferences

last quarry
#

Yes, someone mentioned that. It's still in the docs though

latent latch
#

Ah, ok I got it to work. I forgot to actually tag one of my nested classes which was breaking serialization apparently. Yeah seems to work out of the box for monos.

#

Not that I care too much about built-in, but since it's part of the URP SRP rendering namespace it wouldnt work unfortunately

latent latch
#

Well, looking at implementations for a serializable dictionary it seems like a lot of these iterate over the dictionary every single time something is serialized and that seems like an awful idea. Anyone any sources to something that would work for say a large grid tool that's actively changing?

steady bobcat
#

You would need to offer your own get/set functions i guess to sync changes with the serialized lists and dictionary

#

but this brings new challenges

latent latch
#

All these implementations are horrible. It's just clearing the dictionary wrapper and having to repopulate it each time something is inserted

#

via OnBeforeSerialize callback

night harness
#

i mean

#

for most people thats just kinda fine

latent latch
#

True, but I got a voxel tool that's got about 500k entries in it

steady bobcat
#

Then you need a custom version that can split up how the items are stored in a smarter way perhaps?

#

could also not auto sync the changes but require a manual sync to the serialized version?

latent latch
#

yeah i was thinking that. I may just end up writing my own serialization I guess if it comes down to it

round violet
#

are delegates expensive to call each frame ? (at a high count)

#

for design purposes i would rather use delegates, but performance wise a pooling on update would maybe be better

somber nacelle
#

invoking a delegate is basically exactly as expensive as just calling the methods it contains directly. the expense is when you subscribe/unsubscribe from it as they are immutable so a new instance is created for each of those operations which generates garbage.
of course, if you are concerned about performance you should instead use the profiler instead of asking somewhat cryptic questions where the answer is usually itdepends

plain summit
#

Quick question folks:
We have an issue where Application.Quit takes a while on some platforms (6-10 seconds on Windows) and crashes completely on others (Steamdeck). I've seen similar issues come up, but havn't really found any proper solutions for it yet. Has anyone found a way to deal with this and/or a good understanding of the underlying issue?
(This is on 6000.0.38f1)

steady bobcat
vestal arch
#

crashes completely on others
-# well it did quit

steady moat
plain summit
plain summit
steady bobcat
plain summit
#

Thanks, Ill try that.
Its using a standalone linux build.

steady bobcat
#

cool then may be easier. You can try starting the process and piping the std out to a file.

plain summit
#

the crash doesnt occur on other linux distros we have tested though, which is puzzeling.

#

so turns out: the crash does not occur in desktop mode 🙃

steady bobcat
#

I bet using a windows build via proton will just magically fix this issue

hexed oak
#

it's 1000 times easier to serialize a struct and use a list of structs than a dict

leaden ice
#

Why not use both in conjunction?

vestal arch
#

you could just use a premade package for nice editor support, like the serializeddictionary asset

latent latch
#

As I mentioned, the serialize dictionary implementations are fake

#

you need to constantly refresh the dictionary which makes the whole quick lookup pointless

hexed oak
#

^ they're wrappers for other types. And yes I hold my point it takes me 2 seconds to make a simple serializable struct and use that.

latent latch
#

might as well just stick with a list of structs, but for my case I am actively serializing to this dictionary and iterating isn't an option

steady bobcat
#

If you want to do a better version you need to have buckets for the data yourself and serialize these collections instead of one gigantic one.
If your data can already be split in to "dimensions" of some kind then that is also a way to go (kd trees)

late lion
vestal arch
#

also it doesn't matter that they aren't actually dicts for most cases does it
it's there for dx, not perf

latent latch
#

Ok so here's the problem. If you want to serialize data it needs to be in someway a list as far as I can see. You can serialize that data each time you insert it into the dictionary by throwing it into a list, sure, but if you need to do a lookup it needs to be in the dictionary

#

But the dictionary will clear its data when unity recompiles, so basically it needs to be in that list at all times, but this defeats the purpose of the lookup

#

if you are serializing current data at all times, then you need to sync these two containers which means replacing those keys by iterating the list

vestal arch
#

a serializeddictionary is just a replacement for the boilerplate of generating a dictionary from a list of structs, imo

and by replacement i mean, "someone else already did it"

steady bobcat
#

So this is why its just done in a lists to keep keys and values

steady bobcat
#

overcome the cost of creating a new dictionary on de serialize

#

Im just trying to point out why it sucks rn

vestal arch
#

so the whole concern here is just, perf on deserialization?

#

why is this an issue lol

latent latch
#

Because I'm not iterating over a list of a handful of entries

#

I've a paintbrush for a voxel tool that's inserting hundreds of voxels a frame

#

which needs to be serialized per stroke

steady bobcat
#

do these have a 3d/2d position?

latent latch
#

3d grid

vestal arch
#

if you want something like a dict, you could

  • use a list of structs directly, and use Find or smth
  • create a dictionary on Awake so you can use it like a dict
  • use a premade asset to do #2 except you don't have to write boilerplate
latent latch
#

It's an editor tool ;p

steady bobcat
#

you could have fixed this ages ago with kd trees as you can serialize these as is

vestal arch
latent latch
#

Yeah, I could chunk it more and fix a lot of issues, but the idea is I want to decide the chunk on the export

#

I guess I can undo the chunks and redo it later?

steady bobcat
#

you can convert the data later, rn you are concerned about actually storing it...

vestal arch
latent latch
steady bobcat
#

this is in editor rn hence unity serialization

latent latch
#

Yeah cause otherwise a runtime dictionary would work fine.

#

But got to deal with Unity's limitations

vestal arch
#

like i said: for dx, not for perf

steady bobcat
#

Id never use a dictionary for 500k voxels 😆

latent latch
#

I mean I use them everywhere too, but this is one the one use case where they would shine

vestal arch
#

cool, but that still doesn't mean serialized dictionaries are inherently bad lmao

last quarry
#

Dictionary lookups are really fast

steady bobcat
#
Voxel[,] voxels = new Voxel[100,100]; //Do this
Dictionary<Vector3Int, Voxel> voxelsDict //Not this
last quarry
#

Obviously you wouldn’t use them for voxels

latent latch
#

I mean, you can pretty much get the same functionality from a list of structs, but if you don't want that boilerplate I get it. Still, you do need a way to draw them on the unity inspector

last quarry
#

Nor would I use an array

latent latch
#

It's an infinite grid btw

last quarry
#

Octrees are more efficient for voxels. Otherwise you’re just storing a bunch of empty data.

latent latch
#

similar to unity's grid

#

which is why I use a dictionary

last quarry
#

So you’re going to serialize 500,000 dictionary entries in a YAML document?

latent latch
#

Yeah that's another problem. I guess I might as well just write my own serialization

last quarry
#

Definitely a better option here

steady bobcat
#

kdtrees/octrees seems smartest but try to avoid serializing many children as the depth limit is 10
But hopefully it results in some class + list/array that can be serialized and then used as is

latent latch
#

I may be overthinking how quickly I should be serializing the data. Considering how most of these entries are bound to elements on the scene, and since Unity doesn't automatically save the scene data when managing those objects, I could just delay it until saving the scene and reloading the domain.

primal gale
#

Ive got a situation where a flying enemy (2D) fires a bullet from a fixed position under the enemy. But lets say I go above the enemy and the bullet will collide with the enemy, how can I make it os that the bullet ignores the enemy its being made on? Using rb so I can shoot it

leaden ice
#

either of those will work

primal gale
#

or do I have to do that after I already instantiate the bullet

#

that makes more sense

#

hold on

#

nope

#

oh im dumb let me try the ontrigger2d

leaden ice
leaden ice
#

you do it when you spawn the bullet

primal gale
#

I can try layer collision

leaden ice
#

it works if you do it right ¯_(ツ)_/¯

#

presumably something is wrong about your code or your setup.

primal gale
#

ive just got this simple code

#

takes in the rigidbody of the enemy that is firing, and the bullet that was just instantiated

leaden ice
#

bullet is your prefab

primal gale
#

but I thought it becomes real when its instantiated

leaden ice
#

No

primal gale
#

ah

leaden ice
#

bullet is always the prefab

#

instantiate returns the newly created object

#

you are ignoring that currently

vestal arch
primal gale
#

so how would I call the real bullet

leaden ice
#

Capture the return from Instantiate in a variable

#

so you can do things to it

#
var newBullet = Instantiate(bullet, ...);
primal gale
#

alright thanks it works now

chilly surge
#

After upgrading to Unity 6, I need to check WebCamTexture.width/height to be positive before calling GetPixels32, or else it might crash on iOS.

hexed oak
#

Is there a way to get a cross section of a gameobject relative to the current camera? Like an outline or something?

#

I think the bounding box covers a much larger area than the actual outline of the mesh

#

and when the gameobject is rotated, that bounding box moves to an even more exaggerated larger area

steady bobcat
#

depends what kind of outline you need. Just some post processing effect or texture?

hexed oak
#

I need the screen point positions of the red circle, or a few of them

#

and if the object rotates (maybe a more complex object would have been a better example), a new outline would be needed

steady bobcat
#

I think you would need to render an outline (using some technique such as inverse hull, edge detect via depth/normal/stencil) to a texture to then extract screen positions of it.

leaden ice
#

Do you need it in CPU world or for rendering something

lusty vector
#

holy heck i managed to make the dialoguebox thing actually work! hooray!

merry aspen
#

Hey guys, got some question. Lets say I have some character created from different floating pieces. It would have an idle animation, but lets say, if an object was thrown at them at high speed and I wanted the pieces of enemies to be ejected but slowly float back to their initial position, how should I handle this? Is there such a thing as a non-rigid animation in Unity6?

lean sail
merry aspen
#

But maybe there is a simpler way...

lean sail
merry aspen
night harness
#

@pastel cipher we'll move here

#

so for stuff that you want to be global i'd suggest something like this

public class MyGameManager : MonoBehaviour
{
    public static MyGameManager Instance;

    [field: SerializeField] public ColorPalette ActivePalette { get; private set; }
}
public class ColorPalette : ScriptableObject
{
    public static ColorPalette Instance => MyGameManager.Instance.ActivePalette;

    [field: SerializeField] public ScriptableColor Damage { get; private set; }
    [field: SerializeField] public ScriptableColor Healing { get; private set; }
    [field: SerializeField] public ScriptableColor Protection { get; private set; }
    [field: SerializeField] public ScriptableColor Currency { get; private set; }
}
#

So you have a ScriptableObject that holds a reference to all your global color selections. Then you store that on your GameManager.

Because your GameManager is a Singleton you can make a "Instance" field on your ColorPalette that just points to your GameManager's reference of the palette

#

which means once you plug in a ColorPalette into your GameManager you can use your colors like ColorPalette.Instance.Damage.Color etc.

pastel cipher
#

Ye... but why not just call the TextFormating directly as I am doing already?

night harness
#

The short answer is that you could still do that yeah. But this is moreso an example of using scriptableobjects to keep your logic and data separated in a modular and organised way. some practical benefits of this specifically though is

  1. For when you do want certain content to be able to manipulate their prefered color, using the same system everywhere is nice and consistent
  2. I know your not concerned with this for this project, but imagine you wanted to provide colorblind accessibility features, to where you could swap out the entire color coded palette of your game by just changing the ColorPalette the GameManager references.
  3. In the even you wanted specific associated icons to go along with this color coding, you could store said icons in the ScriptableColor script, which is an example of how easy this would be to expand upon.
pastel cipher
#

It's not the cleanest, for sure, and I could make it more accesible from the editor which I think is the path you are going for, but, actually, I don't really care much on that regard as long as it's not like incomprensible levels of messy

#

And I don't think it is

night harness
#

at the end it's up to you

#

But I do think you should dip your toe in the water abit here when you can

pastel cipher
#

I am gonna have to make a superclass for all the different types of shield, damages over times and stat modifiers on the satatus effects when I begin adding more so, I'd probably consider adding the SO on status effect specifically at that point

night harness
#

Just keep this stuff in mind yeah

#

getting your definitions out of your code and script default references and into so's and prefabs etc. is gonna have major notable improvements to your workflow once you adjust

pastel cipher
#

Mostly I save them on prefabs, yeah

#

So me using the status effects as components that are directly added has turned a bit messy, ye

night harness
#

yee

#

oh another thing

night harness
# night harness which means once you plug in a `ColorPalette` into your `GameManager` you can us...

if your like me i'd imagine ColorPalette.Instance.Damage.Color looked very long and gross. with an extra definition per color though you can clean it up with static getters super easy

public class ColorPalette : ScriptableObject
{
    public static ColorPalette Instance => MyGameManager.Instance.ActivePalette;

    [SerializeField] private ScriptableColor damage;
    [SerializeField] private ScriptableColor healing;
    [SerializeField] private ScriptableColor protection;
    [SerializeField] private ScriptableColor currency;

    public static Color DamageColor => Instance.damage.TextColor;
    public static Color HealingColor => Instance.healing.TextColor;
    public static Color ProtectionColor => Instance.protection.TextColor;
    public static Color CurrencyColor => Instance.currency.TextColor;
}

so the static colors just point to the instance, which means now you could just do ColorPalette.DamageColor

#

could even remove the Color part of the property name ig too

pastel cipher
#

Well, it would be specially annoying if the autocomplete didn't get what I am going to type on like first 3 letters lol

#

It's fine

#

Oh, and thanks 😄

round violet
#

im new to the unity profiler and i have a few questions

  • can you zoom in the top "CPU usage" horizontal bar ? i cannot see the precise fps/ms (the only "checkpoints" are 15, 30, 60fps) so i dont know if im at 90, 120, or more FPS
  • when you select a white vertical line at the tope (see screenshot),is this a single frame ? im confused because in one vertical line i see multiple Player and Editor loops
steady bobcat
#

You can calculate it from the CPU time. e.g. for 16ms -> 1/0.016

round violet
#

i cannot see the frame time (aside inside the timeline)

#

there is only the frame times of each layer

#

i thought the profiler would zoom relatively to the min and max frame time it got during the profiling session, like here

quartz folio
#

Unclear what you mean by "here". Do you mean the Timeline view? If you're looking at the hierarchy view you can switch to Timeline using the dropdown on the middle left

round violet
#

between those two profiling session, the "cpu usage" view is zoomed in, relatively to the frame time

#

33-16ms on the left one and 8-1ms on theright image

thick terrace
#

are you just trying to see the exact frame time of the current frame?

quartz folio
#

It says it in this area bottom middle

#

If you're clicking on the correct graph

#

and also if you hover the top area

quartz folio
#

and also if you select the highlights area in the top left

round violet
#

thanks!

#

i totally missed that 😅

round violet
#

welp i think i got half of my answer, OverlapSphereCommand exists

rocky jackal
#

this will give me an array with 4 springs in it right ?

mellow sigil
#

3 springs

maiden fractal
#

indexing starts from zero, count strats from 1

mellow sigil
#

an array with space for 3 springs, if Spring is a class it starts out with 3 nulls

vestal arch
maiden fractal
#

fair enough

vestal arch
#

indexing starts from 0; but that doesn't change how you count things

#

if you have 4 springs, you have indices 0, 1, 2, 3

maiden fractal
#

sloppy wording by me

#

array of size 1 would have 1 inside the braces even if the index of the first and only element is 0 was what I meant

rocky jackal
wraith elbow
#

Hello guys
After renaming an embedded package, extension functions from are no longer "seen" by Unity/VS with error

CS1061: 'object' does not contain a definition for 'IsNull' and no accessible extension method 'IsNull' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?).

IsNull resides in the renamed package under a namespace DPON.Utils in a static public class Extensions.
The file where this error occurs does have a using DPON.Utils, but it's greyed out, as if nothing from this namespace is used
I'm kind of lost as to what might be causing this. The .asmdef associated with this package seems to be referenced correctly.
Deleting all .csproj files and Reimporting All assets do not seem to do anything...

thick terrace
wraith elbow
thick terrace
#

as long as the asmdef is somewhere above it in the folder hierarchy it should be part of it 🤔

#

can you see the project for it in your IDE?

wraith elbow
#

Yes

thick terrace
#

how about the platform settings on the asmdef?

wraith elbow
#

Any platform is ticked on both .asmdef containing Extensions and the one using it

thick terrace
#

is there anything else in the package which is working? you could check the manifest/package lockfile to see if it's being found at all

wraith elbow
#

Okay, turns out I indeed screwed up linking assembly references 🙃
Things were in a couple of different packages, and I was not looking in places I should have been looking

abstract inlet
#

helloooo just wondering if my code is particularly spaghetti’d and in need of optimization! not very experienced with coding overall and the code itself works fine without any obvious lag on performance or anything, just want to be sure it’s not detrimental in the long run when more scripts and objects are around

if anyone would like to take a look & has any thoughts / advice for improving the efficiency of it that would be great :]

https://paste.mod.gg/vgbyyofegdof/0

vestal arch
#

in general: worry about perf when it becomes a problem

#

worry more about the readability/maintainability and structure

true heart
#

in general GetComponent is quite expensive, its alright to use it in Awake/Start but then stick to using that cache variable

night harness
#

just expensive in comparison to caching them

thick terrace
#

more importantly, writing GetComponent everywhere is horrible for readability 😛

abstract inlet
#

fair enough lmao! I cobbled it from a lot of different tutorials late last night so I missed that, thank you!!

#

I think also because they used to be 2 separate scripts and then I realized I could just put them in the same script and forgot to actually use the variable 💀 like a fool

night harness
#

Why is PlatformTrigger being called with a tiny delay?

abstract inlet
#

I was trying to make it so that if the player dashed but wasn’t colliding with a platform there’d be a little cooldown where the dash velocity wasn’t affected by the gravity change so that they still traveled in a straight line

night harness
#

Ah

abstract inlet
#

that part was tricky because I spent like an hour trying to work with a coroutine & waitforseconds but it just wasn’t working shinji

night harness
#

A Coroutine might be a little more preferable

#

😛

abstract inlet
#

I tried I promise !! I think what happened when I tried to use the coroutine was that it kind of broke the gravity altogether because it wouldn’t start the gravity unless I had pressed the dash button, and on top of that it slowed the gravity down drastically scruncht

#

There’s probably a way to throw it into a coroutine without causing any other issues but that likely has something to do with how the current code is set up I think so I haven’t figured that out yet

night harness
#

(also you don't need to check this the opposite way as an else if, you can just do an else)

        if(onPlatform)
            rb2d.gravityScale = 0f;
        else
            Invoke("PlatformTrigger", 0.1f);
abstract inlet
#

CatYes ! I’ll try that later, I think VS kept giving me an error when I used else in general though. It kept thinking that the else needed a ;

vestal arch
#

GetComponent<Rigidbody2D>().gravityScale += gravityScale;
this should probably be an assignment, not an addition

#

also gotta ask - is this supposed to be top-down or sidescroller?

#

some parts of the code indicate one or the other

abstract inlet
abstract inlet
vestal arch
#

what's with the gravity thing then? you wouldn't have gravity in the Y- direction for a top-down perspective

abstract inlet
#

it's sort of like top down platformer? so I still want it to look like it's 'falling' if it misses the dash/jump

vestal arch
#

you usually wouldn't really have jumping as a core movement mechanic in a top-down game

abstract inlet
#

typically not no, i'm just testing around with a prototype to see what sticks! was inspired by Hyperlight Drifter's mechanics at a glance, not a lot of intense platforming but still some dash-jumping from platform to platform if that makes sense

vestal arch
#

like, it's in 2d, right? so jumping and "vertical" movement both go on the Y axis

abstract inlet
#

checks out! to clarify (since i used them interchangeably) it's just dashing forwards for now and not actually jumping

vestal arch
#

ah seems like that's in 3/4 perspective so there is some sense of going in the Z axis

abstract inlet
#

yes! or at least the illusion of it lol

vestal arch
#

yeah lol

#

so yeah you wouldn't be able to use the same rb movement directly for both of those, you'd have to add some stuff most likely

abstract inlet
#

it seems to work as-is, could you elaborate on what you mean/what needs to change in the current code?

vestal arch
#

well, what do your platform colliders look like? is it just a full boxcollider2d trigger across the entire platform?

abstract inlet
#

yes i think so!

vestal arch
#

so if you "jump" from one platform to another, it should look something like this, right?

#

but instead, it'd end up being like this, since you're "on" the platform when you enter the trigger

abstract inlet
#

ahhh i see what you mean

vestal arch
#

that illusion of height would have to exist separately from the rigidbody

abstract inlet
#

i've got more of a 'dash' thing going on and i'm not sure if i'll change it to an actual 'jump' yet, so currently it's not noticeable

vestal arch
#

so perhaps an issue for future self lol

#

but in the meantime - perhaps you just don't need gravity at all

scenic heron
#

can you check distance between objects using raycast?

naive swallow
#

Google it next time, it's faster

#

Literally just "Unity raycast distance"

#

first result

abstract inlet
vestal arch
#

well, what do you need it for?

#

or is it for falling from the platform?

abstract inlet
#

it is for falling from the platform

vestal arch
#

ahhh i see

abstract inlet
#

either way ty yall for your advice!! super appreciated

abstract inlet
abstract inlet
#

hmm ok i know i'm back so soon 😭 but i tried it out again with a coroutine and i'm just not sure why it's not working the same way after following a few tutorials

invoke code
coroutine code

attached videos, invoke example is the first one, working as intended with the red square dropping down very quickly/with a minor delay after dashing, whereas the coroutine one just. Isn't lmao

vestal arch
#

well you're gonna be calling the coroutine every frame you aren't on a platform, that doesn't sound right

#

should probably just start the coroutine when you dash

#

and also set the gravity to 0 in the coroutine, before the wait

hexed fjord
#

Invoke has += gravityScale
while Coroutine has = gravityScale

abstract inlet
hexed fjord
#

why did you put it inside the Input.Space section? now it wounld never fall unless you dash

abstract inlet
abstract inlet
hexed fjord
#

oh

vestal arch
abstract inlet
#

also if i put it at the start instead it 1) functions more or less the same (i.e. not falling at the right speed) 2) it actually no longer recognizes when it's on the platform to set the gravity back to 0 i think

#

OH i see let me try that

vestal arch
#

also wait i just realized

#

wouldn't this mean you can't fall off the far side of platforms lol

#

since you'd "fall" and then end up back in the trigger

abstract inlet
#

uhhh you might have to draw it out for me i don't know what you mean by the far side of platforms lol

vestal arch
#

like the "top" of the platform

vestal arch
hexed fjord
#

yeah, if you're making a top-down it doesnt make sense to fall in the Y axis

abstract inlet
#

OH that yeah i don't intend on that actually being possible later

#

like i'll probably put in other colliders or objects to block the sprite from leaving that zone if that makes sense? or at least that's the idea i have atm

#
using System.Collections;
using JetBrains.Annotations;
using Mono.Cecil.Cil;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public float moveSpeed;
    private Vector2 moveInput;
    public Rigidbody2D rb2d;

    private float activeMoveSpeed;
    public float dashSpeed;

    public float dashLength = 0.5f, dashCooldown = 1.0f;

    private float dashCounter;
    private float dashCoolCounter;

    public float dashCheck;

    private bool onPlatform;
    public float gravityScale = 1f;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        onPlatform = true;
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        onPlatform = false;
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        activeMoveSpeed = moveSpeed;
    }

    // Update is called once per frame
    void Update()
    {
        moveInput.x = Input.GetAxisRaw("Horizontal");
        moveInput.y = Input.GetAxisRaw("Vertical");
        moveInput.Normalize();

        rb2d.linearVelocity = moveInput * activeMoveSpeed;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (dashCoolCounter <= 0 && dashCounter <= 0)
            {
                activeMoveSpeed = dashSpeed;
                dashCounter = dashLength;
                StartCoroutine(DelayFall());
            }

        }

        if (dashCounter > 0)
        {
            dashCounter -= Time.deltaTime;

            if (dashCounter <= 0)
            {
                activeMoveSpeed = moveSpeed;
                dashCoolCounter = dashCooldown;
            }
        }

        if (dashCoolCounter > 0)
        {
            dashCoolCounter -= Time.deltaTime;
        }


    }

    private IEnumerator DelayFall()
    {
        rb2d.gravityScale = 0f;

        yield return new WaitForSeconds(0.1f);

        if (onPlatform == false)
        {            rb2d.gravityScale += gravityScale;
        }
        else
        {
            rb2d.gravityScale = 0f;
        }
    }
}
#

this is where we're at now lol

#

may be delayed in responses just multitasking on smth else atm

hexed fjord
#

just to cover all possibilities, can you check if you accidentally changed the value of gravityScale on the coroutine script? since its a public variable

abstract inlet
#

alright I checked and it was set to 1, so i experimentally set it to 0 and ran play again juuust in case but now it just kind of works like your typical top down without any fall mechanics which is great but not what i'm trying to do lol bob

hexed fjord
#

Copied your script into my project and it works just fine with the +=

hexed fjord
#

the newest would only increase gravity as long as you kept holding space

vestal arch
#

you really don't need to keep adding gravityScale

#

you don't need to add jerk lol

hexed fjord
#

well, it works, but i think the real issue is moving by setting velocity directly

vestal arch
#

ah yeah true, that should be disabled while dashing

#

i did notice that but i forgot to mention it 😔

hexed fjord
#

the prob is that it keeps negating gravity's acceleration, that's why constantly increasing gravity makes it act "normal"

#

the good answer would be to use MovePosition for movement instead i guess

vestal arch
#

that would break collision

hexed fjord
#

hmm, thats a tricky issue
i guess just increase gravityScale to 10 or something, that worked for me too

swift shell
#

Question for referencing things via GUID

We're using this for GUID generation:
https://github.com/Unity-Technologies/guid-based-reference

It's really nice to reference things cross-scenes

One small problem: We have a big scene with a bunch of stuff, and I was separating things in prefabs, to prevent file conflicts and better git diffs.

the problem is that GUIDs are only generated in scenes. Which I totally understand why. But the bummer is that if anything in this big scene needs a GUID, it will have to modify the scene. Even if the prefab is only instanciated here once.

Any tips? Maybe there's an alternative way of doing this.

vestal arch
abstract inlet
abstract inlet
vestal arch
# abstract inlet i return! how do i do this lol

basically, save some state to check when you can move.
you could have a boolean for "currently dashing", which you would set when you dash and unset when the dash is finished, and then in the movement portion, you would check for that and only if it's false would you do the normal movement

or for a more extensible system, you could have something similar with a state enum or something like that

latent latch
#

Variants are surprisingly extra useful when it comes to multiple devs working on the project, otherwise a larger scriptable object workflow works to keep it all just plain data

abstract inlet
vestal arch
#

you could just do the first one lol

abstract inlet
#

would it be less efficient in the long run though?

#

not sure when my little group might get an actual coder on board who could sort any of this out but for the time being i'm just hoping to make it less spaghetti wherever i can

swift shell
#

i could modify this addon to let me generate them in prefabs but that will cause more problems elsewhere

latent latch
#

Usually I just use c# GUID if I'm using them at runtime

#

and generate them upon creating an instance

#

Otherwise GUID supplied by the AssetDatabase works fine for editor usage

swift shell
#

i need references for specific things inside prefabs. i don't think asset guids cover that

#

guids that persist forever in disk

#

an alternative would be to split this big scene into multiple scenes but i'd prefer not to

latent latch
#

Throw it on a load scene as a singleton to reference

#

If it's a unique prefab instance then prefab variant or SO instance

swift shell
#

mmm yeah. like i could make a Guid component but for prefabs...

#

with a big warning like "this prefab should only be instanciated once!"

rigid island
#

spaghetti happens more with referencing, not bool/state management

abstract inlet
#

hmm i see. still slightly confused so i'll probably brush up on it later

#
{

    public float moveSpeed;
    private Vector2 moveInput;
    public Rigidbody2D rb2d;

    private float activeMoveSpeed;
    public float dashSpeed;

    public float dashLength = 0.5f, dashCooldown = 1.0f;

    private float dashCounter;
    private float dashCoolCounter;

    public bool dashCheck;

    private bool onPlatform;
    public float gravityScale = 1f;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        onPlatform = true;
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        onPlatform = false;
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        activeMoveSpeed = moveSpeed;
    }

    // Update is called once per frame
    void Update()
    {
        if (dashCheck == false)
        {
            StartCoroutine(Movement());

        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (dashCoolCounter <= 0 && dashCounter <= 0)
            {
                dashCheck = true;
                activeMoveSpeed = dashSpeed;
                dashCounter = dashLength;
            }

        }

        if (dashCounter > 0)
        {
            dashCounter -= Time.deltaTime;

            if (dashCounter <= 0)
            {
                activeMoveSpeed = moveSpeed;
                dashCoolCounter = dashCooldown;
                dashCheck = false;
            }
        }

        if (dashCoolCounter > 0)
        {
            dashCoolCounter -= Time.deltaTime;
        }

        if (onPlatform == false && dashCheck == true)
        {
            StartCoroutine(DelayFall());
        }
        else
        {
            rb2d.gravityScale = 0f;
        }
    }

    private IEnumerator DelayFall()
    {
        yield return new WaitForSeconds(0.1f);
        rb2d.gravityScale += gravityScale;
    }

    private IEnumerator Movement()
    {
        yield return null;
        moveInput.x = Input.GetAxisRaw("Horizontal");
        moveInput.y = Input.GetAxisRaw("Vertical");
        moveInput.Normalize();

        rb2d.linearVelocity = moveInput * activeMoveSpeed;
    }
}

current code looks like this + the dash & player are moving fine but they're not detecting the platform/gravity isn't 'activating' when they're off the platform

my laptop is also low on battery and i don't have a charger so i will resume work on it later runbitch ty for everyone's help so far!

robust dome
#

<@&502884371011731486>

sleek bough
#

!ban 1143311282108379216 ad spam

tawny elkBOT
#

dynoSuccess aeirik. was banned.

vestal arch
#

in fact it delays the logic by a frame lol

swift shell
#

anyway, thanks for the help @latent latch 🙂

btw, what did you mean by this? i don't think i understood

You can also create prefabs like a PrefabLookup table that incorporates these prefabs

abstract inlet
vestal arch
abstract inlet
#

oh I did not know that

vestal arch
#

also @abstract inlet am i understanding it right that you want gravity to not apply during the dash?

abstract inlet
#

so like. just the bool’s name default true? and then !name is false?

vestal arch
#

then why isn't that coupled lol

vestal arch
abstract inlet
vestal arch
#

the logic for disabling gravity and the logic for dashing is separated, even though they should be logically linked

abstract inlet
#

oh I see what you mean. But gravity should also function even if the dash button is not pressed (like if the player just walks off the ledge)?

vestal arch
#

so instead of that separate coroutine with a random 0.1s delay, you would disable gravity when you dash and reenable it when the dash ends

abstract inlet
vestal arch
latent latch
vestal arch
#

-# on that note, shouldn't dashLength be dashDuration?

abstract inlet
vestal arch
abstract inlet
vestal arch
abstract inlet
vestal arch
#
    void Update()
    {
***     /* elided */

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (dashCoolCounter <= 0 && dashCounter <= 0)
            {
                dashCheck = true;
                activeMoveSpeed = dashSpeed;
                dashCounter = dashLength;
+               rb2d.gravityScale = 0f;
            }

        }

***     /* elided */

-       if (onPlatform == false && dashCheck == true)
-       {
-           StartCoroutine(DelayFall());
-       }
-       else
-       {
-           rb2d.gravityScale = 0f;
-       }
+       if (!dashCheck)
+       {
+           rb2d.gravityScale = onPlatform ? 0f : gravityScale;
+       }
    }

-   private IEnumerator DelayFall()
-   {
-       yield return new WaitForSeconds(0.1f);
-       rb2d.gravityScale += gravityScale;
-   }
swift shell
#

pristine diff display

abstract inlet
#

WOAH temWHOA

#

I’ll be sure to try it out later tysm you didn’t have to plug it all out like this cat_explode

leaden ice
somber nacelle
#

yeah you can use diff as the language code for a code block

shadow wagon
#

woah that diff looks sick!

rustic rain
#

does unity have a way to draw a an arrow in debug?

shadow wagon
#

Debug.DrawLine() is the most convenient

#

it doesnt have an arrowhead, so its not a true arrow but for debugging purposes that doesnt matter too much

rustic rain
#

i see, thank you 😄

shadow wagon
#

its a real shame the options for visual debugging is so limited, I think that there's a lot of power that could be gained from it

rigid island
#

handles give you a bit more options / control

shadow wagon
#

I've used Handles.Label quite a lot, its incredibly helpful!

#

being able to read values as text in the scene, instead of having to constantly flip back and forwards between the game and the console, its a very good thing

steady bobcat
round violet
#

i assume that update transforms is slower if my object has a parent ?

hexed pecan
wheat spade
#

I have a pawn/controller communication system that uses Scriptable Objects. Each action a controller communicates to the pawn, "jump" for example, is an instance of "ScriptableAction". When a controller wants the pawn to jump, they have a serialized variable of type ScriptableAction, assigned with the jump asset in the inspector, and they call jumpAction.Invoke(). Every pawn that does something on jump would likewise have it's own variable and do jumpAction.AddListener(). The current system I have is pretty good and is perfect for AI controlled pawns.

I'm having trouble connecting the player's input to this system though. Should I have the player controller have a function for each action and connect it to the InputSystem, or somehow have all that logic in the scriptable object? I would prefer if I don't have to edit a c# class just to have my game start receiving input.

lean sail
# wheat spade I have a pawn/controller communication system that uses Scriptable Objects. Each...

this whole communication system through scriptable objects sounds extremely unnecessary.
to answer your question though, you would usually want to have your input handled in one place. then you just need to call the methods you want. Im not sure what your player controller is, or how these scriptable objects are set up, but this does sound like a very awkward scenario because of how you are using SO's here.
also no clue what "prefer if I don't have to edit a c# class just to have my game start receiving input" means. You can use the new input system but some class somewhere has to actually receive and process the input.

vestal arch
pure ore
#

Got a question. My character is still moving fast, but isn't the point of setting m_MoveDirection to its normalized self multiplied by the current speed supposed to make the player move slow?

Vector3 vector = transform.forward * MovementInput.y + transform.right * MovementInput.x;
m_MovementDirection.x = vector.x;
m_MovementDirection.z = vector.z;
if (MovementDirection.z > 1f)
{
    m_MovementDirection.z = 1f;
}
else if (MovementDirection.z < -1f)
{
    m_MovementDirection.z = -1f;
}
if (MovementDirection.x > 1f)
{
    m_MovementDirection.x = 1f;
}
else if (MovementDirection.x < -1f)
{
    m_MovementDirection.x = -1f;
}
m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
cosmic rain
pure ore
#

Well everything feels fast. Even with low float variables

cosmic rain
#

Must be your CurrentSpeed then.🤷‍♂️
Or whatever you do with m_MovementDirection later on.

pure ore
#

so maybe debug it? Okay

lean sail
pure ore
#

like at a snail's pace

lean sail
# pure ore yeah im not but if I do it makes the player move EXTRA SLOW

you probably changed multiple things then at once and are associating the wrong thing to this problem. you are normalizing the vector and multiplying by speed. it doesnt matter what you do to this vector beforehand. If it is not the zero vector, it's length will be CurrentSpeed at the end

#

the only thing those if statements are doing is limiting the directions you can actually move

pure ore
lean sail
#

you need the normalization though...

#

can you paste the whole context !code

tawny elkBOT
pure ore
lean sail
# pure ore https://pastebin.com/CETsAcWx

ok there are definitely a few things here to address. you shouldnt be calling move multiple times per update. have one vector that is the sum of all the movements you want, then call 1 move at the end of your logic. in that final move call, thats where you should be multiplying by time.DeltaTime.
what you had before with the normalization was fine
m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
i also dont really see why that 2nd move is needed, it looks like a bandaid solution that should just be removed

#

what you're doing now with multiplying by Time.deltaTime is making the x and z movement frame independent, but not the y because you are setting the y value after

pure ore
lean sail
pure ore
#

WAIT I know why

#

its because I don't have the player layer

lean sail
#

the only thing i see for jumping is that you're setting m_ActiveGravity += m_JumpForce * 0.11f; (which is a magic number here, you shouldnt need this random 0.11f here)
you have to account for this in your movement

pure ore
#

idk how but i did

lean sail
#

you're still associating the wrong thing to this problem here. you never need magic numbers

#

if it went high, thats likely because deltaTime wasn't factored in

wraith spear
#

Hi all, I'm working on a turn-based RPG and transitioning from battles in the overworld (Chrono-Trigger, Sea of Stars, etc.) to a separate scene (Pokémon, old Final Fantasy, etc.). However, I'm scratching my head a bit on how to pause the overworld scene while the additive combat scene is running. Any advice would be much appreciated!
After some research, I seemingly have 3 options:

  • Implement something like IPausable and use that to pause the overworld classes (most work, but feels like highest degree of control. Leaning towards this one)
  • Set everything to-be disabled as a child of a single GameObject and disable that (least work, feels a bit wrong however)
  • Unload overworld and reload it based on a previously saved state (feels like a middle ground of work needed but with a big risk of headaches later on in development)

Did someone implement something like this at some point? What were your experiences?

wicked scroll
# wraith spear Hi all, I'm working on a turn-based RPG and transitioning from battles in the ov...

Maybe this is unhelpful with how deep you already are, but I would suggest a variation on #1, where your overworld acts as a 'parent' and ticks the 'battle' world (or you have some intermediary parent of both, up to you) and so is the arbiter of whether/how much each should be active. This also lets you have them talk back and forth pretty easily if you need stuff to happen in the overworld in response to the battle (flags being set, achievemnts being tracked, whatever)

#

it's nice to be able to load the battle scene independently for testing, so having it act as its own environment but also be 'embeddable' is one way to do that

wraith spear
wicked scroll
#

I'm not sure what that means? I guess I'm mostly suggesting that you manually tick your battle so that you can just not do that instead of having to implement some kind of pausable interface everywhere

#

well your world, but really both

#

you probably want the world simulation to still run to some degree, just a lesser one

#

or maybe not, I guess in a battle usually the world is fully paused...but it's nice to have the option in case it comes up

wraith spear
round violet
outer plinth
#

Hello everyone, I am attempting to Intersect a mathematical representation of a sphere (SDF) on the GPU with a ray from the GPU, however, when I assign the texture to my primitive in scene it seems as though the UVS are not wrapped correctly, anyone got any ideas?

round violet
#

is there a curve type which has a curve editor in the inspector that can support N curves inside ?
the only curve type i know that accepts more than 1 is the MinMaxCurve one (locked to 2 curves)

tribal monolith
#

Hello, sorry if this is not the channel for this question, however:
I am working on a project, where I try to emulate a user's desktop as closely as possible and right now I need the System.Drawing library for getting icons and some other stuff.
For this to work I have switched my "API Compatibility Level" to .NET Framework from .NET Standart 2.1.
The only platform I plan to support is Windows.
Is this an okay solution?

#

The other solution I had is to just call a new process -> powershell

violet nymph
grizzled ferry
#

Hey, I know this is absolutely subjective but is it standard to have a comment explaining the method inside, or should it be just before its definition?

grizzled ferry
violet nymph
grizzled ferry
tribal monolith
tribal monolith
#

Okay, thank you so much!! koteLove

eager tundra
tribal monolith
#

Hello, I am trying to extract icons form some files and for debugging save them in a file.
When I put this in powershell, it works
[System.Drawing.Icon]::ExtractAssociatedIcon(*file*).ToBitmap().Save(*saveFile*, [System.Drawing.Imaging.ImageFormat]::Png)
however when I try to do this in Unity
Icon.ExtractAssociatedIcon(*file*).ToBitmap().Save(*saveFile*, ImageFormat.Png);
It will save the icon as a random picture

#

Does anyone know why this happens?

steady bobcat
#

wtf thats the mono logo

next heath
#

how do y'all prefer using attributes? (number 2 is me)
1:

[HideInInspector]
public bool CertainlyABoolean = true;

2:

[HideInInspector] public bool CertainlyABoolean = true;
rigid island
next heath
rigid island
#

yeah 1 is preferable for other inspector attributes like Range, Header,ContextMenu etc.. I guess I only use 2 for SerializeField now that I think about it.. UnityChanLOL

steady bobcat
#

No 1 all the way

abstract inlet
vestal arch
abstract inlet
#

oooo i seee

abstract inlet
#

thank you very much for your help!! the script's been ironed out i think :]

lucid brook
#

does unity have C# 11 support?

#

damn

#

So next question, does anyone know of a way to do something like this in C# 9?

List<int> list = new List<int>() { 9, 6, 5 };
switch (list)
{
    case List<int> _ when Test is [9, 6, 5]:
        print("Do thing");
        break;

    case List<int> _ when Test is [2, 4, 8]:
        print("Do different thing");
        break;
}
chilly surge
#

You just have to write it out the old fashion way.

lucid brook
#

Damn, and here I was thinking I could be fancy about it.

chilly surge
#

Similar code can work if you can change it to a tuple.

lucid brook
#

a tuple?

#

let me google that one lol

#

no I don't think that is going to work for what I'm doing

chilly surge
#

What are you doing?

#

On mobile, but you very well could write similar code with tuple:

if (list.Count == 3)
{
  switch ((list[0], list[1], list[2]))
  {
    case (9, 6, 5):
      // ...
      break;
    case (2, 4, 8):
      // ...
      break;
  }
}
#

Better yet if you have the 3 elements already then you don't need the list at all just to do pattern matching.

lucid brook
chilly surge
#

You haven't explained what you are trying to do at all so we don't know what the list is for.

#

What I meant was that, if your idea was "I have three numbers and I want to check them, so I make a list then use pattern matching for it" then you wouldn't need that list at all, just use a tuple.

lucid brook
#

Like: stomach > chest > head will trigger an uppercut

#

So I use the list to add a specific input like 2 (for the chest) and start a timer that removes that input from the list after a set time

#

if the list contains 3 items I check what they are and trigger a special attack

chilly surge
#

Sounds like you already have a list, then yeah makes sense to want to use pattern matching on it directly.

#

But yeah Unity is still on C# 9 so no collection patterns, but you can do the tuple thing.

lucid brook
#

yeah that works great. before today I had just never heard of tuples.

#

but thank you for the help!

chilly surge
#

(Maybe consider using a queue instead of list, although it's pretty minor)

swift falcon
#

Did i do this right

#

idk if im slow but im not able to look around still would i have to mess with inputs or smt of the sort

rigid island
swift falcon
rocky steppe
#

Hello!

#

I had a question.

#

I have a question, I'm trying to learn C# & Unity and then blender, I'm doing all of this for VR application based development for psychology and mental health applications. I come from a Java based background, I know in Java all of structured programming and very basic OOP, also I know C# structured programming, I have a course that I payed for from Code Monkey, this I go through learn C# & Unity and have him teach me VR application in Unity, I was wondering with my expereince I'm doing this 3 hrs/day and in two weeks or so could I write proper code, knowing where to start, of course I'll have to use Google for errors, but for anything else. Also, can someone also send me the best VR Unity Course. In a week or two I would want to be able to work on mini-projects and planning on writing the pre-draft of my project.

#

Thank you.

rigid island
swift falcon
#

thanks nav

ocean hollow
rocky steppe
#

Thank you sir.

vestal arch
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

lone turret
#

Unity allows you to make custom geometry for sprites via Sprite.OverrideGeomerty and allows you to set custom uvs for said geometry by Sprite.SetVertexAttribute. But unless I'm missing something unity won't let you create a sprite with a rect outside the bounds of its texture, which could be a completely reasonable thing to do if you're using custom uvs.

The only working solution I have to this is making a larger texture with a bunch of wasted space so it fits my rect. Is there any way I can manually set the sprite rect? This has to be a sprite unfortunatly, I can't get away with a mesh

steady bobcat
#

you can set the sorting layer on mesh renderers too so im not sure what other functional differences a sprite renderer has

round violet
#

im using ScreenPointToRay with a camera and im wondering how i should make overlay UI block the raycast

placid summit
#

has anyone done runtime node editors?There is UnityRuntimeNodeEditor on github I looked at but it is very limited out of the box, a starting point perhaps

thorn crane
#

how to create main menu ?

rigid island
round violet
#

doesnt seem to work, at least when called in a input action callback

rigid island
round violet
#

i get this warning Calling IsPointerOverGameObject() from within event processing (such as from InputAction callbacks) will not work as expected; it will query UI state from the last frame when i touch, but since it queries the UI of last frame it should still work since its not moving

eager tundra
rigid island
round violet
steady bobcat
#

Re use 1 list but the example above should be good

rigid island
#

ya just make list a field

eager tundra
round violet
#

yes thats why i need something else before

steady bobcat
#

Yea, the example above. You have to use that to first check if the screen pos would hit anything in the UI before continuing with your physics raycast.

steady bobcat
round violet
#

wdym by that ?

rigid island
#

i will change the example just incase someone else takes it lol

round violet
#

oh okay

rigid island
round violet
#

saw it

#

unity could of make it an out as well

#

while we are at it, what should be the proper way to scale a touch delta with screen res ?

rigid island
steady bobcat
#

out means nothing here, its a ref pass anyway
The point is to not do new List() each call

#

Its already designed to avoid pointless allocation

hexed pecan
round violet
hexed pecan
#

It would allocate a new one and replace it

round violet
#

fwiw, im used to c++ & out params, not sure if in c# its the exact same behavior

steady bobcat
#

Yea we cant heap allocate and then delete it right after 😭

round violet
steady bobcat
#

e.g. List<string> is std::vector<std::string>*

round violet
#

yeah i always hated the c# synthax for that

vestal arch
#

(c# doesn't have syntax for that?)

round violet
#

i dont like having some implicit stuff like that

#

let me type * or & if its a ref or ptr

vestal arch
#

ah, gotcha, yeah

steady bobcat
#

there is stackalloc which can be used with Span<> to allocate on the stack instead but its limited in use

vestal arch
#

higher level languages tend to do that
less for you to control, more implicit stuff

steady bobcat
#

managed languages you mean

vestal arch
#

it becomes more about ref vs value types rather than like, direct values, pointers to the stack, pointers to the heap

vestal arch
#

memory management is just one aspect of that

steady bobcat
#

true true

round violet
#

i dont know if ref on classes or list are allowed

#

since it seems that its implicit

vestal arch
#

pretty sure not, since they're, yknow, already refs

hexed pecan
#

You can use ref with classes

vestal arch
#

ref is used for value types

hexed pecan
#

For example it can replace a reference from the calling scope

somber nacelle
#

it's just mostly pointless with a list since that can just be cleared and Add called in it which is going to be cheaper than allocating a new list (at least memory wise)

hexed pecan
#

I do have some methods that allocate the list if a null one is passed in

vestal arch
#

oh so ref is basically just a & from the caller and a * from the callee (in c/c++ terms)

hexed pecan
#

But mostly yeah what boxfriend said

round violet
#

ref must be valid in c# to ?

vestal arch
#

i mean ref in c# is the equivalent of passing in a variable pointer in c/c++

#

like you would for scanf

atomic comet
#

Hey all, I'm trying to find all the cameras in my scene and sort them lexicographically, FindObjectsByType seems to be working as it should but the sorting doesn't result in what I'm looking for, would anyone be able to point me in the right direction? Cheers

round violet
round violet
hexed pecan
round violet
#

having some functions know they have a valid ptr would be cool 🥲

vestal arch
round violet
#

sad me

eager tundra
#

you can probably use nullable references to help with that

vestal arch
#

would that work with unity

#

since unity has a fake nonnull thing

eager tundra
#

yeah, there's this pitfall with Unity objects

steady bobcat
#

Yea just dont. Use nullable with value types and thats it.
New c# does make nullability more obvious and something you can require or not.

void ledge
#

Hello guys. I am trying to create a third-person controller by following this tutorial:
https://www.youtube.com/watch?v=YiNCqmAF3Lc&list=PLD_vBJjpCwJsqpD8QRPNPMfVUpPFLVGg4&index=4

Everything is working fine except for the animator. For some reason, when the character switch from idle->run, it would work for the first few second after I press play, then stop working and stuck at the beginning of the run animation.

I checked the value from the BlendTree and noticed the value kept changing in e-10 scale (e.g. 3.564695e-10). Not sure whether this is the cause or now. I would really apperciate if anyone can provide some advice regarding how to fix it🥹

In this video (Episode 3) we implement movement animations for our player via animator values, that will be changed based on our input!

► PLAYER MODEL & ANIMATIONS
https://drive.google.com/drive/folders/1HcjzIXnUDMxsd5Pj6s-iFMmuPKr5SajN?usp=sharing

► JOIN OUR DISCORD
https://discord.gg/jzmEVx5

► SUPPORT ME ON PATREON!
http://www.patr...

▶ Play video
primal gale
#

can I make an A* AI system that would work across different simple 2d maps or would I have to manually create a system for each scene?

somber nacelle
#

you can make anything you have the skill to make

steady moat
primal gale
#

luckily I have the intelligence of a newborn baby

#

time to get coding

steady moat
#

I mean, do you even know where to start ?

primal gale
#

no

#

I might aswell try to learn through brackeys for the things I dont know such as AI

#

ill give it a try

steady moat
#

I do not think you will find anything about creating A* through multiple level though.

#

It would be more effient to find an alternative solution

vestal arch
#

i don't think that's what they're asking about?

#

a system that works across multiple scenes, not works through multiple scenes

steady moat
#

What is the difference ?

vestal arch
#

i don't think he's asking about navigating like, across scene transition boundaries

primal gale
#

yeah I just want to have a system where I do not need to manually place waypoints or whatever through rooms

vestal arch
#

just a single system that works in multiple scenes

primal gale
#

probably gonna use a navmesh

vestal arch
#

whether that's a navmesh or waypoints

primal gale
#

so lets say I implement a navmesh, would I still have to draw waypoints around simple obstacles?

#

like lets say I literally just had a box with a smaller box inside as an obstacle, I would need to place waypoints on all corners or something like that to contain the navmesh

#

Im probably gonna read up on AI and navmesh or whatever because it seems quite interesting I just know nothing about it yet

vestal arch
#

idk about navmeshes tbh

#

wouldn't you just not have the navmesh over that inner box

primal gale
#

I think so

#

from working in 3d I know it will shape itself according to the environment

#

havent tried it in 2d but surely its even simpler

somber nacelle
#

note that unity's navmesh does not work for 2d out of the box, but there are assets that make it work

primal gale
#

Ive used waypoints before for a simple enemy that will crawl around a box but for this I want my flying enemy to be able to move past obstacles in the way of the player

steady bobcat
primal gale
#

Ok one more thing, I'm using Cinemachine to add screen shake to my game, and I want to use it for multiple different things. Lets say I shoot something then my screen will shake based on the cinemachine attachment I got on me player, if I wanted different screen shake for each mmovement thing how can I directly change the variables on cinemachine so its different?

void ledge
#

it just stuck at the same pose

#

Stuck like this wherever or however I move it. It is now either idle or move with this pose

steady moat
void ledge
#

U mean this property when I am importing the animation?

#

Sorry I am new to Untiy so I am not exactly sure...

steady bobcat
#

"Loop time" = plz make my anim loop

#

you can easily debug this stuff by selecting the gameobject with the animator at runtime + observe the animator states (in animator window)

void ledge
#

ohhh

#

no wonder

#

I go it working now! Thank you both of you for helping me!!

#

much apperciated!

vestal arch
#

@primal gale fyi, physics layers are a thing if you haven't heard of them

primal gale
#

layers are too scary

vestal arch
#

(if it makes sense for your usecase)

primal gale
#

I fixed it anyways

vestal arch
#

it's basically categorizing objects

primal gale
#

yeah but you can only have 1 layer cant you

vestal arch
#

then you can say "i don't want these 2 kinds of things to interact"

vestal arch
primal gale
#

ill give it a try