#archived-code-general
1 messages ยท Page 159 of 1
let's say your movement input is (1, 1) for the current frame.
_sc.PlayerRB.MovePosition(new Vector3(move.x, 0, move.y));
is now going to move your object to the world space coordinate (1, 1)
you need to add the input to the position of the object to get a new position
๐ What about the use of "AddForce," with a ForceMode of acceleration? That was also not doing anything to the movement of the character.
Also, something that I noticed is that the position is increasing exponentially in the inspector as soon as the player hits the ground.
That's just a very small number that is essentially zero
Since nothing in 3D space is actually a whole number unless explicitly set.
ADdForce is not going to do anything if you are simultaneously using MovePosition
also yeah that's a position of 0 basically
alrighty... would you reccomend attempting to continue with the use of MovePosition(), or should I look into other methods?
having no idea of what kind of motion / control feel you are trying to achieve with your game I have no comment
no worries! thanks for the info you were able to provide!
Ahhh, awesome! Thank you.
int[a,b] is a square if a == b, but a doesnt have to be same as b and thus, rectangle :3
That makes a lot of sense
why is it that object.setactive(!object.activeInHeirarchy) works to set an object as inactive but object.setactive(false) doesn't? I thought activeInHeirarchy was a bool
they both work
and it is a bool
Both work fine . . .
Oh it DOES work fine
how would one go about making the object active once again
(true) doesn't work
SetActive(true)
hrmm
it does
make sure you're not expecting code that is on the newly deactivated object to run
e.g. in Update
It won't.
So if the game object is defined in the code of the object that deactivates it
I can't turn that object back on
You can do whatever you want
But if your code is not running, it won't do anything
because it's not... running
damn
I swear I had it set up so the boxer object could turn the hitbox object off and on
void Update()
{
if (Input.GetKeyDown(KeyCode.X))
{
hitbox.SetActive(false);
Debug.Log("Inactive");
}
if (Input.GetKeyDown(KeyCode.Z))
{
hitbox.SetActive(true);
Debug.Log("Active");
} ```
uh oh I forgot to format again
if hitbox is on the same object as your script then your script won't be active anymore too, thus update won't work
edit it and add another ```
Can I define public GameObject hitbox; to another object then?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
you can define anything you want in any script you want
How do you get hatebin to give you a unique URL? I pasted the code then hit the disk to save thinking that should generate a URL but it did not
Sure, or just don't deactivate the object and instead deactivate idk, the image or whatever you want. But would be best if you attach the script to something else so it won't be deactivated
wait that's weird, none of the scripts for deactivating/activating object hitbox are in the object hitbox
hatebin sometimes bugs out
try a diff one
its all in boxer and it still doesnt run the update after
Just looking for a code review when someone is free...Want constructive feedback to learn more.
https://gdl.space/iperulelel.cpp
int x = Random.Range(0, 2);
if(x == 0)
{
RandomAnimation.SetInteger("Random", 0);
}
else
{
RandomAnimation.SetInteger("Random", 1);
}
Can be simplified to:
int x = Random.Range(0, 2);
RandomAnimation.SetInteger("Random", x);```
unclear what the point of it is though ๐ค
I have a parameter that is getting passed to the animator...if it is 0 it plays one animation, 1 it plays the other...I tried explaining it in the comment above that line in the code
Show hierarchy and what's what
are you telling me the order of the objects matters aswell?
I mean the object where the script is
And the object you're trying to deactivate
boxer is the script for hitbox
thus when object hitbox is inactive it no longer updates
i need a new object
I will say I that for Canvas, aka UI stuff, I am pretty sure it does matter though
Hey, I have method that does component adding/removing in editor on GameObject hierarchy on every component of some type. How can i record undo in this method as single operation? It's curerntly running in Update loop with ExecuteInEditMode.
@wide dock @leaden ice thank you guys for getting me back onto my old engine, works great
Should i put all modified objects on end of operation with this?
Yes, or just call Undo.RecordObject on all of them individually followed by https://docs.unity3d.com/ScriptReference/Undo.IncrementCurrentGroup.html
Ok, i'll try first one
could you use that to do a rewind feature like the do in Viewport?
-
I prefer setting my components in
Reset(), as it automatically handles self assigning and I dont need to drag and drop, means you wont be doing this work during runtime and adding longer load time to the game. Can also just manually drag and drop it -
Same thing Praetor said, you dont need the if/else, you can just do
.SetInteger("Random", x) -
RandomAnimation = this.GetComponent<Animator>(), naming convention wise this is an Animator not an Animation, Unity has both things called Animations and Animators, its typically good practice to name your references to unity objects asNameType, so I would name thisRandomAnimator, not...Animation -
if (waitCompleted), I try and declare my class fields directly above the first method (vertically in the code) that uses them. In your example here I would have declaredwaitCompleteddirectly aboveUpdate. At first glance in this line I see you referencingwaitCompletedbut I have to scroll up half a page to actually see what it even is -
audioSource.Play();you probably wantPlayOneShothere for "SFX" style sounds, as PlayOneShot lets you overlap sounds. -
You use
waitCompletedto trigger self destruction, but you could replace all lines of code that arewaitCompleted = true;with straight up directly callingDestroy(gameObject);, also, you already destroyed the object in your "true" part of your if condition inside ofWaitCounter.
Time.timeScale = 0; should this be 1f btw? 0 would freeze time or am I mistaken?
I see, Id be careful because IIRC thatll also "freeze" any UI animations you may wanna use... maybe?
it would, I read that...I dont have any animations on it right now, but that makes sense... Can you paste a code snippet of what you mean here:
You use waitCompleted to trigger self destruction, but you could replace all lines of code that are waitCompleted = true; with straight up directly calling Destroy(gameObject);, also, you already destroyed the object in your "true" part of your if condition inside of WaitCounter.
Your logic effectively is just that `If waitCompleted is true, destroy myself" there, and you dont use waitCompleted for any other purpose
so you can just remove waitCompleted and directly call Destroy instead
I have it in the update...I was having an issue where the object was destroying before Time.timeScale was set back to 1
else {
Time.timeScale = .25f;
yield return new WaitForSecondsRealtime(1.5f);
Time.timeScale = 1f;
PostProcessing.SetActive(false);
Destroy(gameObject);
}
afaik this should work fine
I'm somewhat of still having problem.
Could you quickly implement example?
Foo[] fooArr = GetCompomentsInChildren<Foo>();
for(int i = 0; i<fooArr.Length; i++){
fooArr[i].gameObject.AddComponent<Boo>();
DestroyImmediate(fooArr[i]);
}
Thanks...only been working with C# for a week so really fresh sitll
I thought I did that before but obviously it was something different because that worked
your first half of the statement (the true part) is calling destroy before the other values are set I think
That's cool, if you're still learning I'd checkout #๐ปโcode-beginner . They have a lot of resources from the pinned messages . . .
is there any good modern implementation of Thrift for Unity? Latest version which does seem to generate Unity-friendly code without issues out of the box is 0.9.2 via csharp generation, which is quite ancient and doesn't support any modern features like async support
You have a duplicate script in your project
ik i had already deleted it tho
You have another one
Hi guys, it's been a while since the last time I used unity, when I use visual studio code, it shows me the following warning that is wrong and doesn't make sense, I already searched the internet and I still can't find how to fix it, does anyone know how to eliminate those false warnings of unused methods?
PS: I swear to god that if someone suggests "regenerate project files" I will completely ignore it because I have already tried that ad nauseam
make sure that it is configured. those can also be ignored since unity will call those methods automatically
also maybe consider switching to a real !IDE that is actually supported
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
hello guys, so i am making fps game and i wanna make the skin and animations invisable to me and appears to the other guys in the game so what can i type in search to have a tutorial im using photon pun 2
I'm not sure where to ask this
But when I add a rigidbody to an object I have with a mesh collider
the mesh collider seems to 'diseappear'
as in the wireframe disappears
Why would this happen?
Is it because it's non-convex?
Turning the IsKinematic seems to make it come back
Non convex colliders can't be used with moving objects/rigidbodies
it doesnt render because it matches the mesh wire
either unity decided that mesh wire has to have higher order, so it draws over collider wire, or that its redundant because they are equal
How do you get an object from a higher container in Zenject?
what are the absolute value brackets used for
in what context
any
what is " absolute value brackets "
for absolute values obv
the ||?
https://stackoverflow.com/questions/38415007/how-to-get-the-absolute-values-in-each-element-of-array
i can only find this
which is string.Format formatting
wait no, its not
What do you mean?
You should typically just register all your stuff globally for a DI engine, and can inject anything into anything
From a child container get an item from the parent container
Is it ephemeral or registered for DI?
Registered
cuz you should be able to just inject the same thing into the child as well
if you want them to both be the same instance of the same thing, you want it registered as a single (I pretty much register all my stuff as singles, I very rarely need anything other than singles)
I wanted to bind an interface to it only in the child container
Or well, as a single or FromInstance
what do you mean?
Situational injection is usually a code smell from my experience, I avoid that stuff typically
it sort of violates the point of doing all this stuff, that you should just be designing your components to be standalone individually and they shouldnt "care" who calls them or who they call, they just do their own job
@somber nacelle i read one of the links that you share (ttps://code.visualstudio.com/docs/other/unity) there was the solution!, it took it took a little time to understand it and implement it but finally I did it, thank you very much for passing on the information
I am trying to setup a__ one-way platform__ script. The downward input will call on Physics2D.IgnoreCollision between the player collider and the platform collider. I set IgnoreCollision back to false in the "OnCollisionExit2D" call. For some reason, OnCollisionExit2D keeps being called right after OnCollisionEnter2D. I am lost as to why.
!code use a website, discord collapses that
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thanks, will do
When set to ignored, it's likely removed as a colliding object.
How would you guys implement a ledgeclimb?
By using fancy trigonometry raycast to determine if a ledge starts/ends or just use a collider which tells the climbable area via `extends?
Define ledgeclimb
Holding onto a ledge, move left/right till end of ledge, climb upwards or let go/fall off.
At the moment I'm doing a raycast above/infront of player with direction down to look for a reachable higher ground. Next I'm doing a raycast forward at the height of the previous cast to get the wall position. After that, I'm lerping to the desired position on the wall.
Now I want to climb left/right to the edges of the wall but can't figure out an easy way
Assuming you've got some working ledge hang feature implemented, you could simply allow movements to the left and right whilst hanging or climb above. I'm not really sure what you're asking.
How do I detect the end of a ledge
So it's about ledge hanging then. You could either use a collider with callbacks or shoot a few more rays to check if area is valid for hanging.
I want to travel a fixed distance for every button press and play an animation (0.5f).
I could do a raycast at the destination and see if there's still wall to hang on to. But if not, how do I calculate the remaining distance to the end of the wall?
Cut destination distance in half, do another raycast, cut again in half and so on?
Maybe allow it to fully animate but do not translate the position - assuming you aren't changing the position using animation.
No, I want to keep that seperate (guess otherwise it would be root animation?)
Just want to avoid that my character ledge hangs through the air
Looks like a very specific design, good luck - truly.
It should be like something you see in the old Tomb Raider games honestly ๐
Guess I will try something like
// Is there wall at the desired destination
// Is there an appropriate angle on the wall to grab onto
// If not, cut distance in half and check again
// If hit, increase distance by half and check again...
A lot of Raycasts, hope it doesn't take too much performance
When I spawn things with Zenject they get childed to the container they originated from, but in my case the container is on the enemy. When I spawn loot from enemies and destroy enemies, loot gets destroyed too. Any solutions?
Instantiate loot over an item manager?
Will work, but it's a bit complicated, isn't it?
Enemy signals a createLoot() to the manager, it creates loot at position of the enemy with desired loot told by the enemy before he dies.
Kinda like createLoot(position, List<lootTypes> lootList)
Yeah I get it
But then loot won't be able to get anything from enemy's container if needed
Maybe you shouldn't destroy an enemy by deleting it, just deactivate it?
Doesn't sound like a good idea
Why not?
Because because of drop?
Don't you have an enemy manager that takes care of all enemy instances?
What do you mean by drop?
Dont originate it from the enemy
Make a LootManager or whatnot and "bubble up" the enemy death as an event, which triggers your LootManager to spawn loot
So the type of loot that's dropped is stored in the enemy unit, which is known by the manager.
Before the manager "kills" (deactivates) the enemy, it can send a dropLoot to the itemManager, which also deletes the loot after it got registered by the player inventory. Don't know your code, but this seems not too complicated
Hey, I need some help with my normal interpolation
I'm using the example code here uses barycentric coordinates to interpolate normals (https://docs.unity3d.com/ScriptReference/RaycastHit-barycentricCoordinate.html)
but the normals returned dont "scale" with the mesh
the green line is the interpolatedNormal and it keeps the same angle regardless of mesh scale
how would I fix this?
The scale doesn't have anything to do with your normal. It should always be perpendicular to your surface
Normal interpolation, if i'm not mistaken, is a "mean" between multiple normals
the problem is when I scale the mesh, the normal returned is no longer perpendicular to the surface and retains its angle
What do you use to draw your debug line ?
Debug,DrawRay
Can you show me the call to DrawRay pls ?
I linked the example code I'm using
I didnt change any line I was just testing it
Oh ok, my bad
Thought you adapted it
I think that's because the ray is not supposed to be your normal. What the example do is draw a line between your mousePosition and your surface barycenter when your mouse is over a the collider
Yet the Vector is called "interpolatedNormal" and at uniform scaling it returns a perfectly usable normal?
I'm actually confonding DrawLines and DrawRay, the second argument is not a position but a direction, my bad
the comment says DrawLine but the function is a Draw Ray
I'm making a player ability (it's on button press) that will have dynamic mesh generation for visuals, depending on player input. How should i do class structure or where to put what code?
I managed to bandage the issue by correcting using lossyScale so as long as the mesh isn't skewed it should work fine
I created a vector that had it's x as 1/lossyScale.x and likewise for y and z and then scaled n0,n1 and n2 by that vector
would be alot better If i knew how to get the actual scaled normals rather than this bandaged solution so I could also use it with skewed meshes but oh well
on a script on the player object seems like a good start.
The question is way too vague to answer more really
Hello, I am creating a meditation VR app.
While scripting the timer, I noticed that the TMP is not compatible with my script but legacy text works just fine.
Has anyone else had this problem and knows how fix this?
TMP has different types, so you need to adjust your variable to allow the use of TMP
In this case, the variable must be of type TMP_Text
Oh yes! I missed that.
Thanks a lot! @thin aurora
- In my project, I have an "Edge Collider 2D" component, which is essential for triggering an event that spawns platforms for the player to jump on.
- The function "SpawnMultiplePlatformWithEnemyProbability" is responsible for spawning several platforms, precisely eight platforms in my case, each separated by a vertical distance of "2.6f." Inside this function, a for loop will run, for spawning these platforms.
- The variable "nextSpawnPlatformPosY" will store the y position for the next spawning platform, and it will be updated within the "SpawnMultiplePlatformWithEnemyProbability" function.
- In our situation, "nextSpawnPlatformPosY" will hold the value of the top platform's y position minus"2.6f." [Because it holds the value of the next platform y position]
- The objective is to shift the offset of the EdgeCollider2D from the top platform's position to a some position below it.
- In this case, Unity will call the "SpawnMultiplePlatformWithEnemyProbability" function and proceed further without waiting for its completion.
- If, during the ongoing execution of the "SpawnMultiplePlatformWithEnemyProbability" function, we attempt to retrieve the value of "nextSpawnPlatformPosY," it will not provide us with the top platform's value. I hope this explanation is clear.
- My question is, how can I ensure that I wait for the "SpawnMultiplePlatformWithEnemyProbability" function to complete before proceeding further? So that my logic work as excepted in any scenario.
use coroutine/async?
@ashen yoke
Thank you for your response. After conducting some research, I came across coroutines, where people use "yield return null;" to pause for one frame. However, I'm not entirely clear on the concept. Could you provide some examples to help me understand it better?
coroutine runs asynchronously, you can suspend execution with yield indefinetely until some condition you want is satisfied
you can chain coroutines so one awaits another
IEnumerator WaitForSpawn()
{
int countLeft = 10;
while(countLeft > 0)
{
yield return StartCoroutine(Spawn());
--countLeft;
}
Debug.Log("All spawned");
}
IEnumerator Spawn()
{
Instantiate...
while(!completedSpawn)
{
yield return null;
}
}
private IEnumerator Seq()
{
yield return StartCoroutine(ExplodeCar());
yield return StartCoroutine(CrowdReaction());
yield return StartCoroutine(WinningCelebration());
}
like this right? I found it on stackoverflow.
this will run them sequentially one after another waiting for each to complete yes
Thanks for guiding me in the right direction, much appreciated.
Real question, do you need the StartCoroutine ? Or you can do yield return Spawn()
I just started a build without doing the StartCoroutine, hope it works.
yep you need StartCoroutine
I base myself on yield return Mount(user, Dialogs.DialogType.Load, (LoadSaveResult result) => mountResult = result);
Which is working
๐ค
this should only work until first yield
hm
I've been using this for a while.
You don't need StartCoroutine
Thanks for sharing
But if you want to cancel the routine you do need the Coroutine object it returns
@steady moat check this out
IEnumerator Test()
{
IEnumerator[] wait1000Frames = new IEnumerator[1000];
yield return wait1000Frames.GetEnumerator();
}
IEnumerator Test()
{
object[] wait1000Frames = new object[1000];
yield return wait1000Frames.GetEnumerator();
}
yep
just did
im using mec and always sticking with running coroutines through Run, assumed unity would also enforce something but returning any enumerator works it seems
yeah why wouldnt it
at the top level its most likely just a ```cs
foreach(YieldInstruction i in coroutine)
It makes sense, this is not even Unity tricks
yeah
I made an interesting discovery just now. If you call a coroutine function just like a regular method, it will execute as a normal function, and the yield return statements will not work. I thought it was relevant to share this information since we were discussing coroutines.
That doesn't sound right
that is correct
By coroutine function you mean it returns IEnumerator right?
correct
The enumerator you get back is enumerating over the code in the method
But if you never call MoveNext on it (enumerate it) it shouldn't execute, right?
yep its skipped
Yeah, it doesnt do anything
You should read this:
https://learn.microsoft.com/en-us/dotnet/csharp/iterators#enumeration-sources-with-iterator-methods
THis is basically how coroutines work under the hood
and it will explain your observation
Thank you for sharing, it is really informative, I will definitely go through it.
private void Start()
{
IEnumerator t = TestCoroutine();
while(t.MoveNext())
{
Debug.Log(123);
}
}
IEnumerator TestCoroutine()
{
Debug.Log("0");
yield return new WaitForEndOfFrame();
Debug.Log("1");
yield return null;
Debug.Log("2");
yield return null;
Debug.Log("3");
}
private void Start()
{
TestCoroutine___ t2 = new TestCoroutine___();
while (t2.MoveNext())
Debug.Log(123);
}
class TestCoroutine___
{
public int index;
public object current;
public bool MoveNext()
{
switch (index)
{
case 0:
index++;
Debug.Log("0");
current = new WaitForEndOfFrame();
return true;
case 1:
index++;
Debug.Log("1");
current = null;
return true;
case 2:
index++;
Debug.Log("2");
current = null;
return true;
default:
Debug.Log("3");
return false;
}
}
}
yay i did the work of the compiler
No need for a compiler anymore
player.playerInput.actions["Look"].performed += OnLook;```
do I have to unsubscribe input events manually in OnDisable() or does Unity automatically do it?
most likely you have to
cant imagine how unity would deduct your intent
and what mechanism would do it, since you are not binding it to a specific monobehaviour
You have to do it
but you can disable/enable the whole action map in Enable/Disable
or the action itself, im going from the docs
Does anyone have an idea how I can check when a platform I'm moving on will end, so I can limit the movement distance?
Want to avoid to send Raycasts constantly and maybe pre-calculate the destination
put empty objects on the ends of the platform is one way
Sphere/Capsule casting
Yeah but I have to put that onto every climbable object
yes
prefabs!
Otherwise you are likely to have to do some kind of raycasting/physics query
That's what I'm aiming for since I can't forget the empty objects on some of my climbable surfaces ๐
find furthest intersect, filter by collider of the platform, get furthest approximate edge
So overlapping the cast-origins, casting into the direction of the wall and find the furthest hit?
Is the tracjectory known and static ?
I would probably do a raycast downwards from a position slightly in front of the character
and possibly binary search my way into finding the edge
use this instead
sphere cast would project a wide testing tube in into velocity, more reliable imo
can use Capsule cast instead
Will try it, does it also recognise the exit point of the wall collider?
i dont understand
I understand your proposal like this
your initial question i understood as "finding the platform edge"
Like I do a CapsuleCastNonAlloc in front of my player (inside the wall) and check for the furthest distance
you do capsule cast from player towards velocity vector, usually no gaps
you get bunch of intersection points, you analyze them
How do I pass in the value of my slider to this function? Cause right now its always giving me '0' despite the slider was set to the max value
Ah OK, so that's what you meant
you can use it for finding floor edges, walls, next position, lots of stuff
OK, with this approach I only have to look out for not putting two climbable platforms too close to each other I guess, since my default climb distance is 0.5f.
So I'm going to sweep a capsule for 0.5f and see what's the furthest point I get. If there's another platform too close, I would get this as a result as well, climbing over the gap ^^
you can test the collider
if you know the collider you are standing you can filter out all points unrelated to that collider
Right
i see what you mean, yes you can find gaps between colliders, but note that the RaycastHit[] results are not ordered by distance
youd have to sort/split into groups by collider, find closest points between 2 groups to find gap span
probably
Hmm, documentation says For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point.
So when starting the sweep inside the wall, I wouldn't get any distance?
When I start inside the player I wouldn't touch anything
what it would do is do full sweep so you actually get the points intersecting with the wall
I've got an origin and a direction in which the player should move, by sweeping just over the surface the player is attached to, I won't hit anything
Maybe this makes it a bit clearer of what I'm trying to do.
The red capsule is the player, moving alongside the (blue) wall-normal in 0.5f steps, green is a ground layer.
A sweep at the origin of my player into the direction the player wants to climb won't hit anything, since the cast would be next to the wall too (as my player).
Or I'm getting something completely wrong about the CastAll functions
This looks cool
Hello! How are you? I have a problem with Unity. I'm very new to this, and I don't know how to solve it. When I create a script with C# and try to use the Time.deltaTime function, it doesn't work for me. Could you help me with that? Thank you!
error: Assets\Scripts\PlayerControler.cs(16,9): error CS0103: The name 'time' does not exist in the current context
This is what happens right now, just moving further and further.
But yeah, will try the Casts, maybe that's a solution.
Otherwise I have to bite the bullet and use empty game objects
are you sure you are using Time.deltaTime ?
Yes
it's like it doesn't detect it.
show code
Docs say I can include a true or false param to define wherever it includes inactive objects
GameObject.FindObjectsOfType<FastAccess>(true);
This gives an error saying No overload for method FindObjectsOfType takes 1 argument
Oh wait
I created my project with the wrong Unity version smh
Looks like your IDE is probably not configured
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
How do I set it up/configure it?
I linked you the instructions
Thank you so much!
vector3 requires 2 or 3 arguments
public Vector3(float x, float y);
public Vector3(float x, float y, float z);
This is another one that slipped my mind, but the main one is the Time. deltaTime issue.
thank you
that issue is compiler panicing, most likely
one error cascades because you broke syntax
happens in some scenarios
cant say for sure because your IDE is broken on the screenshot
ty
i completley forgot about the OR operator
what is the priority of the new input system's update call?
is it before or after Update() ?
I mean logically it must be before the regular Update()
I'm using dotween, which I like very much and use all the time. I want to use the Elastic easing. The amplitude of the easing is way too high. They seem to allow arguments that should control the easing, but from what I can tell, anything I pass in there makes the amplitude bigger? Anyone encounter this before? What am I doing wrong?
I've tried values everywhere from 1.000001f, to .000001f, to .99999f, to 10f, to -10f
guys my unity is just not responding, and i cant open it, is there a way to stop the game running coz theres probably an infinite loop running
or i just gotta restart unity?
Yeah, just force close it with task manager
alr
force close with task manager . . .
?
Thats what ive done last couple of years
When stuff crashes/starts lagging too much
Has anyone ever encountered an error where a variable is correctly printing out a gameobject value, but then when another method in that class is ran, that same variable is returning null?
are these logged during the same frame or at different times?
The debug.Log i have is in the update method, and so that's printing out every frame. The second instance in which the variable is being printed is in a different method that is the result of an event
we need more info. post the !code with the event . . .
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
What kind of magic is going on
why does this keep on looping infinitetly?
"barsetting.numberofbars" is always 19.
and then, ```cs
while (BarContainer.GetChildren().Count > barSetting.numberOfBars)
{
List<GameObject> bars = BarContainer.GetChildren();
Destroy(BarContainer.GetChild(bars.Count - 1).gameObject);
}
You sure of that ?
the condition must be false in order to exit . . .
"BarContainer.GetChildren().Count" this bit initially is 20, but for whatever reason, never reduces?
even tho im destroying one of the chidlren inside of it
well yea
as it keeps on looping
it reminas same 19
and the count of bars still is 20
each time it loops, so is it no destroying the child of barcontainer?
is BarContrainer an argument of this method?
no, its just a transform that ive assigned in editor
its the object that contains all my bars
this is hella weird, and it makes my game crash coz it keeps on infinitely looping
but i dont know why it keeps looping, its not destroying the object?
can you show the entire method?
quick Q but u see the "HandleNumOfBarsChange" here, unity will exceute it fully right
before moving onto next line
you need to add StartCoroutine to make it a coroutine . . .
Ah right, i will change that thanks, btw without the coroutine, would unity still execute that function fully
before moving on to the next line? right?
nope . . .
ok so its good that i added the coroutine coz i need it to fully execute before moving on
I like that post, it has some good visual examples
Thanks, that does seem quite nice
summarized though:
yield return StartCoroutine(A());
yield return StartCoroutine(B());
B() wont start until A() is over, wrapping method wont end til both are done
var a = StartCoroutine(A());
var b = StartCoroutine(B());
yield return a;
yield return b;
A() and B() run in parallel, wrapping method wont end til both are done
StartCoroutine(A());
StartCoroutine(B());
A() and B() will run in parallel, wrapping method ends asap
This is veryy handy and easy to understand thanks lol
Personally I prefer Tasks though, they dont seem to be quite as a performant as Coroutines, but in return they have a tonne of handy utility methods and make more sense
instead of yield return you just use await, and you get stuff like await Task.WhenAll(...) and await Task.WhenAny(...)
prolly an enumeration thing
For some reason i cant see the value of that
well, while loop is just the first thing that came to mind lol
BarContainer.GetChildren() does this return them in the right order?
if so you can just do BarContainer.GetChildren().Skip(barSetting.numberOfBars) to get all the ones that require deleting
yes they in right order
wait so, what does skip do, it basically gets all items in a list after a certain index?
yeah it "skips" that many in the list
Ah i see
You also can use .Take which takes that many
alr thanks, i will do that, never knew about skip
Destroy does not happen immediately
so if you specifically wanted say, the 6th to 10th(inclusive) items you could do
.Skip(5).Take(5)
Ah thats probably why its looping infintetly lol
oh well, ima go with the .skip way then
seems better
I have a fully built AddForce physics based movment system and am now experiencing a very dumb and obvious bug. for reference here are moves that the player can do to increase their momentum (which is at the core of the game):
- Jumping - Not only upwards, but it pushes the player forwards
- Sliding - it pushes the player forwards and slides the player on slopes
- Dodge - it pushes the player in the direction they are facing
Now. The problem occurs when the player presses multiple of the same button. The statemachine changes very fast and triggers all 3 addforces if prompted by the player. This is undesirable because it makes the player suddenly go at 24 km/h speed.
How can I get rid of this without fundamentally changing those mechanics - the player has to be able to dodge and slide every time during play, jumping isnt AS important, but they still have to jump during those states too - now what??
How do i set prevbar to barsettings, but not like reference to it?
if u know wahtim saying
i dont want bar setting to be updated if i change prevbar setting values
i want prevbar setting to be its own bar setting, but just has its settings set to bar setting here once
Make a new bar setting and assign the values accordingly?
Hello, does anyone know how to add a scalebar to Mapbox Unity sdk specifically on its zoomable map?
prevBarSetting = new BarSetting(barSetting); but idk if thats possible
i dont think it is mhm
Well you can just make a new set of values and set them one by one but thats nasty
I dont think there is a different way to completely copy an object instead of making a reference to it
what is BarAudioVisualizer?
my script
we can't tell you how to make a copy (or if you can) without knowing what the type is . . .
Oh that too yeah
BarAudioVisualizer doesn't tell us anything. is it a class, struct, poco, MonoBehaviour?
so how can i make bar setting
be able to get copied
so BarSetting can be copied . . .
Copy constructor?
just create a ctor that copies all of its values to the new instance . . .
or a copy ctor . . .
Or make it a struct
Thats the same thing lil bro
i cant new() the object lol i tired
personally, i agree with Dalphat. just make it a struct, especially, since it has a few fields and they're all value types . . .
Thats a mind shortcut you dont just new() an object lmao
Default constructor
Just make a struct out of it thats better
Ok, and struct can be copied?
A normal class can too yeah
simply by doing obj = obj?
Yes
well mine aint getting copied for some reason, isntead it was making a reference
a struct is a value type, it's copied by default . . .
i want to assign the prevBarSetting object to another object
basically copy its values
copiedClass = new ClassName(...stuff that the constructor needs..);
But yeah struct is way better
If you need only values
Ok thanks
i will do the copy constructor coz that actually does waht i wanted
How does struct not do what you wanted :33
Its a little more clearer than constructors
Constructors are useful when you have functions within a class
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
class is a reference whereas struct is a value type
reference type assignments copy the reference, whereas value type assignments copy the entire value. Therefore, assignments of large reference types are cheaper than assignments of large value types.
When the class object is instantiated you can provide values that it works off
Yes
I always use contructor workflow so that i can keep an instance of the class and assign values to it
Like a little notepad
is it good practice to separate out player animations into a separate script? (currently have it in same script that handles movement)
Limit the velocity of the rigidbody or the added velocity.
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, MAX);
Limit Velocity:
if(rigidbody.velocity.magnitude < MAX) {
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity + velocity, MAX);
}
(wont work if velocity decrease speed)
Could I ask experts here to have a little look at my repo, which is going to be sent to an employer, and tell me if the code is bad? https://github.com/Telov/SIRGamesApplicationTask
of ur github lmao
What should I change it to...
is there a way to know which meshes take up most gpu rendering time?
Hello having a bit of trouble with saving/loading system.
Basically i've gotten to a point where my game saves/loads fine inside the Unity play mode. But when I upload the game onto github pages or itch.io, saving seems to not be working anymore.
Pretty sure the problem is in Application.persistentDataPath, but I don't know what to replace it with.
Code is in C# and the build is WebGL
have you checked your javascript console when trying this?
How should I handle recoil in an fps? should I have 2 rotations stored, one being the true rotation and the other being the one affected by recoil, add recoil to the recoil rotation and have it slerp back to the true rotation?
basically - and the simplest way to do that is to add another GameObject to the hierarchy
@green oyster There's no off-topic here
e.g.
PlayerBody // < this one rotates left/right (y axis rotation) with player input
CameraRig // < this one looks up and down (x axis rotation) with player input
Camera // < this one rotates for the recoil, and always reverts back to (0,0,0)
problem is I have a bunch of code that uses specific calls using transform.parent(x amound of times)
so I think Ill just use one script
there's no need for this
and there's no need for multiple scripts
cant I just attatch a script to my camera that handles the recoil?
or is there a problem with doing that directly to a camera?
you can attach your script to whatever object you want
my solution had nothing to do with which object the script is attached to
This is about setting up the object hierarchy to make recoil easy in your code
Yeah... dont think its working at all in a browser
I think if you want to write/read files in WebGL you actually need to use UnityWebRequest, rather than File.Write/Read
is it ok to use a SpriteRenderer to render an image within 3D scene, instead of using a canvas and setting it to world space? Thank you
how do you set a blend time for a specific virtual camera?
like the transition between whatever camera and the said camera is x seconds.
can i set this in the said camera without worrying where the blend comes from?
i think will instead do somthing quite stupid
but It may work
hi, im working on photon fusion and I am using cinemachine. When player spawns camera sets follow to that player. camera is not network object and class is monobehaviour. My issue is when a player spawns on my host's camera sets follow to client. how to fix it?
im confused with that
only activate the vcam on the local player's machine
im trying to change the speed of an specific animation, but this changes the speed of everything, how do i change the speed for only 1 animation??
how do i check if its local player
check the photon docs
if (originalMesh == null)
{
Debug.Log($"Error - {meshFilter.name} does not have a sharedMesh!");
continue;
}
Mesh meshCopy = Object.Instantiate(originalMesh);
UpdateMesh(meshCopy);
string fileName = Path.GetFileNameWithoutExtension(assetPath);
string newAssetPath = Path.Combine(destinationPath, fileName + "_" + meshIndex + ".asset");
if (AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath) != null)
{
Mesh existingMesh = AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath);
EditorUtility.CopySerialized(meshCopy, existingMesh);
EditorUtility.SetDirty(existingMesh);
}
else
{
AssetDatabase.CreateAsset(meshCopy, newAssetPath);
}
AssetDatabase.SaveAssets();
what are possible reasons why changes to my meshes are not updating my meshes?
In the above code, if I delete the mesh and make unity create a new one from scratch, it comes out as expected.
However if I do not delete the mesh, the above code won't change the resulting mesh. I am specifically editing the meshes vertex colors
yes, a SpriteRenderer is attached to a GameObject within the scene and is used for 2d; this is the preferred method. UI Image is for the canvas which is in screenspace. the canvas will redraw everything inside of it when any object moves . . .
What is different about ```
AssetDatabase.CreateAsset(meshCopy, newAssetPath);
that is not occuring when I do?
Mesh existingMesh = AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath);
EditorUtility.CopySerialized(meshCopy, existingMesh);
EditorUtility.SetDirty(existingMesh);```
Ok thank you! @rain minnow
EditorUtility.CopySerialized(meshCopy, existingMesh); - maybe my changes arent considered serialized?
so the copy method doesnt carry them over the way making a new one from scratch would? My changes are writing to the vertex colors in this use case
I already do that lmao, the huge impluse is supposed to not happen not be limited
Lowering the clamp is just a bandaid
i already checked and again checked but I still couldnt managed to make it. Should i make my vcam network object or not? Is my logic wrong? checking if local player is wrong idea?
If I have an array of a class type, does Array.CopyTo create copies of the values as well, or will I just end up with two arrays that reference one set of objects in memory ??
what i want to achieve is one camera in scene and set to local player
you couldn't find out how to check if the player being spawned is a local player? then perhaps multiplayer isn't for you just yet if you cannot understand the photon docs
also #archived-networking for networking related questions in the future ๐
.d i just kindly ask my questions and you are saying maybe its not for you lol
both arrays will have the same references
it's a shallow copy so both arrays will reference the same object in memory . . .
if you dont want to help me okay dont help me as i said i already checked and couldnt manage to make it work. sorry if im in wrong text channel.
multiplayer is not a simple topic and beginners who don't know how to read docs really shouldn't be attempting it. if you want to continue brute forcing your way through it, then go for it ๐คทโโ๏ธ
just a suggestion; pls avoid using capital letters while saving files or reading files; ill give u the reason: i was recently working on an ios development; and i would execute a command to create a directory at persistent data path by name "Sample" and it would create it by the name "sample" later when i run the debug log to check if the directory that i just created exists or not; it would throw me with a false; also the same issue happens on spcific manufacturers of android devices as well
So I've been trying to find a solution for a long time and still not sure how to fix this issue. I have two camera, one that has post processing and another to ignore post processing on certain objects that use the layer
IgnorePostProcessing. The problem is any object that is ignored by post processing camera is causing fog to not be applied to these objects. Not sure if this is a unity bug or if I need to change something?
I have attached both the camera settings.
simple simple question
heres some code
side = new string[] { "Black", "White" }[rand.Next(1)];```
to pick a side randomly. Now, sometimes, for some reason I CANNOT figure out, side = "Whitee" and I tried to figure this out for so long and I cant begin to think of a reason why
well it wouldn't be that line of code that sets side to "Whitee". however, i do have to ask why you've decided to create an array there if you're just choosing between two elements. especially if you're doing this often. just use a ternary for that or at the very least instantiate the array only once instead of every time you need to choose a random object
well I only have to choose a side once
okay well then you're still instantiating an array unnecessarily. unless this isn't your actual code and is just meant to demonstrate what is happening
no for now it is the actual code - i should use a ternary for this?
for this specifically? yeah probably. as for your issue, you'll need to show more code because neither of the strings in the array are "Whitee" so that line of code is not assigning that string to your side variable
actually yeah now that you mention it that's probably not it
let me show you all of the function here
if (host)
{
System.Random rand = new System.Random();
side = new string[] { "Black", "White" }[rand.Next(1)];
Debug.Log("Side: " + side);
enemySide = side == "Black" ? "White" : "Black";
SteamMatchmaking.SendLobbyChatMsg(new CSteamID(m_SteamIDLobby), Encoding.UTF8.GetBytes("SIDE/" + enemySide), 1024);
}```
(this runs on both machines, assuming there is one host)
theory - its something to do with the fact i gave it 1024 bytes
anyhow, whatever it is, i still get "Whitee" when decoding the message
I decode it like so:
byte[] message = new byte[1024];
SteamMatchmaking.GetLobbyChatEntry(new CSteamID(m_SteamIDLobby), (int)data.m_iChatID,
out CSteamID sender, message, 1024, out EChatEntryType type);
string messageString = Encoding.UTF8.GetString(message);
Debug.Log("Chat message update. message: " + messageString);```
If this is steamworks.net, their docs are decent. You might be able to find an exact example of what you need there
i think i fixed it hold on
i changed 1024 bits to the length of the encoding
exacto
maybe thats screwing it up idk
ALRIGHT making the byte size array lesser worked from the "Whitee" thing but brand new problem - the converted from UTF8 byte[] string now cannot equal anything else
Four logs
Debug.Log("side == White:");
Debug.Log("Side: " + side);
Debug.Log("Class of side: " + side.GetType());
Debug.Log(side=="White");```
Output attached


trim the string, there's white space you aren't seeing ๐
Debug.Log($"'{side}' is equal to 'White' ? {side == "White"}"); this will show you what i mean
testing this vigorously one sec
dont ask me why how or when but it output this
'White
screenshot it
is this what you mean?
yeah. and that line was exactly the line i gave you?
i think its some c++ issue then with the amount of bytes u are giving
what did u change it to
length of the bytes sent
oh this is different
byte[] enc = Encoding.UTF8.GetBytes("SIDE/" + enemySide);
SteamMatchmaking.SendLobbyChatMsg(new CSteamID(m_SteamIDLobby), enc, enc.Length); ```
it is the ascended string, it screws up everything else
It's probably just got the null terminator in it
that sounds cooler then what it probably is
lemme look it up
huh
a c++ thing
can i even handle it in c#?
theres probably just a different method u have to do for sending/receiving steam messages. I chose to use facepunch instead cause of stuff like this
also i just had an idea
should be able to just trim the \0 character
ive heard good things of facepunch, im trying like 3 networking types to see what works best
thats my next excursion
lemme try that
yeah that didnt work
facepunch it is, we are starting over peoples
that shouldve worked although I couldve sworn the examples ive seen just didnt have to deal with this, what did you type?
message was SIDE/(side) and it seems to really mess things up when i split it by "/" and look at the [1] slot
should just be fine to do .Trim('\0')
tested it myself. if there are null terminator chars at the end of the string that will remove them. if that isn't the character in the string that wouldn't do anything though
BTW congrats this is the weirest programming error i have ever had
i guess this is what happens when you mess with networking
https://github.com/rlabrecque/Steamworks.NET-ChatClient/blob/master/Assets/Scripts/SteamChatClient.cs
you might be able to just do what this person did, they dont seem to have to deal with null terminators
this did not work
added side = side.Trim('\0');
wait
check it
print out what characters you are receiving cast to int so that you know exactly what whitespace characters there are
at this point id just print out each byte of the string and see what it is
honestly got no clue why they do, just one of the drawbacks to using steamworks.net since its written in c++. You'll always have to do some workarounds
Facepunch at least is more concise code but the uh documentation... ๐ป
we'll deal, thanks anyways people
what should i use for sending long blocks of code
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hi, sorry this isn't strictly a scripting question but VSync is taking up ton of frametime in my Windows build, even though VSync is set to "Don't Sync" in Project settings.
It's similar to this topic's issue, but none of the proposed worked for me :/
https://forum.unity.com/threads/unity-framerate-still-synced-to-vsync-instead-of-target-framerate.1350818/
If anyone has suggestions I'd appreciate it
Hey, does anybody know of a way to translate the movements of a real life camera into unity to animate a unity camera.
I'm trying to find a better way of animating a first person cut scene.
You could use a motion controller to record animation, if it doens't have to be an actual camera. Like a VR controller
Well im using MOCAP gloves to track the hands of the cut scene and i was wondering if i could use a camera to do the unity camera equivalent
And i dont have a VR headset
buying a VR headset might be the cheapest way of doing that tbh. Unless you wanna strap your mocap glove to your face lol
Okay, thanks i will look into it
I think there are apps that can track a person on a video then from that, use a simple rig then just slap a camera on its head
Tho idk any
I just know they exist
i have a mesh generated through script, it works just fine in the editor, but it looks like it has no collision in the build
{
Vector3 dir = MyInput.Direction(target, origin);
/*This line is giving me errors*/GameObject projectile = GameObject.Instantiate(item.bulletPrefab, origin, Quaternion.identity);
Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
Bullet bullet = projectile.GetComponent<Bullet>();
bullet.item = item;
rb.AddForce(dir * item.gunInfo.bulletSpeed);
}``` ```public void ProjectileExplode()
{
GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.up, secondaryItem);
GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.right, secondaryItem);
GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.down, secondaryItem);
GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.left, secondaryItem);
}``` For some reason that line is giving me errors in this specific instance. the bullet prefab isn't null in the item scriptable object either
the error is a NullReferenceException
run through the debugger to see what is actually null, there may be a duplicate script where secondaryItem just isnt assigned or really just a bunch of reasons that this is happening
Which line
Nvm I see it
What Bawsi said
which debugger though
the VS debugger, by attaching it to unity and adding breakpoints
is someone here familiar with mapbox sdk? how can I add a scalebar to a zoomable map?
I have the following logic running to calculate required force to move an object an arbitrary speed. I understand speed to be calculated via "s=d/t". I believe thats what I'm doing here. What I dont understand is how it doesnt match up with the rb.velocity.magnitude of the game object. Am I doing something wrong here in the logic?
//update the distance traveled since the last frame
Vector3 currentPosition = transform.position;
distanceTraveled += Vector3.Distance(currentPosition, lastPosition);
//update the time elapsed since the last frame
timeElapsed += Time.deltaTime;
//calculate the speed as distance/time
speed = distanceTraveled / timeElapsed;
//update the last position variable to the current position for the next frame
lastPosition = currentPosition;
//if the current speed is less than the target speed, increase force applied to gameobject
if (speed < moveScript.targetSpeed)
{
moveScript.IncreaseForceFactor(2);
}
else
{
Debug.Log($"Required force to move {moveScript.gameObject.name} at a target of {moveScript.targetSpeed}, you need a force factor of {moveScript.forceFactor}");
gameObject.GetComponent<CalculateCurrentSpeed>().enabled = false;
}
No idea what you are showing nor what you mean by not having the same as the rigidbody velocity
needs to elaborate a bit on what you expect and what you get instead. Also, how are you applying force, just a single impulse or a continuous force? Remember that velocity = force * time
okay, I need help doing a little thing
I need the currentActiveSkill property, to keep the value of the class BasicMelleAttack I puted inside.
At the current momment it works some what, i can save values inside this class that is inside the scriptableObject, but at the momment I hit play, or get out of the unity, the property resets, anyone knows a way to solve this?
it's not a save function, it's a skill builder
I just want it to save the specific skill that I want it to use
If you want to persist values between runs of game, you're going to have to use a saving system like writing them to a file etc.
this SO saves a class deppending of the specific type of skill that I want to edit on that scriptable objec
t
if you want it to have it a specific value at the start of a run just change it in the inspector?
i'm not trying to save a change that I made on runtime, i want it to save a change I have edited before starting the game
Then why are showing melee attack...
Show use the code that is creating the SO.
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I don't quite get it, if you change it in editor, that should be what it starts out when you run it, unless something else changes it of course
okay, gonna try resume the full code
Or unless you do not correct save the value
The code i'm showing is calculating speed of an object. It gets the distance and time then divides them to get the speed. That speed value is displayed in the inspector under Calculate Current Speed. The rigid body of the object has its own speed value that is the magnitude of its velocity value and is shown in the Move Down script. My question is why do they not match.
EditorUtility.SetDirty();
ignore the Byte property, this was me getting desperate
This is a good point and currently its set to impulse. I will change that to the force mode that accounts for mass. I'm also going to remove any friction acting on the objects
Impulse does use mass as well
ForceMode.Force: Interprets the input as force (measured in Newtons), and changes the velocity by the value of force * DT / mass. The effect depends on the simulation step length and the mass of the body.
ForceMode.Acceleration: Interprets the parameter as acceleration (measured in meters per second squared), and changes the velocity by the value of force * DT. The effect depends on the simulation step length but doesn't depend on the mass of the body.
ForceMode.Impulse: Interprets the parameter as an impulse (measured in Newtons per second), and changes the velocity by the value of force / mass. The effect depends on the mass of the body but doesn't depend on the simulation step length.
ForceMode.VelocityChange: Interprets the parameter as a direct velocity change (measured in meters per second), and changes the velocity by the value of force. The effect doesn't depend on the mass of the body or the simulation step length.
shouldnt the force be applied overtime, and not at once like impluse does?
No, every force is directly converted in velocity
If you want to apply a force overtime, you gotta apply it overtime
Ok, gonna try to explain the things,
I have a scriptable object called ActiveSkillMaker, I want to use this scriptableObject to create every single skill I want, by accessing diferent classes depending of the type of skill and them using UnityEditor to edit the values
the active skill maker has some parameters that every single skill will have, but also has a ActiveSkill_Abstract property, this is the class tha has diferent properties and fuctions deppending of the skill that get put in there.
On the editor, there is a enum that you use to choose a specific type of skill you want to edit, once you choose one, the respective class responsible for that skill is putted on the currentActiveSkill, and you can edit it
it works, somewhat, I can edit everything, it works fine and dandy, but at the momment i click start, close the unity editor or anthing that counts as activating the OnDisable(), the currentActiveSkill return to null
If you want to make change on a UnityEngine.Object, you better use SerializedObject. You can also use the EditorUtility.SetDirty();
However, if you do neither, your change are not going to be saved.
already using SetDirty gonna try use serializedObject
also, please look at the link with the full class and other classes afecting the object, it might give a better Idea of what I'm doing. https://hatebin.com/kduqoszguo
You are not modifiying the object through a serialized property thus it will have no effect to call serializedObject.ApplyModifiedProperties();
If this is the case, then impulse is probably what I need to continue with since i'm increasing the force applied by 2 each frame. After removing friction and continuing using the forcemode.impluse, the result is still not matching with the speed calculated by the rigid body. My expected result is the speed value in the Calculate Current Speed script to match the speed value of the rigid body of the object.
Did you try use an increment of velocity instead of add force
If it does not match, then your code is most likely wrong
this is a relique of older attempts of doing that
I've use Unity Physics to predict and calculate shot, it is pretty accurate. (Not academic accurate, but enough)
Adding force is a hard requirement and thats what i'm trying to figure out with my code. What is it that my code is doing that is incorrect
It has nothing to do with solving your issue at hand.
Isolate the issue.
Reduce the paramters
This will lead to something working
Then take it from there
It is way easier to proceed from working code then non working one.
Assuming the rigidbody.velocity.magnitude is correct, I can safely assume my issue exists in my CalculateCurrentSpeed script. I'm not sure how to reduce the parameters anymore than it currently is. I get distance and time, then calculate the speed. I've removed friction and updated the code to execute on a fixed time using Time.fixedDeltaTime and using FixedUpdate.
You literally need only 3 things. There is way more than that.
- Set the velocity to X value each frame
- Get the first position and the current position
- Divide by the accumulate time
You could even calculate the instantaneous velocity.
You also have 2 scripts
how do i make a method accept an argument?
By following a tutorial on C#
I think I have been confusing myself with my understanding of how forces work. If I continuously apply a larger and larger force which is what my script does to reach a target speed, that isnt going to tell me what i'm been looking for with accruacy. That will only tell me the amount of force I was applying at the time of reaching the target speed. I think what I'm actually trying to accomplish is figure out the amount of force to be applied once to instantly reach the target speed.
could i actually get an answer on that?
if you googled it , it would probably show up
public void SomeFunction(string someStringArg) {...}
I mean, it is one of the first thing you ever gonna learn.
shit lmao i forgot the type part
i just wrote the parameter without specifying
i learned this i just forgot, thank you
that would work if you were coding in javascript, but gotta be more specific with types in c#
No idea what you want, however here is my code that solve the velocity required to make a shot:
private void SolveForVelocity(Vector3 startPosition, Vector3 endPosition, float gravity, float angle, out Vector3 velocity)
{
//x = v * t
//x = v * cos(a) * t
//h = v * sin(a) * t + 1 / 2 * g * t ^ 2
//t = x / (cos(a) * v)
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2
Vector3 delta = endPosition - startPosition;
float x = Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z);
float x2 = x * x;
float h = delta.y;
float g = gravity;
float sin = Mathf.Sin(Mathf.Deg2Rad * angle);
float sin2 = sin * sin;
float cos = Mathf.Cos(Mathf.Deg2Rad * angle);
float cos2 = cos * cos;
float r = Mathf.Sqrt((0.5f * g * x2) / (h * cos2 - sin * x * cos));
Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
velocity = direction * r;
}
The velocity is correct and land directly on the target
private void UpdateForVelocity()
{
SolveForVelocity(origin.position, target.position, Physics.gravity.y, angle, out Vector3 velocity);
Vector3 direction = new Vector3(target.position.x, 0, target.position.z) - new Vector3(origin.position.x, 0, origin.position.z);
this.transform.rotation = Quaternion.LookRotation(direction, Vector3.up) * Quaternion.AngleAxis(angle, Vector3.left);
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject projectile = Instantiate(prefab, origin.position, origin.rotation);
Rigidbody rigidbody = projectile.GetComponent<Rigidbody>();
rigidbody.AddForce(velocity, ForceMode.VelocityChange);
}
}
What i'm trying to accomplish is figuring out the required amount of force to add to an object using AddForce() to make an object reach a target speed instantly. Though I appreciate the script and your help. I believe I have another route to take to figure out a solution though its more of a brute force than actual programming magic. This script will save me some time later on down the road.
Applying an X amount of force only once to reach a target speed of 100 for example
So, you have an acceleration ?
And you want to transform it in velocity ?
m/s^2=m/s/s
acceleration = velocity / time
acceleration * time = velocity
Also, I do not understand the fundamental requirement of that.
Because, you can simply set the velocity
F = ma, apply an impulse of 100 * mass to accelerate to 100 m/s or whatever your scale is (excluding friction and drag). But like Sim said, there's a forcemode specifically to do this anyway
I want a method to run in void update, but only once triggered, and stop once it reaches a certain point. I can't quite figure out the logistics.
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
as far as running the method for a duration you can learn about coroutines to take care of it or you can keep track of your time by using Time.deltaTime (time elapsed since your last frame). Everyframe you can update a value that is keeping track of the time between each frame such as the following
float elapsedTime = 0f;
elapsedTime +=Time.DeltaTime;
if(elapsedTime >= duration){
//You will do whatever you need to do to stop once it has reached your target duration
//do something here.
}
@hidden flicker
this is not perfect and you will need to fit it to your code
I didnt know how much force I needed to accelerate my object. All I knew was how much mass the object had.
F is the amount of force, you need 2 out of the 3 to get the missing one
by trial and error, i found the mass (100) needed a force of 500000 to acellerate my object to 100
yea i know
that was my whole question
I wasnt sure how to accomplish that lol
the force was only going to be applied once
accelerate*
I guess my question is, how can I programmatically figure out how much force I need to apply to an object once to accelerate it to my target speed instantly.
โaccelerateโ and โreach target speed instantlyโ are two separate things.
Do you want to set the velocity so it instantly reaches the target speed?
No I need to use AddForce so I cant set the velocity directly
so accelerate would be the wrong word I suppose since it would reach the target speed instantly
Depending on what youโre trying to do, you might be able to get away with not using AddForce
Why do you need addforce for this
At this point I can go in any direction but I want to limit it to AddForce for potential later applications and my own personally learning
Tbh I still donโt really understand why, velocity gives you perfect control over how the object moves.
I was trying to make a menu for my game but the input module wasnโt picking up the axis of the left stick
You can use a PID algorithm. Itโll attempt to add force and decrease it over time as the speed gets closer to the target. The reason why you canโt really calculate it is because Force is mass * acceleration. To instantly (near instantly) move an object to a target speed, you have to add a super high acceleration to speed it up, and then a low one so it doesnโt accelerate faster.
https://youtu.be/y3K6FUgrgXw this shows it off in unity
You could add a force that is (targetVelocity - currentVelocity) * someMultiplier
If you want to gradually reach targetVelocity, that is
playing around with it, this seems to have gotten me close but I had to apply a real number duration
public class ForceCalcuator : MonoBehaviour
{
private Rigidbody body;
public float targetSpeed = 100f;
public float accelerationDurationInSeconds = 1;
private bool onlyOnce = true;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
if (onlyOnce)
{
onlyOnce = false;
float requiredForce = (body.mass * targetSpeed) / accelerationDurationInSeconds;
Debug.Log($"Force required {requiredForce}");
body.AddForce(Vector3.forward * requiredForce, ForceMode.Impulse);
}
}
}
A small example with just a P controller (PID but just the Proportional term):
float diff = target speed - current speed
rb.AddForce(diff * 100);```
If the difference is positive and itโll add speed in the positive direction, and vice versa. If the distance is small itโll add a weak force and vice versa. Itโll have this back and forth feeling of high speed and low speed so you need to tune it correctly
^ yup this is an example
I will try this as well
Is this part really the performance issue of your program? If it's an insanely large list, I would store the average and recalculate it purely based on new entries or removed entries
How big are the lists you're running through this? Or how often are you running the method? It would have to be a pretty big number for it to make a difference in performance.
How many lakes on average?
The .Contains might be a bit heavy here
Hello, is there a way to make a collider that changes shape over time? Or should I have it destroy and then re-create with the new shape each frame?
Contains is way faster on a HashSet than a list, but then again Add is slower
So I cant say for sure
void Update()
{
var gyro = Input.gyro;
var cameraRot = gameObject.transform.rotation;
var newRot = Quaternion.Euler(cameraRot.x, cameraRot.y, gyro.attitude.eulerAngles.z);
gameObject.transform.rotation = newRot;
}```would anyone know why this code still allows the camera to flip when i rotate my phone on the x axis?
Also, if a collider moves from point A to point B the next frame, will it collide with things inbetween point A and point B, even if they collider itself is not in that position on either frame? Hopefully that makes sense
Depends on how many bad lakes there will be. The threshold is around 5 elements I think. Anything less than that and the linear search beats HashSet.
How do you move the collider?
I guess I would have it be in one position, and then the next frame update it's position to the new one, unless there's a better way
There's a limit to how optimized you can make the compares. At some point, you need to reduce the number of compares. This could be done by reducing the number of lakes you spawn, or by using a spatial tree, like a quadtree.
You need to move it via a rigidbody to accurately detect collisions. Using transform or collider.center to move it is not reliable
hey all. I'm trying to make a canvas to display icons for units in a game. I want to cull icons when off screen. Is there a quick way to check if a vector3 is within the view frustrum?
So like RigidBody2D.MovePosition() would work?
you would have problems running anything 5 million times
It should
okay, thanks
Contains will get linearly more expensive relative to amount of items in the list
you may have to implement some other data structure then, so your methods can have early outs
And so in this case I would want a kinematic rigidbody specifically is that correct?
In that case list is probably faster
Linq has Array.Contains but I think its pretty slow
Never used
Just assuming tbh
still you could cut out performance time by doing what i said with the list before, storing the average instead of recalculating every single one
Non kinematic will work at least, and kinematic might work in 2D, not sure. It depends on a setting in the physics setting AFAIK
Can you use dfs to flood fill each lake? then get the โcenterโ of each lake when running dfs?
is that not what .eulerAngles does?
im sure theres a lot of ways to do it, i would probably have some struct or class for a lake though where you store the x,y and the average is calculated internally
list.contains is also typically slower than hashset.contains as well, so if you can conver to that and get away with it, might offer some better performance
var cameraRot = gameObject.transform.rotation;
You then use cameraRot.x and cameraRot.y
@swift falcon Also note that List is not thread safe to write to, so it's not safe to use inside a Parallel.ForEach. You might not be seeing issues now because the Parallel.ForEach might not actually be parallel, but it could be on other computers.
Depth first search
profile it ๐คทโโ๏ธ
how much is a big slowdown, world generation especially for 1 million tiles is gonna always take a little bit of time
if you're talking like a minute, just slap a loading bar on that
I will consider using a dfs and get all center of the lakes and do nearest neighbour search find out the lakes close to each other and you can start dfs again to flood fill the lake from its center
You would have to lock every usage of it, because you can't have a thread try to read from it while another thread writes to it at the same time.
And a lock will slow things down.
depending on what you're generating (like its compexity, etc) you could offload to a compute shader, provided whatever platform you're building for supports it (most do these days)
thats what im doing ?
individual axis are just getters, not setters and you cant add vectors together
he is saying you are using the quaternion values and plugging them into somewhere that expects eulers.
which is wrong
thats why i turn it into a euler angle first gyro.attitude.eulerAngles.z
var cameraRot = gameObject.transform.rotation;
var newRot = Quaternion.Euler(cameraRot.x, cameraRot.y, gyro.attitude.eulerAngles.z);
Yes, and where do you do that for cameraRot?
sorry for potato quality video, but if you're just doing simple mesh generation, compute shaders are insanely fast. This video im using marching cubes to generate a big mesh every frame with a noise function at over 500 fps https://i.imgur.com/ZDjXyou.mp4
did u read what i wrote
Sure, but concurrent collections have their own performance concerns.
https://hatebin.com/yohgdjimfz
So i have code here that is for a 3d unity player for a first person game, the code is for a grabbing mechanism like in the game portal, so basically it consists of a grab range in which how far you can grab an object, a grabbable mask, in which to tell apart which objects you are allowed to grab, and a Hold position (The game object in front of the player which will determine the position of the grabbed object. Where im having trouble with is the part is the Hold position gameobject following the mouse x and y axes like the camera does. Please help I don't know how to do this, Note: There is also an anchor gameobject placed in the same area as the camera (In the head of the player) which acts as the object the Hold position gameobject rotates around. The hold position gameobject is a child of the anchor and the anchor is a child of the player.
You would have to run all the generation on a separate thread.
how do u have 500 fps, i dont even get that in an empty scene and i have a pretty good pc
the mesh is being fully generated in parallel on the gpu using a compute shader
is there even a point of doing this then?cs var newRot = Quaternion.Euler(cameraRot.eulerAngles.x, cameraRot.eulerAngles.y, gyro.attitude.eulerAngles.z);
or do i just use all quaternion values and it works the exact same
Do not read or write directly to quaternion members, it will not do what you expect
Do you use AsyncGPUReadback?
Only through the helper methods will anything valid happen
you could also break each thing down into a chunk and write without locking where each thread writes to its own chunk instead of one big list where you have to lock
@swift falcon do you want to find out all the center of all separated lakes and find out some closes pair then remove one lake of these close pairs?
i have, but in this example, im actually also rendering it on the gpu directly from the buffer the compute shader is writing to, so i dont need to read it back, but yeah if you want colliders to work, you'll need to do the read back
which helper methods should i be looking into? visual studio says ToEulerAngles() is deprecated
if(!player.GetComponent<LockOnHandler>().visibleEnemys.Exists(gameObject))
{
player.GetComponent<LockOnHandler>().visibleEnemys.Add(this.gameObject);
}
this causes C1053 error: cannot convert "UnityEngine.GameObject" to "System.Predicate<UnityEngine.GameObject>".
What should I do?
just dont do any of the generation on the main thread, and only move the data over to the main thread once you've finished generating the chunk or w/e, that will prevent the game from freezing even while the genration is happening
You should use the Quaternion Class functions that deal with Euler angles - Retrieving, modifying, and re-applying Euler values from a rotation can cause unintentional side-effects
is Quaternion.Euler() not a valid helper method?
It's totally fine
then im confused about which part of that code snippet i sent which is incorrectly using quaternion members
You were reading x and y from a quaternion, cameraRot
the TL;DR w/ unity afaik is, unless ur using the dots job system, you can't do anything that interacts with the engine directly outside of the main thread, but a mesh is just a set of data, so you can easily generate that outside of the main thread without needing to use any unity functions, then onces done, you can convert it to a unity style mesh on the main thread
i was reading from cameraRot.eulerAngles.x/y/z
oh mb i had changed it since then
just google multi threading tutorials for c# it works the same
but doing it this way is the correct way yes?
Yes, though it may or may not do what you expect depending on the values of the euler angles because euler angles are truly an annoying system of compound rotations performed in a specific order (Z, X, Y)
i really just want to disregard every axis except for tilting the phone on the z axis. if theres a better way, i'd love to hear it as my current experience with the way i've been doing it has been really rough
I have a class (Gamestate) implementing an event (PropertyChanged), that invocation of it is not publicly exposed (it gets triggered via unexposed logic internally.
However, I want the ability to open a "transaction" that will not invoke the event until the transaction is finalized, as an IDisposable sort of deal, with a filter.
Something like:
using var transaction = GameState.OpenTransaction(g => g.UI);
GameState.UI.Blah = whatever; // << This would normally trigger the event, but it wont inside the transaction asap
GameState.UI.Foo = something;
GameState.UI.Bar = somethingElse;
transaction.Commit(); // This will cause a *single* event to now fire off, rather than multiple
I want the transaction.Commit() to trigger the event which is on GameState, however, I dont want the method to trigger the event to exposed to anything else. Right now its private.
Thoughts?
okay so it doesnt respond to the x axis changing, but it does this weird 180 flip when i pass a certain angle on the y axis
hello people of this server
im not sure if this is the right channel
but
i cant jump in my 2d game on unity
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float horizontal;
private float speed = 8f;
private float jumpingPower = 16f;
private bool isFacingRight = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}```
this is my code
That is because you are resetting your velocity every frame.
This was informative, thank you for the suggestion
ill let u know if it works ty
can u tell me where im resetting my velocity every frame
This is what I ended up coming up with for having a concept of "opening" transactions so far, I think this will work?
https://hatebin.com/bgrmoijhbn
I should now be able to simply open a txn like so, I think:
using var txn = GameState.OpenTransaction();
GameState.Something = something else // wont fire event just yet
GameState.Foo = bar;
GameState.Phi = baz;
txn.Commit(); // Now the events will fire, and only distinct ones in case of overlaps;
https://www.spawncampgames.com/paste/?serve=code_926 full script here, but i think i included the relevant bits
im looking through old repo's currently, trying to see if i can't find it
i set up my input button it still displays this error
ArgumentException: Input Button space is not setup.
To change the input settings use: Edit -> Settings -> Input
UnityEngine.Input.GetButtonDown (System.String buttonName) (at <dbc9087e67094ae597a416f542bc9023>:0)
PlayerMovement.Update () (at Assets/PlayerMovement.cs:37)
Because it's Jump not space
Don't use strings for Input parameters
Use the KeyCode enum for it instead
KeyCode.Space
And what is it?
ArgumentNullException: Value cannot be null.
Parameter name: source
UnityEngine.AudioSource.Play () (at <ffe857c3421441dd831fcce832acbe2a>:0)
PlayerMovement.Update () (at Assets/PlayerMovement.cs:39)
Well you haven't assigned the audio source have you
You haven't assigned the audio source into the inspector or referenced it using GetComponent
So why do you have this line just sitting around in your code?
What is on line 39 in PlayerMovement?
Avoid using GetComponent if the component is already present
(You can use it in Reset though)
my team member for a group project wrote the code
Doesn't matter, show us the error code . . .
let me check
Are we pointing fingers or trying to solve a problem?
{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
jumpSoundEffect.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationState();
}
34-44
liines 34-44
jumpSoundEffect.Play();
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Not easily readable. Which is line 39? That's the error line . . .
Then check if any reference variable on that line is null . . .
This becomes easy as there is only one variable on that line . . .
question about spawning using coroutines
Check that jumpSoundEffect is assigned and not null . . .
In my game. I am gonna use a auto aim feature when user so that clicks the fire button (on mobile) it fires in the direction of the enemy automatically... I have made characters with all four sides attack animations... is it possible to play the correct animation according to direction in which the user aimed and attacked by pressing the button ???
Hey, using C# delegates for events currently, should I be using UnityEvents instead? Is there any resources for how to do so?
Running into issues with re-loading scenes not resulting in a proper reset, but there's probably many other solutions to this.
public delegate void EInt(int value);
public static EInt OnNewScore;
// sub/unsub in some GameObject's OnEnable/OnDisable
unity events are basically just a serialized event, what part is not actually being reset?
just stating as well, the code you've shown isnt an event at all, its just a delegate. An event is specific where you cant invoke its logic outside the class, only the add/remove listener functions are exposed
TBH I don't know, the main issue is the InputManager bindings that refer to Scene objects, some of them stop working on scene reload. I was hoping, by moving to unity events, I would be able to invoke the events from those bindings directly, instead of the bindings referencing a scene object's function that then invokes the events.
where is InputManager?
reloading scene not reseting, do you have domain reload on play disabled?
or you mean reloading in editor, opening another scene?
the only way the statics are cleared is on domain reload
otherwise you have to use [RuntimeInitializeOnLoadMethod] for runtime and InitializeOnLoadMethod for editor
Sorry I was wrestling some Plastic issues lol
Oof yes ๐๏ธ
So I have two kinds of bindings: one to an in-scene Player class' public methods. Those work OK.
The second to a singelton manager, that works the first time. On scene reload, it stops working though.
its all there
can anyone please tell so that I can procced with my project further
I mean reloading as in starting the current scene again, like
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
runtime?
Yeah at runtime
Yes it is possible
your question is just is X possible, which the response is yes. You just have to code it to work
that sounds like a bad design, because it means you would have to handle clearing statics yourself when you switch scenes
ok ty
thanx
xy issue, what are you trying to achieve
Not enough details.
Is it 2d or 3d? What does the "four sides attack animation" mean and why would it be related to autoaim? Does the user actually aim at all or is the autoaim supposed to choose a target?
if its just a singleton the problem is in the code of your singleton instance getter
show it
Make the "restart level" button keep working after the first reload
I don't 100% think the input binding goes to the Instance though
public static GameManager Instance { get; private set; }
void OnEnable()
{
if (Instance == null) { Instance = this; }
else { Destroy(gameObject); }
}
just the button doesnt work?
2D, a top down game have animation for four side movement, up down left right, like that.... user will just click the button and the nearest enemy will be hit by user
Sorry brainfart, the escape button (to bring up the pause menu) stops working. Previous issue was that it would come up but the reset button wouldn't work, but I broke it further lol
looks like spaghetti, input manager which should not know of any of the consumers of input is somehow PlayerInput at the same time as InputManager, and stores a reference to GameManager
I think I just followed the Unity quick start guide, I guess if I bind in OnEnable it might continue working?
Ok, well, your auto aim should only be responsible for getting the direction to the target. Animating the character should be handled by the character controller. For example:
- Button pressed
- Character controller gets the direction from the auto aim
- Character controller checks if the character is facing in the right direction and changes animation if needed.
- Character controller start the shooting logic.
etc...
i cant deduct your scene structure from that
im trying to understand - the PlayerInput should dictate which method is being called when input happens?
thats the idea?
yea thanks for the overview. It will help me to write the code
are all the unity events referencing objects in the same scene and are present at edit time?
For now yes, created a bunch of inputs and bound them to in-scene objects in the GUI in the screenshot. Probably stops working for other levels though
where is this InputManager located?
Yes, all referencing in-scene objects, should be present at edit time
MainLevel looks like this
do you know which variable becomes null on scene load?
I don't think it's a null reference issue? It's just that the Toggle Pause action doesn't call the relevant method any more
ok, are you enabling/disabling the action map?
Nope, it continues working (mostly) because I can still fire and aim after the reload.
Yeah, I'm guessing something to do with the singleton-ness
do you see the event in the inspector after load?
public void RestartLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
IsPaused = false;
SetPausedState(false);
}
thats not TogglePause
others dont?
Yeah the others stay bound
Must be referencing an object that gets destroyed.๐คทโโ๏ธ
is Managers in DDOL?
public void TogglePause()
{
Debug.Log($"TogglePause called with {IsPaused}");
IsPaused = !IsPaused;
SetPausedState(IsPaused);
}
void SetPausedState(bool pauseState)
{
if (pauseState)
{
Time.timeScale = 0;
AudioListener.pause = true;
Events.OnPaused?.Invoke();
}
else
{
Time.timeScale = 1;
AudioListener.pause = false;
Events.OnResumed?.Invoke();
}
}
I don't think so
What exactly is referenced here originally?
my guess is, the scene has a reference to manager serialized in the event
new scene is loaded, your singleton still sees the value in static field
destroys the newly loaded manager
the reference is invalid as a result
in your case you are misusing static backing field
typically the intent is to keep a single instance in it over the lifetime of the game
but it wont work with your setup
because you are serializing references to specific instances
The simplest solution would be to call a method on the same object. Something like OnTogglePausePressed in an InputHandler component or something. That would do something like GameManager.TogglePause().
or to invert it and hook events dynamically from the observer
Yeah that's what I was considering, or moving to the actual event system directly. Just need a local, static message bus essentially
When you write
Debug.Log($"TogglePause called with {IsPaused}");
what is the difference between that and
Debug.Log("Toggle Pause called with " + isPaused);
class GameManager
{
void OnEnabled()
{
InputManager.Instance.onPause += HandlePause;
}
void OnDisable()
{
InputManager.Instance.onPause -= HandlePause;
}
}
first is string.Format
second is string concatenation
google interpolated strings
google all 3 things
Ya I did and it says that it will evaluate the variable that is in curly q's
does the second not do that?
second does ToString() same way first one does, with one difference, no format, and each + will allocate a new string
you are chaining string.join
What's InputManager here? Is that my scene object?
that is the script with your input events
PlayerInput in your case
Hmm it's all setup in the GUI for now, might need to change that
oh so for the example that I used, if you wanted to add more variables in, its less writing at least...I could in theory do $"This {var1}{var2}{var3}{var4}" where in concat I have to "This" + var1 + var2 + var3 + var4
and even then it wouldnt look pretty because I dont have spaces
I would need $ before it though
It's optional syntax you can use if you prefer it. I would question why you are printing multiple variables with no spaces in between though lol.
It does have some helpers to format numbers, dates, etc.
You can add spaces in both cases. "this" + " " + var1.... The main difference is just a matter of preference + memory allocation(the latter one doesn't matter in debug environment anyway usually).
ya I hear you! Thanks...I ask some questions but enjoy reading the posts as well to learn so just follow up off other users as well
gotta be self aware
just wanted to mention that you don't have to use brackets with ternary operator
but that's more readable
yeah it's just for readability
Thanks so much for all the help! I ended up moving to SendMessages instead, and adding small functions to invoke the events desired instead. Seems solid so far, cheers!
since you ended up using cursed SendMessages, i havent provided any help at all
Is there a generally better option? The messages are basically syntactic sugar to auto-subscribe for $EventName to the method On$EventName
syntactic sugar is when compiler compiles code into something else
hello jason's simulation
SendMessages is runtime construct, resolved at runtime, using reflection or whatever unity does
yes there is a better option, rethink your architecture so that observers can find the observables
do u know what this error is ?
reset layout see if it fixes it
i still got it
Try restarting Unity then
How Do I get the direction of enemy to update this parameters... I am using auto aim... the nearest enemy will get hit by the Player when user clicks button (on Mobile)... but then to play the respective animation how will I get the direction of the enemy... I have four attack animation for all four direction ( as we do in 2D movement animation)
I want that when enemy is upward the vertical_attacking float should be -1, when its Up vertical_attacking float should become +1 .. same for the left and right
so that the correction animation play on correct time