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
#archived-code-general
1 messages · Page 451 of 1
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.
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
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
It's an actual 2D array with [,], not an array of arrays
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
you cant do generic stuff properly on a 2d array
Hello, Does anyone have a good yt video on a simple player controller? like moving around and looking around. ty :)
i once experienced this issue and it pushed me to only a normal array and calculate index myself
int index = (y * width) + x;
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.
does anyone know how to fix this? i want the character to still be standing up even if it's looking down or up
Dont rotate the player on its x axis
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.
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."
Gizmos from the Gizmo class use world space, is this stuff currently done in view projection?
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
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:
It's not the right channel but if you google the error message there are plenty of solutions
pretty code related to me
Try installing openssh if its not already. Is this x64?
strange. does it give more info about what tried to use it?
Oh sorry, I mean it's x64
my only idea is its linked to a newer libssl version that you have. I've experienced annoying issues before with glibc versions ✊
how?
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
mmm, I alredy install "libssl-dev" and restart the editor but nothing
try adding openssl and libcurl4
openssl has been enough for me to use libcrypto in the past (ubuntu + debian)
yay
np, my struggles with openssh have paid off 😆
@livid inlet This is a code channel, not for promotion or whatever this is. If you have a question then !ask a question.
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
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 😔
...why the link lmao
i didn't say it was a bad thing
i'm just getting war flashbacks to CRUD applications
same reason you posted a random thought
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
going to have to show the setup / scripts related to GameManager, for starters is it inside a DDOL ?
No it's not a DDOL
oki.. show scene switch scripts + game manager component
what else is there ? (the actual component aka the code)
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
use 👇 to share code btw
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
more interested in seeing how you deal with assigning a Instance to Game Manager
sounds like you might not be handling possible duplicates
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}```
how did you type this character using your keyboard?
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
i know it would be á
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
oh, so pressing the key does that?
did you not write that comment?
seems okay then..
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
I would double check the setup also you should probably steer away from AI Slop generators
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)
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
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
well ideally that code in Awake should prevent duplicates
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
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
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
Removing those lines of code doesn't fix anything though
fwiw you should change your text encoding in your IDE if you end up working with strings in other languages, at least in C++ I had an issue where my shit wasn't working right because the encoding was set to ANSI or something and it needed UTF-8
but that's minor
you probably have a zombie GameManager based on what you describe. You'd have to show GameManager, but likely you are not unsubscribing properly when the scene unloads or when GameManager is destroyed
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
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
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
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)
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
I am decently proud of a couple of the systems I put together but they for sure could be much improved
doesn't have to be, but it often is lmao
yeah same, honestly that feeling never goes away lmao
and if it does, you've either reached the pinnacle of software development or you messed up
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
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
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
sounds like your server isn't updating non-host clients
your host should just be another client btw
yeah that's a netcode issue
They are the same entities but function as separate ones
no enemy logic should be occurring clientside unless it is completely deterministic
It's kind of amusing, in a way
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
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
yeah multiplayer is always a challenge
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
i'm not planning on it anytime soon for that reason, huge pain in the ass
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"")
despite having worked on CoD I've never played it
i have no idea how the perk system works lmao
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..?
were you using an "attribute" model for stats like reload speed?
I do not know what that is
or were you just modifying the value in place
I just use good ol variables
The major issues was actually the actual reload speed and the animation being sped up properly
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
honestly i just use animancer, i'm not sure how animation speed works with other animation systems
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;
}
ah, switch statements.
mood
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
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
And fought with that decision for a few hours
Until I realized for loops exist
And just used a for loop
tbf if you're coding something like staged reloads this isn't terrible
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
...yeah this is the exact reason you want to use a class to hold stats + modifiers instead of just modifying a value in place
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;
}
i have to ask
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
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
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
int reloadAmount = Math.Min(reserveAmmo, ammoCapacity - ammo);
ammo += reloadAmount;
reserveAmmo -= reloadAmount```
well for future reference lmao
tbf this is literally how the industry works so
the todd howard memes are actually very accurate
it just works
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
yeah i mean don't sweat learning projects too much
I probably should do that
I mean it's the kind of project I'd like to take a bit further than just being a learning project
Wouldnt still be working on it otherwise
honestly my game isn't even a learning project and i still overthink everything without even performance testing it first
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
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
yeah I am
unless you've got a genuinely unique idea most people will pass up an amateur single dev game
It's like 100 bucks to upload to steam isn't it
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
yes it is, 100 usd for a steam token
i believe you do get the money back if it makes 1000 (or whatever amount they said)
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
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
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
it's also rough in art 
it's rough in general especially in the current landscape with all the layoffs
that sucks
I just want to start working right now I need that experience
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
I've often looked at those and rarely do they need entry/junior level unfortunately
that's kinda the other issue with the job market in general, nobody wants to hire new grads/entry level
I'm starting an internship next week so at best I could have a job after that is over but that is highly unlikely
oh shit, nice. good luck, some places do internships to scout new hires tbh
...others do it for tax breaks
It's a master's internship so idk if they want new people
how should I go about starting a coroutine from a script that is not monobehaviour?
you have to start it from a monobehaviour
choose one related to your object, or one that doesnt get destroyed, and just call StartCoroutine on it
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
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
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
is there a way to run heavy computation on a thread separate from the UI that is considered "better" in unity? For c# in general I'm seeing multiple options like async, System.Threading, and System.ComponentModel.BackgroundWorker
You can run any other code in Other threads as long as its not an operation that requires Main Thread, UI is one of them usually
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
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
does someone know real quick if Init() or Awake() happens first?
I can't find Unity docs on Init()
because it doesn't exist?
are you confusing Start & Awake?
Init() happens on prefab creation is all I understand but it does exist
what do you mean on prefab creation exactly ?
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...?
where are you getting this info from ?
and what exactly are you trying to do
this is a "framework" someone created, its not a unityengine thing
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
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 👀
by "create prefab" are you talking about spawning / instantiating a Gameobject from prefab ?
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)
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
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
Yes the Init
"the init"
no idea what you mean literally no such function exists until you create one
Instantiation and Initialization, different things
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
Project Settings > Script Execution Order
thanks
LateUpdate is probably better in this situation as it's more explicit
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
Unity 2022.3.51
Splines 2.6.1
there is version 2.8.1 actually which has nice extras (2.7.1 added spline extrude profiles for roads!)
when creating a new mono instance with the new keyword, is it attached to a gameobject ? if yes, how does it determine which one ?
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
Its not and you shouldn't do this for this reason. Only use AddComponent<>()
How broken do those instances get? I assume a lot of course but curious if stuff like a coroutine would still be managed correctly
I presume StartCoroutine() would throw an error as Unity is who is continuing their execution over time
async functions would work still
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
lives via activator.createinstance
even calling the gameObject getter throws an exception tho lol
(and coroutines unfortunately do not work)
dunno what you are trying to do but stop 😆
the best way to learn is to fuck around and find out 😄
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)
is there a way to reference a prefab with a specific script on it (root) ?
and not a plain GameObject
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
whats the meta attribute for that ?
what do you mean
im talking about a serialized field that only accepts a GO that has a given component
yeah just the type
well it doesnt show anything if i just put the type
it should? is the type inheriting from MonoBehaviour?
[SerializeField]
ParticleSystem particleSystem;
yeah
you are over thinking it
the script lives on another prefab in the Assets
yup
As said already, if the component is on the root of the Prefab, you can drag the prefab asset to the field and it works.
Coolscript instance = Instantiate().GetComponent<Coolscript>();
you mean this?
well this is not picking the projects prefabs wit hthe script at the root
you have to manually drag and drop it
yeah the default search is dumb
you cant put stuff from the hierarchy on a prefab
not what they are asking
@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
And just in case you don’t know this also means you can instantiate and return the type rather than gameobject
Saves the getcomponenting
thats good to know
what happens if i try to edit the prefab ? would unity prevent it or will i just edit the asset ?
as in edit it via code?
yeah
for example, from the BulletPrefab var
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()
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?
You have an infinite loop. If you can't find it yourself you'll have to show the code
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
Thread.Sleep pauses the entire game. You'll have to use coroutines or async or just check the condition in Update
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
There are other ways to make one-off events in Update but coroutines are the easiest in this case
async and coroutines are the way to go for this
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)
i found this https://www.reddit.com/r/Unity3D/comments/eye8yk/performance_results_collider_vs_overlap_test/ but its 5 years ago
2D or 3D?
3D
They don't show the source code, but what might be happening here is they're using the old SphereCast methods, whereas SphereCastNonAlloc is faster, for obvious reasons.
You'd have to test it yourself to find out which is faster
SpherecastCommand or RaycastCommand are options too
This would also give you continuous detection so you dont get tunneling (projectiles missing collisions at high speeds)
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 ?
As long as it's a job that completes within the frame, yes.
well since its async it could take more than a frame ?
i dont mind receiving the job result a few frames late
Hello quick question, For small turn-based RPG, is it better to create a persistent Scene that has Managers, PlayerData, Camera, etc..
Need a dictionary for an editor tool and I remember that Unity does have a SerializableDictionary but I'm not seeing it serialize any data. I'm specifically talking about this one: https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@14.0/api/UnityEngine.Rendering.SerializedDictionary-2.html
Not enitrely sure why it's in the Rendering namespace but I'm kinda feeling it's not made to serialize monos
Looking just for conformation before I just implement my own
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.
I'm so confused why it's in the render namespace
they must be using it for some modules inside of it
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?
If the generic type has a constraint yeah, but otherwise you need those SerializeReferences
This is no longer true, not since Unity 2020.1.
https://discussions.unity.com/t/generics-serialization/758530
Yes, someone mentioned that. It's still in the docs though
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
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?
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
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
True, but I got a voxel tool that's got about 500k entries in it
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?
yeah i was thinking that. I may just end up writing my own serialization I guess if it comes down to it
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
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 
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)
Do you do any heavy work on OnApplicationQuit()? Do you have any crash dumps/logs you can look at?
crashes completely on others
-# well it did quit
Worth noting that some platform requires you to not use Application.Quit. No idea for SteamDeck.
The logs look normal (wanted to post the section here but its a tad painful to get it from the steamdeck with my current setup).
The behavior isnt though: its basically a frozen screen that only resolves after putting the deck in and out of standby.
I only knew this about mobile and web. But thanks for the info, Ill try and see if there are references to this in the docs or forums.
You can use desktop mode to make it easier (and to see if it acts differently). If its using proton with a windows build you just need to locate the wine prefix then locate the relevent files
Thanks, Ill try that.
Its using a standalone linux build.
cool then may be easier. You can try starting the process and piping the std out to a file.
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 🙃
In game mode its using valves gamescope compositor and it may be miss behaving somehow
https://wiki.archlinux.org/title/Gamescope
I bet using a windows build via proton will just magically fix this issue
it's 1000 times easier to serialize a struct and use a list of structs than a dict
Why not use both in conjunction?
i mean, not really?
you could just use a premade package for nice editor support, like the serializeddictionary asset
As I mentioned, the serialize dictionary implementations are fake
you need to constantly refresh the dictionary which makes the whole quick lookup pointless
^ 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.
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
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)
How so? Are you only doing one look up per deserialization?
wdym by this?
also it doesn't matter that they aren't actually dicts for most cases does it
it's there for dx, not perf
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
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"
Dictionaries use a private struct Entry to store everything from what I can see but I dont see a way to get them without reflection:
https://github.com/microsoft/referencesource/blob/master/mscorlib/system/collections/generic/dictionary.cs#L61-L66
So this is why its just done in a lists to keep keys and values
why would you need to?
overcome the cost of creating a new dictionary on de serialize
Im just trying to point out why it sucks rn
so the whole concern here is just, perf on deserialization?
why is this an issue lol
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
do these have a 3d/2d position?
3d grid
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
It's an editor tool ;p
you could have fixed this ages ago with kd trees as you can serialize these as is
gotcha, but how does this equate to "serialized dictionary bad"
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?
you can convert the data later, rn you are concerned about actually storing it...
or has this entire convo been in the context of your tool the whole time without me realizing lol
Because ultimately the use case for dictionaries are usually hundreds of thousands of elements, otherwise there's no reason not to use a list really. But the purpose of the dictionary is less of a thing here if you're going to have to iterate to replace the keys each time you want to seralize the state
this is in editor rn hence unity serialization
Yeah cause otherwise a runtime dictionary would work fine.
But got to deal with Unity's limitations
lmao what? dictionaries are commonly used for much smaller spaces, just so there's a nice interface for a mapping
like i said: for dx, not for perf
Id never use a dictionary for 500k voxels 😆
I mean I use them everywhere too, but this is one the one use case where they would shine
cool, but that still doesn't mean serialized dictionaries are inherently bad lmao
Dictionary lookups are really fast
Voxel[,] voxels = new Voxel[100,100]; //Do this
Dictionary<Vector3Int, Voxel> voxelsDict //Not this
Obviously you wouldn’t use them for voxels
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
Nor would I use an array
It's an infinite grid btw
Octrees are more efficient for voxels. Otherwise you’re just storing a bunch of empty data.
So you’re going to serialize 500,000 dictionary entries in a YAML document?
Yeah that's another problem. I guess I might as well just write my own serialization
Definitely a better option here
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
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.
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
- Use layer based collisions
- Use Physics2D.IgnoreCollision
either of those will work
got this but it still collides
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
Yeah you have to do it with the actual instance. Not with the prefab. Prefabs don't exist in the game world.
OnTriggerEnter2D is too late
you do it when you spawn the bullet
tried that still dont work
I can try layer collision
it works if you do it right ¯_(ツ)_/¯
presumably something is wrong about your code or your setup.
ive just got this simple code
takes in the rigidbody of the enemy that is firing, and the bullet that was just instantiated
you're still trying to ignore the collision on the prefab
bullet is your prefab
but I thought it becomes real when its instantiated
No
ah
bullet is always the prefab
instantiate returns the newly created object
you are ignoring that currently
it doesn't become real
you create a new, real version, based on the prefab
so how would I call the real bullet
Capture the return from Instantiate in a variable
so you can do things to it
var newBullet = Instantiate(bullet, ...);
alright thanks it works now
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.
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
depends what kind of outline you need. Just some post processing effect or texture?
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
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.
Stencil shader?
Do you need it in CPU world or for rendering something
holy heck i managed to make the dialoguebox thing actually work! hooray!
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?
You wouldnt be able to use animations here, itd have to be some custom solution. It does kinda sound like an active ragdoll except not a human. If you want every piece to respect physics, then maybe look into using joints to connect everything. Otherwise you'll have to code this yourself
Mmhh... Maybe I could put some sort of trackers on parts of an animated (but not rendered) object, and just make the pieces try to approach their coordinates to these trackers
But maybe there is a simpler way...
That is mostly how active ragdolls work
I see! Thanks for the help
@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.
Ye... but why not just call the TextFormating directly as I am doing already?
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
- For when you do want certain content to be able to manipulate their prefered color, using the same system everywhere is nice and consistent
- 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
ColorPalettethe GameManager references. - In the even you wanted specific associated icons to go along with this color coding, you could store said icons in the
ScriptableColorscript, which is an example of how easy this would be to expand upon.
I am already adding icons on the TextFormating script along with other fucntionalities. Here: https://pastecode.io/s/a1y4igss
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
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
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
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
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
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
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 😄
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
You can calculate it from the CPU time. e.g. for 16ms -> 1/0.016
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
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
by "here" i mean the CPU usage window
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
are you just trying to see the exact frame time of the current frame?
It says it in this area bottom middle
If you're clicking on the correct graph
and also if you hover the top area
yeah
and also if you select the highlights area in the top left
do you know if there is a way to make the physics debug work for this ?
im also wondering if this also get the inital overlap
welp i think i got half of my answer, OverlapSphereCommand exists
this will give me an array with 4 springs in it right ?
3 springs
indexing starts from zero, count strats from 1
an array with space for 3 springs, if Spring is a class it starts out with 3 nulls
count also starts from 0
fair enough
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
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
Thank you
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...
if you write it as DPON.Utils.Extensions.IsNull(whatever) what happens?
Hmm, it says that type/namespace Extensions does not exist in DPON.Utils...
Could it be that the file is somehow not "seen"/referenced by its .asmdef?
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?
Yes
how about the platform settings on the asmdef?
Any platform is ticked on both .asmdef containing Extensions and the one using it
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
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
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 :]
A tool for sharing your source code with the world!
in general: worry about perf when it becomes a problem
worry more about the readability/maintainability and structure
from a quick glance I saw you are grabbing the Rigidbody here
rb2d = GetComponent<Rigidbody2D>();
so why are you using GetComponent again in later parts of the code?
GetComponent<Rigidbody2D>().gravityScale += gravityScale;
you should use your rb2d value
in general GetComponent is quite expensive, its alright to use it in Awake/Start but then stick to using that cache variable
nah getcomponents are cheap
just expensive in comparison to caching them
more importantly, writing GetComponent everywhere is horrible for readability 😛
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
Why is PlatformTrigger being called with a tiny delay?
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
Ah
that part was tricky because I spent like an hour trying to work with a coroutine & waitforseconds but it just wasn’t working 
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 
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
(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);
! 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 ;
🤨 could you clarify what you mean by that? what code was triggering that error?
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
gotcha! yeah for some reason the tutorial i was using specified +=
technically a top down, but i modified code i was more familiar with that mightve been more suited to a diff structure
what's with the gravity thing then? you wouldn't have gravity in the Y- direction for a top-down perspective
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
you usually wouldn't really have jumping as a core movement mechanic in a top-down game
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
like, it's in 2d, right? so jumping and "vertical" movement both go on the Y axis
checks out! to clarify (since i used them interchangeably) it's just dashing forwards for now and not actually jumping
ah seems like that's in 3/4 perspective so there is some sense of going in the Z axis
yes! or at least the illusion of it lol
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
it seems to work as-is, could you elaborate on what you mean/what needs to change in the current code?
well, what do your platform colliders look like? is it just a full boxcollider2d trigger across the entire platform?
yes i think so!
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
ahhh i see what you mean
that illusion of height would have to exist separately from the rigidbody
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
so perhaps an issue for future self lol
but in the meantime - perhaps you just don't need gravity at all
can you check distance between objects using raycast?
Google it next time, it's faster
Literally just "Unity raycast distance"
first result
oh why do you think so?
it is for falling from the platform
ahhh i see
either way ty yall for your advice!! super appreciated
oh yes forgot to reply to this specifically, i'm not sure, i don't remember the specific line but else works now so all's well that ends well lmao
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
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
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
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
Invoke has += gravityScale
while Coroutine has = gravityScale
hmm I gave it a shot but I think I'm messing up somewhere https://paste.mod.gg/arlpunilxiuq/0
A tool for sharing your source code with the world!
why did you put it inside the Input.Space section? now it wounld never fall unless you dash
ah yeah i've tested around and while it'd affect the invoke when i change it to = instead of +=, it doesnt change when i do it in the coroutine
beeecause that was the advice lmao
oh
the wait would be outside the conditional - you would wait then check
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
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
uhhh you might have to draw it out for me i don't know what you mean by the far side of platforms lol
like the "top" of the platform
the side that you go off of at the start of this video
yeah, if you're making a top-down it doesnt make sense to fall in the Y axis
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
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
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 
Copied your script into my project and it works just fine with the +=
use this one again and just chnage it to:
rb2d.gravityScale += gravityScale;
the newest would only increase gravity as long as you kept holding space
well, it works, but i think the real issue is moving by setting velocity directly
ah yeah true, that should be disabled while dashing
i did notice that but i forgot to mention it 😔
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
not really, no
that would break collision
hmm, thats a tricky issue
i guess just increase gravityScale to 10 or something, that worked for me too
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.
or you could just do this lmao
i return! how do i do this lol
yeah doing that didn't have a visible effect unfort
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
So what's the overall problem? How to modify a prefab instance inside of a scene without having to save the scene? Not likely, but you could consider using a prefab variant to make unique prefab instances while keeping it off-scene.
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
ok hmmrmgnhm. ill try it out lmao i'm far less experienced in enum states so wish me luck LOL
you could just do the first one lol
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
no, this is about generating GUIDs outside of the scene.
i could modify this addon to let me generate them in prefabs but that will cause more problems elsewhere
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
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
Best thing to do then is generate your own IDs then. You can also create prefabs like a PrefabLookup table that incorporates these prefabs
Throw it on a load scene as a singleton to reference
If it's a unique prefab instance then prefab variant or SO instance
mmm yeah. like i could make a Guid component but for prefabs...
with a big warning like "this prefab should only be instanciated once!"
enum state just makes it easier to ensure something is in a specific state instead of a bool which could potentially have multiple bools be true when not desired
spaghetti happens more with referencing, not bool/state management
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
ty for everyone's help so far!
<@&502884371011731486>
!ban 1143311282108379216 ad spam
aeirik. was banned.
Movement doesn't need to be a coroutine here
in fact it delays the logic by a frame lol
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
OUGHH yeah ok when I get more laptop power I’m gonna go sniff around unity learn again 
also you never need x == true or x == false, you can just use x or !x respectively
oh I did not know that
also @abstract inlet am i understanding it right that you want gravity to not apply during the dash?
so like. just the bool’s name default true? and then !name is false?
yess
then why isn't that coupled lol
no, that's not how variables work
when you access a variable, it evaluates to its value, and that value's type matches the variable's type
booleans are yes/no for computers, so conditionals always use booleans
==, !=, >, <, >=, <=, these are all relational operators that evaluate to booleans
uuuu i don’t know what that. Means.
the logic for disabling gravity and the logic for dashing is separated, even though they should be logically linked
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)?
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
oh I’m not sure what you meant with “also you never need x == true or x == false, you can just use x or !x respectively”, could you clarify?
i'm not suggesting to link gravity as a whole with dashing, i'm referring to specifically disabling gravity during the duration of the dash
I was just saying if you were having trouble referencing prefabs cross scenes you can make a singleton prefab manager, but I misunderstood you and this isn't a cross-scene reference problem
-# on that note, shouldn't dashLength be dashDuration?
OH so like just directly changing the float value (?)
for any bool x: x, x == true, x != false are completely equivalent, and !x, x == false, x != true are completely equivalent
in my defense I was following a tutorial for that lol
you're already directly changing the value...?
isss that not how I would disable gravity during the dash?
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;
- }
pristine diff display
WOAH 
I’ll be sure to try it out later tysm you didn’t have to plug it all out like this 
Wow discord handles diffs properly apparently
yeah you can use diff as the language code for a code block
woah that diff looks sick!
does unity have a way to draw a an arrow in debug?
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
i see, thank you 😄
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
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
vertx offers more tools, including a better text label https://github.com/vertxxyz/Vertx.Debugging
i assume that update transforms is slower if my object has a parent ?
What do you mean with "update transforms"?
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.
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.
discord uses highlightjs which supports a ton of formats, can google it
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;
normalization just guarantees that the vector has a length of 1. It's not supposed to "slow" anything.
Well everything feels fast. Even with low float variables
Must be your CurrentSpeed then.🤷♂️
Or whatever you do with m_MovementDirection later on.
so maybe debug it? Okay
on top of what dlich said, the whole if statement logic in the middle isn't needed at all.
your error might not even be related to this code. it could be pretty much anywhere in regards to how you move, like maybe you arent using deltaTime
yeah im not but if I do it makes the player move EXTRA SLOW
like at a snail's pace
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
Alright I fixed it. I removed the if else normalization, made CurrentSpeed *= 0.7f and added Time.deltatime
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
Okay but now my player can't jump
then that would imply you arent properly summing all the movements you want into one final vector
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
I do need that .1f. I tried deleting it and I went high in the air
idk how but i did
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
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?
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
All of the shared code like the party data is being handled by a bootstrapper that is always loaded, so I don't think that it would add a lot to always load them both, aside from faster loading times. Because of that, I think the greatest "pro" isn't really used
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
The world would be fully paused, and the two should exist as separate entities. They use different sprites as well. I'm afraid that allowing "overlap" will muddy the code base, as I'll have to think of everything that's loaded when making changes to both overworld and combat code.
edit the position, rotation or scale of a transform
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?
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)
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
Changing the API Compatibility level should be completely fine as long as everything still works, but that's on you to check
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?
Aight, thank you so much! 
i mean, would you say this is a better option?
Personal preference, whatever works for you, there's no "better option", honestly in the method sounds better to me, others might prefer on top of it, really about what you find better
alr, thank you for your opinion and advice!
I apologize for another tag, but I just need to confirm that using libs like Windows.Win32 and aforementioned System.Drawing is completely fine as long as it works?
It should be
Okay, thank you so much!! 
the standard is to have a method summary https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
most IDEs will be able to read and provide functionality on top of it
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?
wtf thats the mono logo
how do y'all prefer using attributes? (number 2 is me)
1:
[HideInInspector]
public bool CertainlyABoolean = true;
2:
[HideInInspector] public bool CertainlyABoolean = true;
usually 2 for fields though, for serialzable class for example I prefer 1.
additionally for me, if i'm using unity's [Header] attribute i prefer using number 1
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.. 
No 1 all the way
i return again! I was wondering, what does rb2d.gravityScale = onPlatform ? 0f : gravityScale; mean? Like syntax/purpose-wise, with the "?" and ":" between onPlatform & gravityScale? thank you!
it's called a ternary or conditional operator (ternary referring to its 3 operands)
it's basically a short version of an if/else
that example there is equivalent to:
if (onPlatform) {
rb2d.gravityScale = 0f;
} else {
rb2d.gravityScale = gravityScale;
}
oooo i seee
thank you very much for your help!! the script's been ironed out i think :]
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;
}
You just have to write it out the old fashion way.
Damn, and here I was thinking I could be fancy about it.
Similar code can work if you can change it to a tuple.
a tuple?
let me google that one lol
no I don't think that is going to work for what I'm doing
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.
oh? ok I misunderstood the use case for tuples. that totally works
what do you mean by this?
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.
I am playing around with a VR combat idea, a lot of games do a full physics thing with active ragdolls but I want to go a different route. I was thinking of giving the player 3 areas to punch on an enemy, stomach, chest and head. These will kinda act as buttons the player presses/punches and based on which order they punch them in they get a different follow up attack.
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
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.
yeah that works great. before today I had just never heard of tuples.
but thank you for the help!
(Maybe consider using a queue instead of list, although it's pretty minor)
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
mouse inputs should not be multiplied by delta time
Ahh so get rid of that then or change it
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.
yes thats what should not be multiplied means, you remove it
thanks nav
There is a dedicated #🥽┃virtual-reality channel, so you're aware
Thank you sir.
check out !learn for resources
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
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
you can set the sorting layer on mesh renderers too so im not sure what other functional differences a sprite renderer has
im using ScreenPointToRay with a camera and im wondering how i should make overlay UI block the raycast
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
how to create main menu ?
surely there is plenty of tutorials on this subject...
Unity UI + A script that manages the actions on buttons
doesnt seem to work, at least when called in a input action callback
has worked for me before, show what you tried / setup. If anything use the actual raycast from event system and check the results
i have a input action that fire an event on Touch
i get the touch position with Input.GetTouch(0).position
then i use this to get what i hit
Ray ray = cameraRef.ScreenPointToRay(screenPosition);
if (Physics.Raycast(ray, out RaycastHit hit))
what i simply added is a if (!EventSystem.current.IsPointerOverGameObject()) before calling the raycast code
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
I think you want to use a GraphicsRaycaster there, not Physics.Raycast
maybe youcan do something like this ?
private List<RaycastResult> uiRayResults = new();
bool IsPointerOverUI()
{
PointerEventData eventData = new(EventSystem.current);
eventData.position = Input.mousePosition;
EventSystem.current.RaycastAll(eventData, uiRayResults);
return uiRayResults.Count > 0;
}```
i still have to raycast for my thing, but i want to prevent it if the user clicked on the UI and not in the world
Re use 1 list but the example above should be good
ya just make list a field
yeah, nav's example should be good
but UIs won't block Physics.Raycast
yes thats why i need something else before
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.
perfect, thanks
(it works)
🙏 plz make sure you change it to use 1 list instead of a new one each time
wdym by that ?
i will change the example just incase someone else takes it lol
oh okay
make results a field so it doesn't create a new list each time
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 ?
:\ was hoping an array version RaycastAllNonAlloc like Physics one
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
If it returned an out list then would always make a new list so it's better to have it passed in to avoid allocation
you could still pass a list made outside the function scope ?
It would allocate a new one and replace it
fwiw, im used to c++ & out params, not sure if in c# its the exact same behavior
Yea we cant heap allocate and then delete it right after 😭
i guess my understanding of the out kw wasnt the correct one
a class can be thought of as a pointer always to some heap memory
e.g. List<string> is std::vector<std::string>*
yeah i always hated the c# synthax for that
(c# doesn't have syntax for that?)
i dont like having some implicit stuff like that
let me type * or & if its a ref or ptr
ah, gotcha, yeah
there is stackalloc which can be used with Span<> to allocate on the stack instead but its limited in use
higher level languages tend to do that
less for you to control, more implicit stuff
managed languages you mean
it becomes more about ref vs value types rather than like, direct values, pointers to the stack, pointers to the heap
i mean more broadly, just in general
memory management is just one aspect of that
true true
well neverminded i switched out and ref here
i dont know if ref on classes or list are allowed
since it seems that its implicit
pretty sure not, since they're, yknow, already refs
You can use ref with classes
ref is used for value types
For example it can replace a reference from the calling scope
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)
I do have some methods that allocate the list if a null one is passed in
oh so ref is basically just a & from the caller and a * from the callee (in c/c++ terms)
But mostly yeah what boxfriend said
why a ptr ?
ref must be valid in c# to ?
i mean ref in c# is the equivalent of passing in a variable pointer in c/c++
like you would for scanf
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
yeah it was mb, i forgot that list are passed by ref implicitly
sorting is by instanced id, completely unrelated to gameobject name
For example... ```cs
private List<int> list = null;
void A()
{
InitOrClear(ref list);
// Do stuff with list
}
void InitOrClear(ref List<int> list)
{
if(list == null) list = new();
else list.Clear();
}```
is there any other keyword for the ref & keyword in c++ for c# ?
having some functions know they have a valid ptr would be cool 🥲
not that i know of
"reference type" in c#, java, js, etc is what c++ would call a pointer type, with no equivalent to c++'s "reference type"
sad me
you can probably use nullable references to help with that
yeah, there's this pitfall with Unity objects
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.
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...
Is the animation looping ?
those values are basically 0
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?
you can make anything you have the skill to make
You can if you do it intelligently
I mean, do you even know where to start ?
no
I might aswell try to learn through brackeys for the things I dont know such as AI
ill give it a try
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
i don't think that's what they're asking about?
a system that works across multiple scenes, not works through multiple scenes
What is the difference ?
i don't think he's asking about navigating like, across scene transition boundaries
yeah I just want to have a system where I do not need to manually place waypoints or whatever through rooms
just a single system that works in multiple scenes
probably gonna use a navmesh
oh yeah no you'd still need some way to inform stuff about what they can do
whether that's a navmesh or waypoints
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
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
note that unity's navmesh does not work for 2d out of the box, but there are assets that make it work
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
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?
Not really
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
Check if you set the animation to be looping.
U mean this property when I am importing the animation?
Sorry I am new to Untiy so I am not exactly sure...
"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)
ohhh
no wonder
I go it working now! Thank you both of you for helping me!!
much apperciated!
@primal gale fyi, physics layers are a thing if you haven't heard of them
layers are too scary
(if it makes sense for your usecase)
I fixed it anyways
there's not much to them
it's basically categorizing objects
yeah but you can only have 1 layer cant you
then you can say "i don't want these 2 kinds of things to interact"
on each object? yeah
ill give it a try