#archived-code-general
1 messages ยท Page 424 of 1
Do I have to set that up in the Input Action Asset menu thingy or can I use it like a method in code
I'm not really adding any new buttons on the Input Map, I just want to double tap an existing button to do a new thing
that is on your input action. please see the documentation pinned in #๐ฑ๏ธโinput-system to learn how it works
Hi,
in school I am working on a group project where we are making a game very much alike Plague Inc. I want to recreate the game's visual effect where, as the number of infected individuals in a country increases, blood drops are accumulated on the country on the map like you can see in this picture. I'm not very experienced with Unity or game making in general. How could this visual effect be achieved? Is it with a shader, by spawning game objects or something else?
Thank you in advance for any answers!
the answer is almost always shaders
could be particles + shaders, from the description, in unity 6, probably VFX Graph
Cleverly using masks can let you have the red texture "grow" to fill the whole country (via a custom shader). It can be made for each country and have a gradient to let you control how much of the country is covered by the red effect texture/something else.
but go to #archived-shaders for getting more help
Thank you for your help I will look into it before asking for more help ๐
-
Do you guys know how to export a Unity game to the Web (HTML)?
-
And how do you work as a team on the same project? Is there something built into Unity for that?
Or is it just by using version control like GitHub?
- webgl, built-in build system
- realtime isn't really feasible, version control works yeah
- build it for the #๐โweb platform

How come my score TMP textbox isn't updating only if I set its text in Start()? If I comment out that line, it works perfectly fine.
private void Start()
{
scoreDisplay.SetText("0");
}
public void UpdateScore(int score)
{
Debug.Log("Ding " + score);
scoreDisplay.SetText(score.ToString());
}```
Are you instantiating multiple copies of this object
Hello, today I tried implementing Unity LevelPlay into my project. I tried building the app to see if it works and the build failed with this error:
Resource 'style/BaseUnityGameActivityTheme' not found in AndroidManifest.xml:75,
Following the tutorial I checked Custom Main Manifest and Custom Main Gradle Template but I haven't done anything else with those. The tutorial I followed also included a workaround for an error that popped up, that made me copy paste a gradlew.bat file from the video description.
I know this is not a "code" question but I didn't know which sub-server I should have used instead.
#๐ฑโmobile <-- But you may have an old outdated android manifest that needs regenerating (backup old one, delete, tick custom manifest again and migrate changes needed back)
I don't think so. The script is living in a GameLogic object that only gets created once and only holds scripts.
I deleted it, checked the box again and tried to build the app, but I got the same error again. Did I do it wrong? Also If you want we can continue the conversation on the #๐ฑโmobile channel.
unless UpdateScore is only called once (before Start runs), I see no reason for it to not work
It's called via an Event whenever I pick up a collectible. And the debug line shows that the event is working properly.
It's just that only if I have that initial line in Start, the textbox won't ever update. If I comment it out, it works as it should.
Hey, I've been digging through the unity documentation and there doesn't seem to be some sort of line cast that's similar to boxcast (Yes, there's Physics2D.Linecast but that's not what I'm looking for)
I need it like this image below where you define a line (1), cast that in the scene until it hits a collider (4) the cast stops (2) where it intersects with the cube (3).
How can I go about this ๐ค
Why not just do a box cast?
It has a thickness to it which is in the way
Aren't you just looking for a raycast? Maybe I'm misunderstanding
Raycast is the closest to boxcast in functionality
No, because it needs to sweep a certain area, not be 1 ray
Why? But anyway there's no such thing as what you're looking for.
I'm sure you've already tried but can you set the boxcast's width to something like Mathf.Epsilon or just 0?
This might not work reliably if at all.
Yeah I wouldn't be surprised if it was jank
But setting it to a moderately small value might work
That's what I'm doing now, but 0.001, anything smaller than that and it'll just stop working
And that's not thin enough for you?
I mean, at scales beyond that, physics collision detection becomes extremely unreliable.
I can even imagine a use case you'd need that for.
i mean, that's basically what a ray is
They seem to want to cast a ray/line perpendicularly.
you want it to "sweep a certain area", but also have that area be "1d", aka, 0 thickness?
that just seems contradicting
Like a 0 thickness box cast.
Yeah, it wouldn't check for area overlap, it would check when the line would first intersect with the collider shape
oh so it's a 2d area/casting a 1d line
Essentially yeah
They only thing I can think of is casting many parallel raycasts.
what do you need such a thing for?
Yea you could step along doing them untill you get a hit
How can i make the cubes not demorph
And customers go to an available table?
I'm using rigidbody
The skewing is a result of them being a child of a non-uniform scaled object.
Can i share the source code here
you can but it's not really a code problem
it's a problem of your hierarchy being messed up
Put a log in Start and in UpdateScore. Disable collapse in your console if it's enabled. Look at the order things are printed in
It's not a code thing
private void Awake()
{
if (playerInput == null)
{
playerInput = new PlayerInput();
}
}
private void OnEnable()
{
playerInput?.Enable();
}
private void OnDisable()
{
playerInput?.Disable();
}
does anyone know why when i change to the next scene, then come back it gives me this error
Cannot find matching control scheme for Player (all control schemes are already paired to matching devices)
my player is a singleton with playerInput component inside, im using the generated C# class from playerInput as well
you dont need to put the error message into a codeblock lol
easier to read
not for me 
oh xD
Cannot find matching control scheme for Player (all control schemes are already paired to matching devices)
there you go
Is this script on the DDOL object as well? Or is this just an ordinary script in the scene?
ordinary script in the scene
part of my PlayerController script
my theory is that even tho i have a singleton player it still instantiates another playerInput
then deletes that playerInput
and unity goes to shit
Well, yes, that's how it works.
If you have a scene with a DDOL in it, that object gets created every time the scene loads
that's why you have the object destroy itself in start or awake to make it a singleton
yup thats what im doing
So, your error might be on the one that's getting destroyed. However that code works, you might want to move some things into Start instead of awake, so awake has time to self-terminate before other stuff runs
lemme give it a try
if i set it on Start() i get a missing reference error
since i also got my onEnable() function
{
playerInput?.Enable();
SceneManager.sceneLoaded += OnSceneLoaded;
JamonDialogue.EnableControls += EnableControls;
Jamon.EnableControls += EnableControls;
Jamon.DisableControls += DisableControls;
playerInput.Player.Shoot.performed += Shoot;
playerInput.Player.Shoot.canceled += Shoot;
playerInput.Player.StartRun.performed += StartRun;
playerInput.Player.Ability.performed += Shift;
playerInput.Player.Interact.performed += Interact;
}
maybe a null check here would work
did you even set playerInput?
void Start()
{
if (playerInput == null)
{
playerInput = new PlayerInput();
}
cameraShake = playerCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
}
playerInput = new PlayerInput(); or whatever your class name is?
ah k
What line gives you the null error?
Ah i see, you set it in start
76 which is the playerInput.Player.Shoot...
let get an educational link for you ๐ https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
so you know, start is after enable, but still you wonder why you get the null error?
why not set it in Awake()?
why dont you read the convo
Cause I just jumped in. guess so you took that in consideration and its not for you, sorry then
I don't know what all objects you have that are involved in your DDOL
But things that are going to need to run after the object self-terminates need to be in Start. Things that run before should be in Awake or OnEnable
what about SceneManager.sceneLoaded
You said that this script wasn't on the DDOL so changing this script wouldn't make sense
Well, if this object exists long enough for sceneLoaded to run, it won't be running Start again
yea i see
moved inputs to Start() function, working now
thanks!
The numbers are the score, the pickups are worth 2 or 10 points.
Remember that thing I said about disabling collapse
Okay, new question, how do I make it not do that?
hey, i made this code and sadly it doesnt work as it should or rather as i want it to work. the player should fall after being in the air for some time while jumping even if i dont release the jump button. sadly it does not do that and as long as i hold the jump button it gains height. i debug.loged the whole code every if statement if something gets called infinitly which it shouldnt, ive asked my friends, chatgpt, even reddit and i couldnt find the answer. Help would be much apreciated thanks!
So you do have multiple copies of this object
they're each calling Start when created and overwriting the text
Please use a paste site !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.
It's a singleton, so it really shouldn't.
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(this);
}
}```
Maybe share the full !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.
so did you log that isgrounded is always returning as you expect it to?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yes it returns false when in the air and true when on the ground. after moving left and right this is prolly the only thing that works ๐ฅฒ
Does anyone know why my movement buttons work in the editor but not in the build version on android? Im using the on-screen button component
no ?
๐ฎ
The UIManager lives in a GameLogic object alongside some other scripts (currently a static SFX Manager, and the ScoreScript), and gets called via Events from the ScoreScript.
And did you expose your values and check them all at once, so you know, whats going on when?
how could i do that the best?
cool thing
The sound effects play as it should, and the events work, so apparently it's just that the UIManager keeps calling Start() after every update.
There is so much going on in your code, its hard to follow all values in theory. so just expose the once, that affect jumps without moving left right etc. Just see, what happens to your velocity and also make sure to debug the execution order of your script to follow, what all has to be fulfilled to accept the jump button being pressed and adding velocity to your player
ok thank you. would it be possible tho to display the values in visual studio using the debugger?
This isn't a singleton
You've kind of missed the single most important word in that type declaration
you can inspect and pin things while debugging and also use the [DebuggerDisplay] or ToString to customise whats shown when first inspect a var
This is a member variable, which means every instance of this object has its own copy
So, literally nothing is preventingthis object from existing multiple times
Any chance anyone has experience with setting up a gradle template to look to an Azure DevOps artifact feed for Gradle artifacts? I am running into issues.
Yep, 'static'๐คฆโโ๏ธ
A very important word it turns out
My bad, I'm still new at this. Thanks for the help^^
Nah this is one of those errors that sneaks up on you, took me a while of looking at it to notice myself
well, hopefully I'll remember it better now^^ Thanks a bunch.
i cant find anything suspicous sadly i also spend way to much time on this i spent around 2.5 hours only trying to debug it
haha, 2.5 h is close to nothing that a bug can take of your lifetime ๐
is your velocity increasing? Or is your velocity just staying the same when you hold jump?
my velocity goes like this
it starts at -9.81 (gravity) but somehow it moves very fast down to y max falling speed (-26) as soon as i jump the velociy accelerates up until it hits 30.114... this is the velocity it keeps as long as i press the jump button. as soon as i release it it accelerates down to -26 again
private float CanMakeJump(Vector2Int start, Vector2Int target, float maxJumpPower, float gravity)
{
Vector2 startPos = new Vector2(start.x + 0.5f, start.y + 0.5f);
Vector2 targetPos = new Vector2(target.x + 0.5f, target.y + 0.5f);
float dx = targetPos.x - startPos.x;
float dy = targetPos.y - startPos.y;
float gAbs = Mathf.Abs(gravity);
float epsilon = 0.1f;
float minJumpPower = (dy > 0) ? Mathf.Sqrt(2 * gAbs * dy) : epsilon;
if (minJumpPower > maxJumpPower)
return -1f;
float dt = 0.05f;
for (float jumpPower = minJumpPower; jumpPower <= maxJumpPower; jumpPower += 0.1f)
{
float discriminant = jumpPower * jumpPower - 2 * gAbs * dy;
if (discriminant < 0)
continue;
float sqrtDiscriminant = Mathf.Sqrt(discriminant);
float T = (jumpPower + sqrtDiscriminant) / gAbs;
if (T < 0.01f)
continue;
float vx = dx / T;
bool collision = false;
for (float t = 0; t <= T; t += dt)
{
float x = startPos.x + vx * t;
float y = startPos.y + jumpPower * t - 0.5f * gAbs * t * t;
Vector2 pos = new Vector2(x, y);
Vector2Int gridPos = new Vector2Int(Mathf.FloorToInt(pos.x), Mathf.FloorToInt(pos.y));
if (_worldManager.IsSolid(gridPos.x, gridPos.y))
{
collision = true;
break;
}
}
if (!collision)
{
return jumpPower;
}
}
return -1f;
}
Hey, I'm working on a 2D grid game (think Terraria), I want to check if a monster can make jump from point A (start) to B (target).
So I'm calling this function CanMakeJump(monster.gridPos, target.gridPos, maxJumpPower, someGravityValue)
I have no clue if my formula is even right, I'm getting weird results partially because I don't know how to incorporate horizontal velocity which should be based on monster's movementSpeed statistic.
YOur description of what you want to happen and what's actually happening here isn't very clear to me
but it looks to me like you're accumulating velocity even while you're grounded (up to the max falling speed)
which is maybe the explanation for what you're seeing?
eah maybe but i have no idea how to fix it
only accumulate falling velocity while you're in the air
(not grounded)
when you're grounded, set it to 0 or a small negativevalue
A lot of your code is a bit overcomplicated as well, so it's a bit hard to read it
there's also like 3-4 different places where you accumulate gravity velocity
you should really try to consolidate that to 1
it's too confusing and error prone this way
you also weirdly cut off the beginning part of the script so it's hard to tell which variables are member variables etc and what their types are.
should i resend the whole code?
i dont understand everything neither i copied it from this tutorial: https://www.youtube.com/watch?v=zHSWG05byEc
If you don't understand anything and are just copying a tutorial, the answer is to start over or go over everything and copy it accurately
You must have simply made a mistake when copying the code
but the point of a tutorial is to learn and understand
if you're not getting any understanding out of it, the tutorial was a waste of time
rewatched and checked my code 3 times i did everything i could i think
i did understand a lot of it but not quite everything
I just don't think this is a good tutorial for a beginner
the code is way overcomplicated
it's also just... not good quality code
yeah but sadly its the only tutorial i found which explains how to make the character accelerate while moving
I'm sure hundreds of tutorials do that
thats prolly true i just wasnt able to find any
Any that use GetAxis or any that use AddForce will do it generally.
Some will also do it without either of those.
could i do it using velocity and vector2.lerp?
yes
although
Vector2.MoveTowards would be better
and if you only want to do this for the x axis you can just use rb.linearVelocityX and Mathf.MoveTowards
yk what im just gonna code a playerController based on the knowledge if learned in combination with rigidbody physics but with code i can understand
i dont want to put anymore time in this code
How can I stop my NavMesh Agents from pushing my player's Character Controller? I'm aware I can fix this using a Rigidbody based Character controller, but the project that I'm working on is using built-in Character Controller.
Character controller should be able to exclude colliders from layers to interact with
I don't want to disable collision, I just don't want the character to be pushed.
Only thing I can think of is just not making the navmesh agent zero out onto your character then
I have a class InspectableType<T> where I'm overriding the == operator.
is this valid code?
public static bool operator ==(T x, InspectableType<T> y)
{
return Compare(x.GetType(), y);
}
or will this error out on x == null?
my question is - can I run GetType on a null object if that object is of type T that isn't restricted in any way?
it will give you an NRE yes
you should do something along the lines of:
if (ReferenceEquals(x, null)) return false;
return Compare(x.GetType(), y);```
thanks! but why ReferenceEquals rather than if (x == null) or if (x is null)?
is there a difference between the 3?
I'm using x is null inside my Compare function
I think with no constraints on T, they would all be the same, but ReferenceEquals is just the most explicit in my opinion.
is null is probably identical
cool, thanks!
another question, is there a way to check if the T in
T x```
is the same child class as the T in
```cs
InspectableType<T> y```
when both are null?
T is an abstract base class, and I want to compare if the classes of the two objects (that happen to be null) are defined as the same child class of T, or different child classes of T
When they are null there's no object to check the type of
T and T are always the same compile time type
but the variable that's being passed into the == function, is defined as something, isn't it
it's defined as TChild1 or a TChild2
I want to get what it's defined as, no matter if it's null or not
At runtime it might be one of those things but the compiler only knows T
I suppose
It depends on the context of this stuff
It's hard to explian without seeing the rest of your code but presumably this code is in some base class and there are subclasses or something that are defining different Ts
in those contexts the T will be whatever you defined it as in each of those contexts
ok, new problem:
I have that exact child class that you correctly predicted I'm doing here
[Preserve]
[Serializable]
public class TutorialStageSelector : InspectableType<TutorialStage>
{
public TutorialStageSelector(Type t)
: base(t) { }
}
that's the entire class. How can I enable implicit convertion from InspectableType<TutorialStage> to TutorialStageSelector, without putting anything inside TutorialStageSelector? The reason I don't want to put anything into TutorialStageSelector, is that actually I have like 6 of those selectors with more to come, and I don't want to write the same thing in every single one
I have a function that takes in a TutorialStageSelector, and I call it from a tutorialStage, and I want to pass the argument as a simple this as parameter (I have the implicit conversion inside InspectableType done already)
right now I'm using this silly wrapper on my TutorialStage
public TutorialStageSelector ToSelector()
{
return new TutorialStageSelector(GetType());
}
that should be implicit
Oops, seems like that's illegal in C#? https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0553?f1url=%3FappId%3Droslyn%26k%3Dk(CS0553)
trying to wrap my brain around this...
What is the code you wish to be able to write that this implict conversion will achieve?
I have a quick question about coroutines:
I have class A (MonoBehaviour) that calls StartCoroutine(f())
if A is """destroyed""" (in a way that I am unsure of... my best guess is that the parent GO is destroyed), will this stop f()'s coroutine?
The running coroutine is tied to whichever MonoBehaviour StartCoroutine was called on
if that object is destroyed, all coroutines running on it will stop
note it doesn't matter where f() came from. What matters is what StartCoroutine was called on
got it, as I suspected
if you did a.StartCoroutine(b.f()); it doesn't matter what happens to b, but what happens to a matters
I have a lot of delegates and events of different types and parameters, and I want to write a cleanup method that will force unsubscribe everything from it to use during cleanup in case something didn't properly handle itself. My question is, how can I genericise this to where I could do something like ForceUnsubscribeAll(OnConnectionMade)?
public delegate void NoArgumentDelegate();
public static event NoArgumentDelegate OnConnectionMade;
public void ForceUnsubscribeAll()
{
if (OnConnectionMade != null)
foreach(System.Delegate d in OnConnectionMade.GetInvocationList())
OnConnectionMade -= d as NoArgumentDelegate;
}
I don't know what types I'd need to pass in and uses as a Generic to make this useable for every event and delegate type. Passing a parameter of type System.Delegate lets me pass in OnConnectionMade, but I can't -= it.
passing the event as a parameter wouldn't modify it properly anyway since delegates are immutable so, much like strings, when you change it a new instance is created. i don't know if you can pass an event as ref but if that is possible you could just assign null to it
doesn't OnConnectionMade = null work?
Are you trying to remove only some of the listeners?
I don't actually know. I'll give that shot and see. I'm trying to track down some dangling pointer somewhere causing the program to not shut down correctly, I wanted to be thorough while debugging to find the culprit
Nah, scorched earth
Then = null should do it ๐ค
Then I'll give that a go
assigning null is 100% the cleanest way to remove all subscribers from an event
This seems like a situation where you could use UnityEvent. https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Events.UnityEvent.html
You can pass a single generic type parameter to the delegate
Has a remove all listeners method
Nope, most of these delegates have an arbitrary number of arguments, some params, some return void, some return things, some return tuples
Oh i ser
Some of them definitely could, but mixing between the ones that can and the ones that can't would be annoying so I kept them all at the most complex type among them, which has to be event
Well a tuple would be fine but multiple parameters doesnt work unless you want to wrap them in a struct
What are you designing here
It's complicated
It's a slapdash glue between multiple legacy programs in different languages responding to a bunch of data streams that no mortal should ever have had to put in one place
Me too, I assure you
Can someone explain how can this debug.log output this text
none of the above are in any way overriden on my script
first thing I would do is add a label to this log to be sure this is what we're looking at
this is called from inside awake of a parent object, if it matters
there are no other debug logs if that's what you're asking
Does the script have any Unity Message functions that can be toggled with enabled? (Does it have a checkbox next to it in the inspector)
if OnEnable has not yet been called on that object then isActiveAndEnabled will not yet be true
like this?
oh! yea that explains it
absolutely stupid if you ask me
Oh, that's interesting. I guess internally, it sets that property in OnEnable
and since Awake runs first, it's not actually been enabled yet
interesting
https://github.com/Developer-Notes-Extension/Unity-Notes/discussions/200#discussioncomment-12123302
looks like the docs had a better hint about that at some point
is it possible to get a reference to the prefab asset an object was created from? imagine a prefab asset reference it given and I want to check every gameobject if it was created using this asset.
I want to check every gameobject if it was created using this asset
what is the purpose of this?
https://xyproblem.info
Only in the editor.
Otherwise you would need to make your own wrapper to do it
editor only is fine. how would I do that?
I wouldnt call it that tbh. I asked if smth is possible and explained what I want to do. why? why not?
well typically the why informs the how
Google Unity prefabutility
a prefab asset is given and I want to check if a game object is an instance of it. I dont see how the why would add anything to this. either Unity provides a solution or it doesnt.
ty๐
I'm making a platformer where, in order to have tight turns, I'm using a speed difference system. Here's my Run Function:
float TargetVel = InputManager.Instance.MoveInput.x * RunMaxSpeed;
float SpeedDiff = TargetVel - PlayerVel.x;
float RunAccelAmount = (Mathf.Abs(TargetVel) > 0.01f) ? RunAccelRate : RunDecelRate;
if(Mathf.Abs(TargetVel) < 0.01f && GroundNormal != Vector2.up) { RunAccelAmount = 0; }
float RunVel = Mathf.Pow(Mathf.Abs(SpeedDiff) * RunAccelAmount, VelPower) * Mathf.Sign(SpeedDiff);
PlayerVel.x += RunVel * Time.fixedDeltaTime;
PlayerVel.x = Mathf.Clamp(PlayerVel.x, -RunMaxSpeed, RunMaxSpeed);
RB.AddForce(RunVel * Vector2.right, ForceMode2D.Force);
if (Mathf.Abs(InputManager.Instance.MoveInput.x) > 0.1f && (InputManager.Instance.MoveInput.x > 0 && !FacingRight || InputManager.Instance.MoveInput.x < 0 && FacingRight)) { Flip(); }
}```
I'm not quite sure how to update Player Vel so it ONLY reflects the force applied by Run, as it is a Force and not an Impulse. I did this so it is independent from external forces like jump pads
Here is the full script but I don't think it is required for this specific issue: https://scriptbin.xyz/agejahaxas.cs
Use Scriptbin to share your code with others quickly and easily.
PlayerVel.x += RunVel * Time.fixedDeltaTime;
well the math is correct for adding the force to the PlayerVel variable, however it won't account for friction or opposing forces so your velocity may not be the same as PlayerVel even when no other forces are being applied with the AddForce method
I'm just not quite sure when to reset PlayerVel
Should I do that during ApplyFriction?
Because otherwise it will surely just compound every frame and just get massive
i mean, yeah you should probably apply your friction to PlayerVel if you are also manually applying friction, but it still won't account for external friction or collisions.
you may want to ask in #โ๏ธโphysics if there is a better way to handle this
Ohh wait that's actually smart
Because then I can make PlayerVel lerp to 0 constantly, and Run increases it to a positive value, and Friction decreases it to a negative value
I'll try that out RN
Does anybody have good resources to learn the Finite State Machine pattern?
I just can't wrap my head around it
I've seen a ton of tutorials and videos that tackle it in different ways
Be it using enums, base classes or interfaces
I just can't apply it to an actual project
if you've already seen a ton of tutorials tackling the pattern in different ways, then i'm not sure what you are expecting to get out of other people giving you even more tutorials that tackle it in different ways. there are many ways to implement the pattern, you really just need to figure out what your needs are and find an implementation that meets those needs
I guess I'm just overloading myself like this
I should just take a step back and think about it more
maybe look at what a state machine actually is in computer science and why it exists there. this should clear up a lot of things.
if you look at the average state machine tutorial you only get a bastardized version of what it actually is
you can also learn from this rather excellently designed implementation https://github.com/dotnet-state-machine/stateless
I'll check that out, thanks
my own "state machines" are bastardized versions of state machines!
My general rule is class based state machines for fundamental systems (game stats, menu, etc) and switch statement/if else based state machines for smaller things (individual enemies or objects)
I'm trying to get an enemy to do damage over time, and while i was provided code for a DamageOnOverlap (with a circlecolider 2d) anytime the enemy hits the player, it jus kills them. in the debug it doesn't even do enough damage to kill them, but it still happens. https://pastebin.com/xLbnQSXK
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.
Add logs in the TakeDamage method with how much damage is being dealt and the health etc
It seems like TakeDamage is the important code, which you haven't shown
i know its off topic but im in a organization and when i open the project nothing shows up can ayone help?
not a code question
i actally did-
Not seeing the damage amount logged or the dying part logged
If I await on an async function in Update does it block my update function or no?
i dont think so
Yes it does.
I've had times when I did something similar i.e. block my update function and the entire editor just freezes; I assume it has something to do with receiving an event from every monobehavior before proceeding to the next frame or something?
Unity's main loop is in the main thread. If you block it, the whole game stops. And in the editor I think the player loop is in the editor loop, so it also blocks the editor as well.
those Update methods are bound to PlayerLoop so i guess they all have return to proceed to next frame Updates
Code executes line by line on one thread. If you block it, the entire program would block(or at least the thread)
Also how would I wait on an async function's results without blocking the update function?
For some context I have an A* pathfinding function that creates an entire grid of objects every time it's called to reset the hValues and I don't want to throw that in update since I think it will take considerable time, so I was thinking of making it async would help
This is what I wanted confirmation on, thanks!
its more about locking the main thread where everything runs
Either don't wait for it, or wait for it later, when you're sure it has completed the job.
as dlich said
I was wondering if there was something like in C where you wait on a mutex, i.e. polling an async functino
If it's done then great execute xyz, if not then keep waiting but don't block
Update() {
bool done = async function done?
if (done) {
do xyz
}
if (not done){
continue;
}
}
I see; though it feels weird since I assumed that one monobehavior wouldn't block the entire game's update function running
you can use Jobs for async, so it gets calculated in another free thread
I have a state machine that needs the results of the async function, so I need some way of communicating that the async function is done
it can be done with Jobs
I will check that out
scheldue a job in update, then once its completed assign bool value or whatever suits you
a bit bummed that async doens't support that natively(? not sure if jobs is a part of async)
Thanks ReaZ
exciting though I haven't ever used multithreading in unity yet

async is C# thing, Jobs are multithread way for calculations created by Unity for Unity
you can use async but you have to handle the treads yourself and avoid blocking main thread
yikes, I see. So the job system takes care of this for us then
https://docs.unity3d.com/Manual/job-system.html
The job system lets you write simple and safe multithreaded code so that your application can use all available CPU cores to execute your code. This can help improve the performance of your application.
I just ran over this line of code underlined. Somehow cubeindex (which has a value of 0) |= 1 is equal to 0
am i missing something or 0 | 1 is 1
alright my debugger is wrong somehow..
you can debug log it and check its value
the bitwise operator should return 1 when its 0|1
yeah just done that, so my vs debugger local values arent correct for some reason
it is 1
which is a big problem for my debugging
or you just ran first loop where it was 0 and you reading when it is still 0
A mutex in C would block the thread as well. So I'm not sure what you're asking.
You can check if an async task is done or not. Check the Task API.
since it check next ifs
nah i made sure that cubeindex is 0 when passing over that line
anyone had visual studio locals incorrect before?
you could use a loop for this btw
well the other guess would be that the first if doesnt execute
and yes you should use 2 to power x for calculations so you are not stuck with tons of ifs
from the screenshot, seems like the condition is false
This code is ripped from somewhere and im just running over it to try to understand it. thanks for the tip though
1 << x, not 2**x
(same result yes, but think on bits here, not numbers)
if you mean making it async void and using await then no, it won't block, it's just not really a good idea because the next update won't wait for the next one to finish awaiting
What would cubeindex |= 4 do? I've never come across that
I have a very..... strange problem
i have just reated a variable, bool, like any other
but it keeps switching to false as if something was forcing it to
but, i searched the entire game for refferences and NOTHING is setting it to false, only to true
i commented those mentions that did
And it keeps being false for some reason
funny thing is, i can set it manually during playtime
and it switches
and everything works lol
One might be posting everything as one single line before thinking about what you wanna say... Maybe try to rephrase that with a related piece of code you are having issues with.
Quick check, be sure its not public and set to false in your inspector
Ok, found that the issue was different. I have clones of all chess pieces in my game, and one actual piece that is not cloned. The non cloned piece works as intended, but the cloned ones do not inherit the variable, even though i have done very similar effects and they did, which is confusing for me
Again, without code (hence the channel name), nothing we can do here
!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.
You know what? It was one of those moments when you say a problem to someone, that someone didnt even have to say anything, and you come up with the answer yourself
I forgot foreach loop in one place
so every clone would get that
but i haven't forgotten it before hence i was confused what happened
Thanks XD
Is there a way yet to get Unity 6 working with C#10+ features? I know a few have been backported, but there's a few QoL ones and such that haven't. I imagine the answer is no (outside of using odd workaround hacks/addons like past versions) but figured I'd ask since .NET parity has been "in the works" for ages at this point.
nope the compiler is still stuck on C#9
technically you can update the roslyn compiler unity uses to get the syntax sugar features of newer language versions. but you won't get access to anything that requires a newer .net version. it may not be worth the hassle of doing so though because it isn't really supported
rip, kinda what I figured. maybe someday 
Hello everyone
I know this may sound a bit too bold and sudden, but is there anybody who could help me out with my project?
I've only gotten to work with unity a few days ago because my colleagues asked to
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
My responsibility for now is making an animated UI prototype, but I'm already struggling with the one I'm trying to create
if you need help (rather than a collab request), don't ask to !ask
: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
I'm not really sure what a collab means
I'm just searching for a person who could hop onto vc so that I could explain ym goal and issue, and so that we could sort things out together
collaboration
are you asking for general help, or requesting someone to work on your project with you personally?
As there are no guides on the thing I'm trying to make
vc's aren't great ways to get/give help
we don't have any here
I noticed, but maybe we could still call in private then
Explaining everyhting in text would take too much time
we don't support that here; that's also not a great way to get/give help
Understood
would explaining everything 8 times to different people be faster?
the point of a community support server is to ask and receive help directly in the server, as text. more people will be able to see your question, and maybe respond, than you would get with private help
Understood, thanks for the info still
your question being in text allows people to give answers after you've asked, and not just while you're present
The thing is - I'm really bad with understanding engines
And explanations in text might be way more difficult for me to understand instead of a real-time voice chat
back to your issue; you haven't given much info to go off of, so at this point, nobody can help you; you'll need to provide more context as to what you're trying to achieve and what's going wrong
also you maybe want to consider what channel you ask in? from the brief description you gave, #๐ฒโui-ux may be a better fit, but can't really say without knowing what the issue is
I'm really bad with understanding engines
this sounds like you've given yourself a massive goal. you don't need to understand the entirety of the unity engine for a single feature. focus on the features relevant to what you're trying to achieve, one step at a time
And explanations in text might be way more difficult for me to understand instead of a real-time voice chat
you can always ask for elaboration.
you can also reread text; if you keep asking someone to repeat themselves, eventually they'll get tired lol
Long story short - I'm trying to make a UI action system for a dungeon crawler project that we have
For example, right now I'm working on an Attack option.
When you click it, I want the original image to expand and get replaced with a different version of the sprite, while other three options will be replaced with 3 different options of attacks
So far, I've spent 3 days just to figure out how to properly import pixel art to the engine, and managed to make the attack button exapand on click, along with the alternative sprite appearing separately not to overlap the original button YET
However, for some reason, even though the same animations are linked to both sprites, they act differently, which I don't understand
ok well im pretty sure this is not a code-specific question at the moment, could you forward that to #๐ปโunity-talk and we'll discuss from there
To be honest, this work was dumped on me out of nowhere by the guy who's initial and only responsibility was Unity
If being honest, the way our UI is planned to work is not simple if compared to standart menus and so on
And considering the fact that engines are my weakest point in all sorts of things I could do in game dev, I feel really demotivated working on the UX rather than UI itself, or other things I could take better care of, like animations
Hi, I want a rectangle rotate on the z "around" a sphere but rotate it like the hammer on getting over it, it's always attach to player
So if my case turns out to be too much of a hustle, I'd just refuse to take this responsibility back to the same guy who game it to me out of nowhere, taking on things I can handle or would like to learn
Sure
(btw i see you typing. discord has a button to forward entire messages, that's what im referring to
well, for future reference, i guess lol)
I wanted to add some extra greetings :p
Should I set just the eventbus in the Project Settings > Script Execution Order - or is that v bad to do?
If you try using the SEO you'll very quickly run into issues, it's not a good thing to do
It's best to have something that loads/ enables things in the correct order.
Whether this be having a 'manager' scene which loads first, then any other additional scenes additively after.. or a manager in the scene which enables game objects in the correct order... or some other way, I aint going through everything
Hey ive got a question, since forever to make a gun ive always used raycast but i was wondering if i made a very fast object that behaved like a bullet, (moves using rigidbody and has a trigger collider) if the player lagged would the bullet go through and object due to its fast speed and not call OnTriggerEnter or would it still call it?
it wouldnt even matter if the player lags, very fast physics objects wont always behave as expected. you'll probably have objects go through each other without calling the physics methods
So id have to do a boxcast then to check
"lagging" is kinda meaningless here. Unity uses a fixed timestep physics simulation
It will always do the same number of physics simulation steps
Continuous detection would help for actual collisions not for triggers
Okay
So if my bulletโs collider isnt a trigger it would work fine even if it has very fast speed
I assume?
Continuous detection works only so well. At a certain point you'll need to do Raycasts regardless
Reducing timestep can help too
Also trigger events are not affected by collision options
Yeah but I wonder how could I check because a raycast wouldnt be accurate
I would need a box cast or something
But if it moves downwards and forward then it wont replicate like it should
Yeah but so i would put it in fixed update but then how would i scale it
Wdym scale it
Like I would need to scale it by the speed and by Time.fixedDeltaTime no?
Scale the spherecast?
Lets say in one fixed update it moved 100 units
You mean the distance? Yes it would be velocity * fixedDeltaTime
If it moves in two direction
What I mean is like it moved forward + little to the right + little to the left
I would need to start the spherecast from the old position
And finish it at the current position
Huh
It wont be accurate
I think you're confused about what SphereCast does
It casts a sphere
Yes
With a radius
The radius is just the radius of the bullet
Yeah so how can I check with that properly
For objects that were behind
Like a for loop?
You don't need a loop
Just one cast per FixedUpdate
Along the path the bullet moved
Or will move
Yeah but the sphere wont necessarily cover the whole distance it traveled
Cuz its a sphere
Or maybe im just too dumb to understand what ur trying to say
.
If u dont mind can u do an exemple code?
Like idk pseudo code
I did right here
Ok but what parameter
Direction and max distance
Yes
Of course
No
Radius is radius
That's separate
Again I think you're not understanding what SphereCast does
Ok can u write the whole function so like SphereCast(oldPos, radius, distance etc
sphere is sphere + cast
No I'm on my phone
radius controls how large the sphere is
But I gave you all the parameters
distance controls how far the sphere goes
Ah me 2 ๐
Read documentation
a spherecast draws out a capsule
Oh I just understood
you can get like, a rounded rectangular prism with a capsulecast
So like it checks the sphere and the distance it traveled
Like if it checked a lot of spheres along the path
I didnt know it could do that
it doesn't check a lot of spheres, really
Yeah idk the math behind it
yeah me neither
But uh this is how i will interpret it
Alright nice
Now i know how to implement well a bullet
Now I can use the trail system too nice
Also I hope we can get more control over how lighting works in hdrp cuz like i wanna illuminate a big space without most of the room being completely white due to the light being strong
There should be a maxIntensity or something on the light component
Thanks
#archived-lighting could help with that
Ive already asked before and i dont think there was a solution
The problem is over exposure
I liked how the default rp handled lighting
An object could never be very brightned / over exposed
But urp and hdrp dont have that sadly
Or i dont think they have
yeah idk but if there is you're not gonna get it in this channel lol
Yeah ima ask in lighting
could someone help me with this? still have no clue whats going on
enemy code https://pastebin.com/VcUJ2Xff
health code https://pastebin.com/EtAJViff
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.
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.
Add logs in the TakeDamage method with how much damage is being dealt and the health etc
my logs shows how much is left after the attack
but not how much dmg is being done
Nor when and why the Destroy is happening. I asked this earlier...
sorry blue, i fell asleep
The logs there say you've got 90 hp left, yet it still gets destroyed?
yes
The logs need to go here
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.
One in Kill
One in TakeDamage with the damage amount and health before and after
You'll maybe have something else calling Kill(); - does this method really need to be public?
Very possible something else besides this script entirely is destroying the player. Adding the logs will tell us that if we don't see Kill being called
adding a debug line now makes it work??? wuh??
the health counts up though, not down in the debug
that worked tho, thanks
20 -> 10 -> 0 is down
Hi all, I am working on a project with a cell grid, each cell is represented as an enum:
Dirt, Stone, Water...
A seperate part of my project checks collections of these cells for patterns (say if the cells within a specific bounds are stone or dirt next to water).
The need for OR'ing the enum with these pattern checks made me swap to a flagging system so that I can check if the cell is within the pattern.
That said, this has now had the result that areas (like with world generation) where I would only ever want a single cell to be represented as single cell could now in theory be both Dirt and Stone.
Is their a clean and non-intensive solution for mandating the "flagibility" of an enum depending on context?
so is each type mutually exclusive with others?
or is it a mix between some being mutually exclusive and some not?
In the context of world generation a cell can only be exclusive (Dirt) for example.
However, I'm using a type of pattern checking over groupings of cells, this is in 3D but a 1D example could be:
[ Dirt | Grass ],[ Air ],[ Air ],[ Air ]
So the idea would be that if either dirt or grass has air above it for 3 cells it will be true
The flag logic is being used here
These patterns can get alot more complicated, but this is an easy example
you could have 2 ways of representing types. one as a property, one as a mask
Guys were can I ask for people to help on a project?
the property way would be 0,1,2 etc, used for tiles, while the mask way would be a bitfield
!ask
: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
Like 2 enums? One with [Flag] and the other without?
no, just a single enum
the enum would have values 0,1,2, etc
then when you make it into a mask, you would do 1 << type to get a bitmask
Oh, so manually doing the mask?
you could then check if some tileType (enum) matches some tileTypeMask (bitfield) with tileTypeMask & 1 << (int)tileType != 0
well, not manually, but dynamically from the enum values rather than as the enum value itself
Right, gotcha. I guess this goes to second question then, do you know if the enum fields for the editor (scriptable objects and such) support bitfields, or will I need to write my own dropdown?
well if you use an enum type it'd let you choose from the enums
there is LayerMask that lets you choose a bitfield though, so maybe there's a built-in way? i'll have to do so digging
Thank you, I'll see if I can find anything out about it!
i think it's that
LayerMaskField extends that
So,,, I need some help here sorting out/rubber ducking the logic on the Compendium system in my program. I'm just not sure if I'm doing it in the most optimal or correct way and need some guidance. I'm working on a Compendium of user content, such as Items, Classes, Races, etcโ the Compendium class has three Lists, of the three different types of classes it contains: Sources, Entries and Features. I'll deal with the features in the future, right now I still need help with the entries and sources
- Sources are the top-level compendium "pack" of content entries. For instance, a player might have the
LaserLlama Homebrew Packwhich includes 5 classes, 18 subclasses, 2 races, 40 spells. The source class has very simple parametersโ name, ID, author, version, cover art, etc - Entries are the "meat" of the compendium: There is a class called Entry with some basic info such as name, ID, version, etc. From this Entry class, you derive dozens of specific child classes (Races, Classes, Weapons, etc).
Each GameManager has one Compendium, which is meant to store all the classes and entries and be assessed through different codes in the game every time the game wants to know all the races the player has, all the classes, all the this and thats. Sure. Here's the thing: GameManager has to contain both Sources AND Entries. But logically, Entries are contained in Sources. As in, one Source has many Entries within it. My first thought was to give each Source a List<Entries>, but I didn't like thatโ for two reasons. First, it would be a nightmare to assess every item or race in the game having to loop through each Source in the GameManager and looking for each Entry in Entry<List> then checking if said Entry is of type Race or Item... you know, convoluted. Second, for some other reasons that I'm not going to explain right now, I kinda need each entry to be parsed into its own separate individual Json at the end when loading so users can share them amongst themselves.
(Continuing)
Then, I had a different approachโ each Entry would have a public Source source variable that loads their source within them. At different times the script would loop through all the entries to see if their Source matched the Source in GameManager.Compendium to like, group them by source. But,,, I don't know, it didn't feel right. I don't think the Entry class should hold a local variable with so much information pertaining to some whole other thingโ because now you have the fields Entry.Source.sourceName, Entry.Source.sourceID, and even stuff like the cover artโ having each entry have to carry a separate local variable for their source's cover art sounds like taking so many resources to allocate for something redundant.
Then my other idea was... give each entry a Source source variable, make it non-serializable, and also a source ID variable. You just store the source ID in the json, and when the entries get loaded, the parser will look through the sources that have already loaded in GameManager, find the source that matches their source ID, and have the Source source = sourceInTheGameManagerThatMatchesSourceID.
This solved my problem with saving all the source's information in the entry's JSON, but I still don't think it helped me with the local variables problem... and overall, this Entry-Contains-The-Source approach is feeling pretty sloppy on my end. I don't know. I don't think I'm doing the right thing.
Does anyone have any ideas of a better implementation of this whole "Compendium contains sources and entries, sources are things that will contain entries" system? Or hell, what should I do in scrapping this whole direction for a more elegant solution that's just not clear to me at the moment? Gosh, and this is all before I implement the features, which are things each Entry will contain... ๐ตโ๐ซ
I wonder if you could shrink your actual question down to a shorter version. Its just too much to actually get what you really want. At least I found barely time to read and think through all of that, which might have been hours for you and cant be seconds/minutes for us here to follow
True. I'll trim it down, hold on ๐ญ perhaps ChatGPT can summarize it for me rq
I need help sorting out the logic for my Compendium system. The Compendium stores user content like Classes, Races, and Items. It has three lists: Sources, Entries, and Features (but I'm only focusing on Sources and Entries for now).
- Sources are "packs" of content (e.g., a homebrew pack with multiple entries). They store metadata like name, ID, author, version, and cover art.
- Entries are the actual content (e.g., Classes, Races, Items), derived from a base Entry class.
Each GameManager has one Compendium, which contains both Sources and Entries. Logically, Entries belong to Sources, but I need a way to store and access them efficiently.
Approaches Iโve considered but am unsure about:
- Sources contain a List<Entry> โ This makes retrieval inefficient since I'd have to loop through each Source to find Entries of a specific type. Also, for the needs of this project, I need each Entry to be a separate standalone JSON file at the user's drive
- Entries store a Source variable โ This feels redundant because each Entry ends up storing full Source data (like cover art), which seems like wasted resources.
- Entries store only a sourceID, then use to copy the Source from the GameManagerโs Source list at runtime โ This avoids redundant data in JSON but still feels sloppy.
I feel like Iโm missing a more elegant way to structure this. Any ideas on a better approach, or should I rethink my whole system? (And this is before I even add Features, which Entries will containโฆ) ๐ตโ๐ซ
Ok yeah this was a decent summary thanks mr. GPT ๐ญ
Scriptable objects
Only almost my full screen height, great job ๐ ๐ Okay, nevermind, lets figure this out. From what I read now, first thing coming to my mind with minimal complexity in structure is your actual list of IDs. So each entry has its ID and your source pack just holds the ID to those entries. Nothing wrong with that
Dictionary ?
Dictionary
ayo
Hmmmm so,,, Each entry has an individual ID, and the Source class has a List<string> of IDs?
It really depends on what you want to do with it at runtime. generate the full data set out of this list once or access them frequently or shift the list around change it?
Really just need to group things out a bit more if you do want to use lists otherwise. You can always have like a primary list, but then group out types into sublists of specific types
Generate the full data set once, or minimally if the player makes a new race/class/item/whatever. It shouldnt happen often. In most runtime sessions it would just be
- Game loads everything from user data, save them to GameManager.Compendium
- Every time the game needs a list of all the classes, races, weapons, whatevers that the user has saved they'll communicate with GameManager.Compendium
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm quite wise ,,,
So your Compendium is like a growing one for one player locally, right?
This is making me think of a bit of a loop actually,,,,,,,, that could be quite nice to me
- Sources have a
List<string> EntryIDswhich is empty by default - Entries have a
string SourceID, which is always set to the source that's meant to contain that entry - At runtime start, the game loads all Entries first
- Also at runtime start, the game populates
EntryIDswith the ID of every entry who'sSourceIDmatches the source'sIDstring
I think this way is quite nice actually so the source has a list of everything it contains but doesnt need to hold them in the JSON or anything and its just stored as short strings!! This is a pretty good idea
mhm!
This is meant to be a D&D character sheet builder. Your compendium is, metaphorically, your IRL book shelf. You buy books and you put them on your shelf and now you "have" those races and classes to use in your character, but you're not meant to be constantly buying and removing and ripping out pages and rewriting stuff
okay, nice mechanic. Yeh, I really would let the data sets be their own little parts and the compendium is basically just an id holder for all those types
Also, yes methinks I need to study dictionaries more they seem very helpful but I'm not super knowledgeable on them
If a key is an ID/String, usually you do some sort of hash table
but I can't really make too much sense of what you're asking otherwise haha
Dictionary is a hash table in C#
Does anyone know how to use blazebin on mobile it just looks like this when I try to scroll down
I have the same issue on mobile. It goes blank when I try to scroll.
Yeah it just straight up doesn't work, even in desktop compatibility mode
i just started my new unity project from yesterday, all pink xD what to do?
idk if its because of the editor, i tried installijng the update, but it says cant uninstall all files or some
Upgrade your materials to whatever render pipeline you switched to
nvm it worked
everything was pink, even unity itself, whole screen was pink idk why
but thx ;0
now my camera is idk doing weird
is there a nice, easy and simple way to bring all variables on an object to default, without breaking references to said object?
you know, that might actually be a bad solution to my problem, nevermind
guys i made a func it works but when i spam the fov goes to like 60 like it messes up. Here is the code:
public void ChangeFOV(float newFOV)
{
if (Camera.main.fieldOfView == newFOV) return;
targetFOV += newFOV;
StopCoroutine("SmoothCamTransation");
StartCoroutine(SmoothCamTransation());
}
private IEnumerator SmoothCamTransation()
{
t = 0f;
while (Camera.main.fieldOfView != targetFOV)
{
t += Time.deltaTime;
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, targetFOV, t / 24);
Debug.Log(targetFOV);
if (Mathf.Abs(Camera.main.fieldOfView - targetFOV) < 0.1f)
{
Camera.main.fieldOfView = targetFOV;
break;
}
yield return null;
}
}
targetFOV += newFOV; you sure you want += there instead of just a plain =
idk why?
because it'll keep growing infinitely every time you call ChangeFOV
you add newFOV to targetFOV rather than setting it
lemme use = then ill try
also cache your startFOV before your while loop, and use it as the first value in your lerp
oh i remembered why i did that
imagine it that u use zoom button and running at the same time
cuz u are started to run at the last time
even tho u
zoom
it doesnt work
why?
bro like im trying to make this thing for 5 or 6 hours bro
like insane
and i still cant
i really need help xd
I mean it seems like you want the zoom to happen over 24 seconds considering you divide t over 24, but using that camera.main.fieldOfView instead of a cached value makes it go much faster than you'd expect
and you can't really predict how fast it'll be going
you have no control over the precise time of the change
you should cache it and then devide over the amount of seconds you want it to last
idk how to use startfov because it will be so messy like imagine that u use zoom and run at the same time then which one will be start fov
u know what i mean?
divide*
not devide
actually I think lerp isn't what you should use in your scenario
everyone was using lerp for it
try Mathf.MoveTowards and define a speed of the change
and why?
if you want to move between multiple values at any time, this allows for a smooth change from any value to any value at constant speed
your current code is not very predictable in terms of speed, and even a correct lerp would make the different zooms look faster or slower depending on how big each change would be
since with a lerp you define a time of the change
and with moveTowards you define speed
it should look better
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, targetFOV, mySpeedFOVPerSecond * Time.deltaTime); or sth like that
and you don't need any startFOVs or anythin
but u use here lerp
help i cant refernce my player
hmm why not
look
so do you have Player component on Player ?
wydm
btw this is a #๐ปโcode-beginner question next time.
Your Field is expecting a Player component.
The gameobject you're dragg into it does not have such component
If you're following a tutorial I would revisit it because you probably put it on the wrong object
๐
Thank you i forgot to put the componet on player instead of playervisual
Hey having a simple problem, not sure why it isn't working as intended
for context, this script is on a child object with a ParticleSystem component set to Stop action : Callback
I want to delete the parent object when the system is finished
public class ParticleSystemCallbackDIE : MonoBehaviour
{
private void OnParticleSystemStopped()
{
Destroy(transform.parent.gameObject);
}
}
This is resulting in the object the script is on being destroyed, instead of its parent
does it work if you put it on the parent?
no, because the particle system is on the child
ohh its on the same object?
you sure all the particles died?
yes, because the OnParticleSystemStopped() is happening, its just destroying the wrong object
I want it to destroy FirePillar
but it is destroying FireParticleSystemForShader instead
and the script is on hitbox?
its on FireParticleSystemForShader?
yes
why not just make a Serialized reference
Try Destroying parent.parent.gameObject?
Yeah this is best. Just this
link it in the inspector so its not sketchy
Could be GameObject as well. Transform isn't the important part
true Im just used to always using Transform when no other components exists
hmm, I guess I could seralize it, thats just kinda messy
and I want to be able to reuse the script in alot of different places
I'm pretty sure I solved this before, but I cannot remember how for the life of me
hows that more messy than doing a bunch of guess working accessing parents
cause its not guess work if the prefab is correctly set up
if you ever change the heriarchy or order in anyway your whole thing breaks
thats the definition of mess
yup, but I dont plan to
parent > children hold particles and hitboxes etc
I'm consistent with that
plugged reference directly, unless its deleted will not care which object its on
i mean its ur project you can do whatever. In the long run it just makes these very sketch at scale
just offering suggestion
<- years learning the hardway
Although in this case having a restraint helps make sure we're actually deleting the object the script is on. If you link an unrelated object you're not gonna delete the scripted object.
You could put the script on FirePillar and then have it operate on the child, and then just destroy itself OnParticleSystemStopped
the problem with that is OnParticleSystemStopped only checks the object its on for a particle system
it doesn't recognize that the system is on a child
but, I just gave up and serialized it, that works well enough I guess
thank you for the help
Anyone have experience in Unity struggling to consistency save generic ScriptableObjects? I was under the impression this can be avoided if you explicitly define them in a class but that doesn't seem to be helping. Currently I have
WeightedManifest : ScriptableObject
WeightedManifest<T> : ScriptableObject
[SerializeField] private Dictionary<T, int> weightedCollection
WeightedStringManifest : WeightedManifest<string>
But sometimes it seems Unity just gives up on preserving the SO's made from WeightedStringManifest and they lose their monoscript reference and all references to them are removed
WeightedStringManifest : WeightedManifest<string>
That should serialize like any other class
Actually, is string a good enough constraint?
I would assume so
The only time I really run into serialization breaking is dealing with SerializableReferences and serializing by interfaces and stuff like that, but otherwise I've not an issue with explicit constraints
Yeah I thought this was cool to do
Admittedly that dict is actually a serialised dictionary from something on the asset store but the fact the SO completely loses itโs monoscript reference makes me feel like thatโs not relevant here
that would be the problem and one of the reasons I don't use them
I donโt see how that would be the problem here?
[SerializeField] private Dictionary<T, int> weightedCollection```
This is the only thing there that I can see being a problem, but otherwise the class prototype is fine and shouldn't be the problem
Sure but at best that should just fuck up the serialization of that field no?
The entire SO is failing
How are you creating the SOs?
createassetmenu
each defined class is in it's own monoscript file too cuz i was worried about that being a problem
could you maybe share the whole thing, this is just shooting in the dark otherwise
forsure
WeightedManifest.cs
public abstract class WeightedManifest : ScriptableObject
{
public abstract void ResetManifest();
}
public class WeightedManifest<T> : WeightedManifest
{
[SerializeField] private SerializedDictionary<T, int> weightedCollection = new SerializedDictionary<T, int>();
[SerializeField] private SerializedDictionary<T, int> availableCollection = new SerializedDictionary<T, int>();
//Awful btw
public T SelectRandom(bool claimSelection = false)
{
T randomSelection = Utilities.GetWeightedRandomSelection(availableCollection);
if (claimSelection)
availableCollection.Remove(randomSelection);
return (randomSelection);
}
public override void ResetManifest()
{
Debug.Log("Resetting Manifest: " + name);
availableCollection = new SerializedDictionary<T, int>(weightedCollection);
}
}
WeightedStringManifest.cs
[CreateAssetMenu(fileName = "WeightedStringManifest", menuName = "ScriptableObjects/Manifests/WeightedStringManifest", order = 1)]
public class WeightedStringManifest : WeightedManifest<string> { }
what is causing this error exactly?
It says right in the error: failed to copy a files since it was being accessed by another process.
but I cant figure out.... how exactly is that being accessed if I restarted Unity entirely and it still errors?
Do you have the standalone (built) game running? If not, looks like you have a dangling open file stream, restarting your computer should solve it
probably just running in background somewhere even though I dont see it in Task Manager
Try to delete the DLL file manually from the explorer. If you're lucky, Windows will tell you which program is locking it
There was a way to find that out via command line and process id. I don't remember exactly, so you'll need to look it up. If restarting doesn't help.
Resource monitor can do that: https://thegeekpage.com/how-to-find-out-which-process-is-locking-a-file-or-folder-in-windows-10/
still would love help with this if anyone knows anything
Hey, any ideas why my AI behaves in such a weird way? I don't understand why it jumps like that and sometimes flips in place a few times.
https://pastebin.com/tK3GuPbz
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.
are you remaking terraria ? ๐ฎ
not really, terraria is huge
oh.. gives terraria vibes lol
I mean, its a big inspiration of course : )
are you using a*?
Use visual studio debugger and step through your code, otherwise you need more logging
yup
oh yeah, may not be a state machine problem then
there's visual tools to see how they are pathing which you should probably be using
ye, I will probably code path drawing tomorrow to see what it "thinks"
it already includes path debugging tools
I think it's enabled on the agent itself? Or probably in the gizmos menu
Iโm using my own A*
oh right ;p
yeah then def drawing some visual debugs will help greatly
guys i really need help
my code just breaks whenever I update anything in the code, even a comment
and it fixes itself if i update a script even a comment
I have 0 clue why this is happenign
hey im starting up a new project and ive found myself wanting to just use events for almost everything. Whereas before I might be holding references to other objects now im just pinging events back and forth. But I'm wondering if I continue on with this at a larger scale, will i face performance problems? Or is this perfectly fine
show code
okok
what does "just breaks" mean in this context
ok
and the error line the code is pointing to makes 0 sense
so heres the video
This is fine and usually preferred, lookup "Observer Pattern"
you still usually a refrence but its a 1 way street instead of 2 way
Eg your Subscribers will always need the Invoker reference but invoker doesnt care about subscribers or have to run their methods manually (called from that invoker script), thats the main benefit
in the case of things that are effectively singletons im just subscribing to static events so i dont even need 1 way references
show both scripts
PlayerShoot and Gun
also the error isnt consistant either sometimes I get htis error sometimes I don't I have absolute 0 clue why
ok
like send links of scripts, dont make a video of code lol
yeah I mean you could say thats still a reference but yeah, there should be no problems. With Static especially though make sure you are unsubscribing in OnDestroy
https://paste.mod.gg/xegxjqaieioj/0 this is the gun.cs one
https://paste.mod.gg/hebtqwobdsmj/0 this is the palyershoot one
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
i'm also using a scriptable object for my guns
A tool for sharing your source code with the world!
i think the error youre getting is real that the gunData is null and its just inconsistent the compiling/recompiling thing is maybe just a red herring but i dont know enough about scriptable objects to say what the cause might be
https://paste.mod.gg/vxzxmqheqdpq/0 heres the error message
A tool for sharing your source code with the world!
i mean
all the stuff for the thingy
r filled
field
like i bet if you add a check for gunData is null, it will come back true in the error case
i will try that
<@&502884371011731486>
damn thats one expensive site service
dudes using an AI generated PFP probably a mass spam account
lol
is there anything that deletes the scriptable object on cleanup or something like that?
are you destroying it?
i dont think so
this.gameObject seems to be throwing I think
hmm let me try that
also i tried
nothing
also I just tried
i think it was the reason?
i have 0 clue tbh
oh yeah my b i just swa gun and the gundata first check but its gun yeah
is gun gameobject disabled or anything ?
i think you need to unsubscribe
right? youre sending an event to a dead gun maybe?
its that same issue you just warned me about
but they said it never gets destroyed no?
yeah
wait let me just check again
why would i even want to destroy the gun tho
ykwim
but if you have that static reinitalize setting off isnt it possible its got a dead gun subscricption hanging around
the events are static
the only time I ever destroyed an object
idk maybe you have it on a weapon that destroyes? idk ur game
thats why its between game runs
there is no Gun script on this gameobject?
nope
is just a sphere
with a target script
you need
OnDestroy()
playershoot.shootInpiut -= shoot
playershoot.reloadinput -= starterload
in gun
let me se
its good practice but dont think thats the issue rn
yeah idk
could be lingering event but doubt it
idk this same thing happened to me when i turned off that static reinitialize setting
recreate the bug again
idk if you have it on or not
UnityEngine.Component.get_gameObject makes me assume is somehow this.gameobject
how do i do that
cause this runs a Get to the component GameObject its on
but if you dont have that reinitialize setting on the static object still has a subscription to a now dead gun right
i dont remember the name of the setting let me poke around
alright
did you remove that line
and it still appeared on 25?
ye
and you saved right?
run 1 - add subscription to gun, stored on static event in player shoot
end run 1 - gun is now dead, but subscription is never removewd
run 2 - if statics arent reinitalized, that static event still has a subscription to a now dead gun. You try to access the game object of the dead gun, but it is null
maybe you have two scripts
did you try unsubscribing on destroy?
your restart alone doesnt clear the subscription to the static eventt
so the event gets sent to a dead gun from the previous time you ran the game
for some reason the PlayerShoot just loaded in
how would i be able to do that
sorry im kind of enw to unity
add
OnDestroy()
{
playershoot.shootInpiut -= shoot
playershoot.reloadinput -= startreload
}
to gun
every time you stop the game the static is still lurking in memory
im guess it gets cleared/reset when you hit the error, which is why its hitting like every other time
like this?
yes
let me try
wish had seen that PlayerShoot script earlier lol
that site works very slow on mobile for some reason
i think it works now
i have 0 clue how that bug even
like worked
so im keep messing around
tysm ygs
unfortunate side effect of statics
and events
any time you += to a static event you want that corresponding -= in OnDestroy
or maybe OnEnable/OnDisable yknow whatever is relevant to the context
ah i get it
normally I do
OnEnabled =>Sub
OnDisable => UnSub
i have a question tho, is why does the bug isnt consistant
this way no funny business if its disabled but stil in game
i cant
type
like the bug isn't consistnt like sometimes it works sometimes it doesnt
oh i just
read this
nvm
u guys r so smart ๐
ahhhhhhhhhhhhhhhhhhh
so basiclly the thingy didnt wokr becuase there were 2 instantce of the gun object, and it doesnt get destroyed the frist time it do funny stuff
sum like that
right?
yeah the gun object from the first time you ran the game gets detroyed when you stop playing the game. But player input still is sending messages to that now destroyed object cause you never deleted the subscription. So when player input sends an event to a destroyed object and the code tries to run, it fails cause that object doesnt exist anymore and everything in there is null
ah ok, tysm brtw
btw
so the fix is like this
okok
tysm for u time
np, gluck with stuff
ty, you too
before anyone questions how weird this might look, in theory defining an explicit type like this should be serialization safe for Unity right?
public abstract class TaskBehaviour<T,U,V> : MonoBehaviour where T : ScriptableTask
{
[field: SerializeField] public T Task { get; private set; }
[field: SerializeField] public U PrimaryContext { get; private set; }
[field: SerializeField] public V SecondaryContext { get; private set; }
[SerializeField] private List<AINode> TaskNodes = new List<AINode>();
}
public class PurchaseTaskBehaviour : TaskBehaviour<TakeItemTask, ScriptableItem, int>
{
}
(assuming the types i'm using are chill for serialization ofc)
Lads, quick question! Is it better for performance in a 2d game to have only 1 scene or to have many scenes, or is it better to be somwhere in between?
The number of scenes has no effect on performance
Technically everything you add adds to performance, and this includes the scenes. However, please do not limit your scene count purely to save on performance, because it's very unlikely this has any direct noticeable difference and you just end up making things more complicated for yourself.
don't worry about performance unless a) it becomes a problem or b) you're doing very heavy work (1000000 ops per frame?)
๐ซก cheers
I recently heard the perfect phrase "negligible at a human time scale"
Premature optimisation moment
I've never been able to phrase "yes that operation is slower than something else but it's not really possible to notice" in such a concise way
"negligible at a human time scale" works
well for us it often if its noticeable at a frame scale but I think still applies
but oftentimes these things aren't frame scale
frames are in ms, the differences here may be in us or ns
what i meant was in some programming settings something taking more than say 0.032 ms isnt going to be noticed by the user, but in a game it may be if it happens frequently enough.
Anyone know how to grab all the sprites from this sprite sheet and put it in a list without dragging in each one manually?
how should i handle checking if the player can jump? if i raycast in the middle, then if the player is on an edge he cant jump, but im not sure how else i should accurately check
Raycasts work fine, a common approach is using a different shape like a sphere instead of a ray to do the casting, which can catch more of those (literal) edge cases: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.SphereCast.html - there is also CircleCast for 2D, along with a few other shapes
can i visualize this to debug? i tried implementing it but it doesnt seem to work
bool hitSth = Physics.SphereCast(transform.position + new Vector3(0, .01f, 0), jumpCheckRadius, Vector3.down, out hit, MaxDistance + .01f, LayerMask.GetMask("Ground"));```
i put `jumpCheckRadius` and `MaxDistance` really high, still it doesnt become true.
last time i did it with debug,drawline but there doesnt seem to be a
debug.drawsphere
For the other shapes of casting, you may have to use gizmos: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Gizmos.DrawSphere.html - otherwise theres a nice package I like using made by a community member: https://github.com/vertxxyz/Vertx.Debugging
if you are on unity 2022+ you can use the physics debugger to visualize your physics queries. i also recommend the same debugging package dibbie just recommended
that looks crazy good thanks
Physics debugger seems like such a hidden gem I don't see it getting talked about enough
yeah it's pretty handy, finally being able to visualize physics queries is nice. too bad it's only useful for 3d though
Oh crap that sucks I've never really done 2D games. Seems like a big oversight
do they do different things? or is the package just a better version?
they work differently, and the package can be used for more than just drawing physics queries. it also supports 2d
i personally prefer the package over the physics debugger, but the physics debugger is already included and you don't have to make any changes to get it working so it's nice for quick tests
package doesnt seem to work :(
that is an error from a completely unrelated package
and likely means you need to update it or just nuke the package cache so it is rebuilt
it only appeared once i installed that physics one though?
i didnt add the one from the error
oh it seems to be a dependency
It was probably installed with the netcode package. Vertx's package doesn't use that
oh yeah weird that it only started acting up now
ive had netcode for a while
they both use burst
just a random package cache issue probably ๐คทโโ๏ธ
alr ill delete the cache
deleting the cache folder in appdata did not fix it
or is it a different folder?
the one in the Library folder within your project. the one in AppData is just the download cache
do i nuke the whole folder or only that one package
whole folder usually. it will reimport all of the packages
just do it while unity is closed
Hi guys. I've implemented a skill system. Now each time i update a skill i need to update the corresponding gameobject and im doing so through an even bus.
Every time i upgrade a skill i raise the event and every subscribed objects check if their skill id match with the raised skill id event. Is this a good approach considered that the event is fired to all the objects that are related to the skills?
uh... im gonna need a fix for this one as well now
you only deleted the PackageCache folder which is located within the Library folder, not the Package folder from directly in your project, right?
i deleted all of these
and you did that while unity was closed, right?
yes
when i opened it i had to wait for them to reinstall as well
i checked package manager and they are in there
including the netcode and UI packages?
i pressed ctrl a and delete
cuz u said whole folder
okay that does not answer whether those packages i asked about are in the package manager
oh i thought u ment delete
lemme check
alright i just re-restarted and now only the original 3 errors are there
you ensured that all of your packages are up to date, right?
are you on an older version of the editor? because it does look like your netcode and unity transport versions are kind of old and that experimental version of collections is kind of old too, 2.1 released forever ago but should require 2022+ afaik
2022.3
then you have some wildly outdated packages then and i don't understand why they aren't showing updates available
thats weird, i made this project this week
so its not like i downlaoded em years ago
im on 2022.3.22f1
well you're also on a year old patch, but those packages still have newer versions for that patch
just removed the debugging package and its working again, ig i just wont use it
is that like a big issue?
have any of the other package versions changed when you removed that?
collections went to 1.2.4
non-experimental
math went to 1.2.6
yeah so that would be the issue then. since all of your other packages are wildly out of date, even for the version of the editor you are using, when that package was updated to the version that was required other packages broke.
i would recommend updating your editor to the latest patch then update your packages so things like this don't happen again
does that break anything in my project?
updating to a newer patch would not introduce breaking changes, they typically only include bug fixes. but even still you are surely using some sort of version control and can revert any changes that break things
surely never knew/thought about version control