#archived-code-advanced
1 messages ยท Page 134 of 1
I could be wrong but if it reads the 1 as an int it might be rounding t in that check which means once it goes above 0.5 it rounds up to 1 - which would explain why you don't see 0...0.3...(0.6). Just a guess.
I always put f's after all my numbers just in case.
unfortunately I gotta run, hope it works ๐
thanks for the help!
interesting, trying it rn
Shot in the dark.
no, it should not be the case, t is declared as float so no rounding. but, do mind that if you try to Debug.Log(Vector) it will print values rounded to 2 decimals, so always log .x and .y separately.
And use .ToString("F7")
but anyway, it should stop working only if t goes over 1 and so the loop is considered finished or your coroutine is stopped for whatever reason (disabling game object or monoB component or calling StopAllCoroutines() from somewhere else (like stopping a sound ๐ ) or...)
to be sure, define your t before the loop and then log it after the loop is done, that way you should see when it stopped (what is the value of t) and if you don't see it, then the coroutine was stopped externally (i.e. not finished by reaching the end)
putting rb.position = endPos; at the end worked!
well doing that will of course work, but how will it look?
its really weird because before it would only move like 2 steps and then stop and now with that line at the end it moves all the way through the lerp smoothly
i was expecting it to move those same 2 steps and then teleport to the end
Because it's <1 and not <=1 it never actually reaches the end of the lerp
yeah but even with <= it doesnt work
Hm
Well with such small values it probably gets very close to 1 and then the next value would be over it
anyway, try defining t outside the loop and log it inside and after the loop and see the values, it might give you some insight ๐
So it wouldn't matter if it's < or <=
i thought since the for loop increments t when t < 1, when t reaches lets say 0.99 its still below 1 so the for loop increments it one last time
and then its 1 or above
Good point
Actually no I don't think it would run that last time. The increment happens at the end of the loop and then the check happens at the beginning
well yeah, that is how for loop works:
- take initial value
- check the condition
- if true, do the statement
- change the value with given step
- go to beginning (step 2)
3b. if false, finish the loop
So yeah you were just missing that last frame of movement and setting the position at the end fixed it. I think. Lol
so it increments before it runs the code within the loop?
Increments at the end of the loop, then starts over and checks the consition
no, first time it is what you set as initial, every other time it is after "increment" (it can be decrement or whatever)
I did write the "algo" for "for loop" event though it is not the best way to represent it ๐
so if i print t, i get this in the console:
0
0
0.2
3.533333
seems like it isnt smoothing it like i thought
ok so now you know why it stops in 3 steps ๐
Wow that's exponential
so Time.deltaTime the first time was 0.2, then something greater than 0.8 so the loop finished?
as a debug tip: you can try and leave "breadcrumbs" meaning, you can drop a cube or other primitive on every new position so you can visually track your coroutine. you can also draw that as a gizmo...
yeah i am moving the player while im doing this but it seems smooth
and as @lucid bronze said, log the deltaTime at the end of the loop
t = 0, delta = 0.02
t = 0, delta = 0.02
t = 0.2, delta = 0.02
t = 3.5-ish, delta = 0.327
got it
but I think your culprit here is WaitForEndOfFrame, because it will actually wait for it before using deltaTime, it is better to just yield null since this is a coroutine and it will be executed once pre frame, after Update
at the end delta time spikes up
since I have no idea what deltaTime is after frame ended ๐
huh?
it goes from 0.02 to 0.327
Yeah but that doesn't correlate to the spike in t.
it might be just some "random" value that will be set to a correct one at the beginning of the next frame
Hey so my ItemPlaceable inherits from ItemBase, but when i try to cast itembase as itemplacable i get specified cast is not valid
This is kinda out of my brain
i'll try printing time.deltaTime in update istead
You could try yield return new WaitForSeconds(0.02f)
@lucid bronze yielding new WaitForSeconds every time will just create garbage ๐
@modest lintel you are correct, but his coroutine is updating t with deltaTime value after the frame ended
its not changing in between its changing at the last iteration of the for loop
Yeah I figured. Honestly can this whole thing just be in a FixedUpdate loop vs a coroutine?
well yeah, use fixed update, or just try yielding null
@foggy umbra you cannot "downcast" the base class to inherited class, because it is just... not
yep already yielding null
@solar parcel and it should work? since dT should be correct
yeah time.deltatime is oscillating a lot which is probably the cause for the spike
What is dashSpeed set to?
anything above about 3 breaks it, which is why i set it to 3
but below that its fine
3 x 0.327 does not equal 3.5ish
not really sure how that makes a difference.
private IEnumerator testRoutine()
{
int t = 10;
while (t-- > 0)
{
Debug.Log($"Frame start, delta = {Time.deltaTime}");
yield return new WaitForEndOfFrame();
Debug.Log($"Frame end, delta = {Time.deltaTime}");
yield return null;
}
}
I'm getting exactly the same values here
but if you yield null and dT is spiking... then something else is your problem ๐
Does your game have a bunch of other stuff happening in Start()? Could have an FPS drop if you're loading a bunch of stuff.
well if theres an fps drop i would need to account for that anyway but no ive commented out all other code
Try putting the code in FixedUpdate and use a state book to trigger the dash or something.
bool*
if (isDashing) {}
It has to just be that Unity doesn't like doing physics work in corroutines. That's my best guess
but how would i wait for the next frame in fixedupdate()?
You don't, it does that for you.
so it wont run the entire loop in one frame?
well... you cannot put the for loop in there ๐
Yeah no for loop
Declare t outside the method and then check for t < 1 yourself and set the isDashing book to false if so
bool* sorry I'm on mobile
yes ๐ and of course do your own check for when dashing should go to false
what @lucid bronze said ๐
@foggy umbra ah sorry I am in some deep c++ stuff, so my brain just randomly connected different concepts ๐ it should work ๐ provide some more info please?
it dashed in like 2 frames and each frame was rendered like 2 seconds apart from eachother
Show your new code
oh wait my dash speed is really high
never mind i mixed up 2 different variables
ok so with dashSpeed set to 2 it looks like it goes to like 30% and then jumps all the way to the end, but if pause the game and step through each frame manually, i get the behaviour i want
heres the code
pausing the game and stepping is not a very good idea..... since the frame render will have all the time in the world to finish up... if it is jumpy, maybe profile it?
since fixed update should happen at fixed time intervals but the render will happen when it can
float dashSpeed;
float dashDistance; //both serialized
Vector2 endpos;
void Start() => endPos = rb.position + Vector2.one * dashDistance;
void FixedUpdate()
{
if (t < 1)
{
t += Time.deltaTime * dashSpeed;
rb.position = Vector2.Lerp(rb.position, endPos, t);
}
else return;
}```
and of course rb is cached
try leaving those breadcrumbs
alright
You need to grab the startPos outside the method too
๐
no man ๐ cannot use deltaTime in fixed update, you must use fixedDeltaTime
since that is the whole point ๐
Set startPos in the same place you set isDashing to true.
well instead of using a boolean i just start the dash immediately and then when t > 1 i finish so no need for a bool
and startPos is just rb.position so no need for storing that either
at least i think
That'll work once
yeah
I'm assuming you want the player to be able to press a button and activate the dash
but the lerp is not good here
alright im trying time.fixedDT
since you are lerping between current pos and end pos with increased t every fixed frame
oh yeah
you should lerp between start fixed and end fixed and only change T
haha
and as Unity says: if you are changing rigid body position you should always do that in fixed update
well i guess the issue was that i was lerping from dynamic rb.position instead of a fixed variable
and i literally thought of this and was like "eh its fine"
well thanks so much guys!
Sorry I'm at work and on mobile so I can't paste text but here's what I think it should look like.
Good luck!
thanks!
And FYI calling Time.deltaTime in FixedUpdate still automatically calls Time.fixedDeltaTime. They added that a while back.
@lucid bronze hah! thanks for the tip ๐ I did not know this
@solar parcel you should really never do val = Lerp(val, ...); because you are modifying the "starting point" of the lerp
I believe the result is an exponential decay curve rather than a linear curve
yeah it did look like it was going down slowly like a sine wave
Only if you want to get infinitely close to your destination but never quite make it there?
why does that sound familiar...
๐
Hello, I have a reference of a script in a variable, when the Player collides with an object i want to attach that script (addCOmponent) to this object how can i do that? gameObject.AddComponent<script>() doesnt work
hey guys ive a question
how can i return connectdatabase result into checkjokercode numerator?
Coroutines can't return value - you might try async methods instead.
well technically they do return a value: IEnumerator ๐ but you can pass a reference to an object as an argument and modify it inside the coroutine...
I don't think you can pass-in a ref argument.
I mean just pass argument that is your class, it is reference type anyway
then change properties inside the object... but not sure it is a good practice anyway
That you can.
But it means having a class/struct for each type of argument you want to return from inside a coroutine. Why not.
But when you want to perform an async operation and get a value back I thing async/await method worth a try. Bonus : you get a full stack trace if an error happens
well yeah, it all depends on what is the goal, but in this case, async/await seems like just the right tool
ahahaha yeah
Does anyone know the possible implementation of UpgradeSelection method of MaterialUpgrader class which is under the namespace UnitEditor.Rendering ?
I basically need to modify the material assets via code (part of an automated process)
Want it in a paste site instead ?
Good Grief! where did you find this ?? Is it public ?
A paste will be useful in quick edit.
it's v10.5 not latest one
It's fine.
From SRP package
OOh, I was looking in the URP package. It's the core. Thanks mate @broken socket . ๐
You're welcome. Have fun
is ConnectDatabase going to do more in the future?
Hey guys, I am creating a namespace with extensions for a lot of functions I sometime need to use (like random vector3, adding on in loop and more and removing strings).
If you have any more functions like this you thing I should add or create please let me know.
thank you ๐
Please do not cross-post
Ok sorry
i removed the 2nd ienumerator and implemented the function in the same ienumerator
I'm seeing this code greyed out:
But I am in the unity editor and I need this code to run. Is there something I could be doing wrong?
what IDE is this
how can i go through every single asset in my project folder and find EVERY scriptable object of type BaseItem who's itemID field matches one i pass in
something along the lines of AssetDatabase.FindAssets but im not sure how to make it go inside a scriptable object and look at a field
[MenuItem("Start searching")]
public static void SearchForItem()
{
var unfilteredList = FindAssetsByType<BaseItem>();
foreach(var item in unfilteredList)
{
if(item.itemID = "blaaa")
{
filteredList.Add(item);
}
}
}
public static IEnumerable<T> FindAssetsByType<T>() where T : Object {
var guids = AssetDatabase.FindAssets($"t:{typeof(T)}");
foreach (var t in guids) {
var assetPath = AssetDatabase.GUIDToAssetPath(t);
var asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (asset != null) {
yield return asset;
}
}
}
has some type casting problems here and there
since its discord coded
but the idea works โข๏ธ
sorry - this is Rider. But I've solved that and on to annoying Editor folder stuff now instead.
Quick Search would be perfect for this. You can even choose to have it index the properties. The nice thing is that it doesn't requiring loading the asset in to memory when searching.
sounds good but ill check if avenger got it right first
Oh, his will work.
sweet
interesting adn this certainly is one
but we'll cross that bridge when we get to it, i have enough on my plate with this system rn
is it possible to run operations on quick search results? I've used the UI of it, not really sure if there are any other aspects to it
Sure is.
There is a snippet of how ya use it.
this is great, thanks! Never even thought about the possibility of checking the API for quicksearch ๐
Hello, I'm looking for some UPM and asmdef insights.
I'm creating a package and I'm getting hit with a warning:Assembly for Assembly Definition File 'Packages/my.company/Editor/my.company.product.editor.asmdef' will not be compiled, because it has no scripts associated with it.
/Editor/ contains a single DLL so the complaint is valid. My question, do I need the asmdef in the first place? The DLL is already compiled. But if so how do I work around the warning?
No
Asmdefs are assets that define how scripts get compiled into DLLs
if you have a DLL, it doesn't need an asmdef
Makes sense. Thanks!
Anyone know why Unity is giving me these complaints about Bolt? I dont even use Bolt.....
HDRP 2021.2.0b11
Uninstall the visual scripting package maybe?
ah ok, I wasnt sure if it was a core required package or something
since Unity bought them
They've just installed it by default - annoyingly
gotcha, cheers.
Have they really now? ๐ค
Oh. Some of these decisions unity are making are really annoying
Maybe I asked something similar, but I wanted to know how you would go about programming melee attacks and synchronize them with animations. There is 2 things that I'm never satisfied with :
- How do you detect melee hit ? I'm using a collider attached to my weapon, but it can miss an enemy between 2 frames if the animation is too fast. I was thinking about either using overlap methods to draw multiple hitboxes in between 2 positions of my weapon or create some kind of sweep detection with raycasts between 2 positions but I wanted to know if there was some clean way to do that.
- How to synchronize attacks with an animation ? I was using Animation Events to enable/disable my weapon collider, but letting my visual animations "handle" gameplay logic seems really awfull. Also, anim events can create some unwanted behaviours : for example, I was blending between my attack and death animation, so the attack anim event was still triggered during the blend, meaning the corpse of the enemy still did damage to my player. On the other hand, most action games synchronize animations/hit detection so I guess you have to at least use the animation to move the collider or a reference point, which means there is a little bit of gameplay logic in there.
Sorry for the long text.
@rare sentinel detecting melee hit is usually done by doing a forward raycast from the players center. if you really want to do it from the weapon you can also do a linecast between the start of the animation and the end of the animation for example
why not a simple sphere cast with a delay before casting it? Delay based on your animation
Well using simple raycasts/spherecasts seems inacurate ? We all know how we hate when the sword of an enemy clearly didn't touch our character but still did damage. I can't picture a game like Dark Souls having simple sphere casts and not precise weapon colliders. Maybe I'm totally wrong tho
For example, I was trying Skyrim and realized how bad the hitboxes are. You can attack in the void next to an enemy and still hit them because melee hit seems to be a big cube in front of the player.
If you do a linecast from the point of your sword at the beginning and end of the animation, It's almost guaranteed to have hit the enemy
Yeah this is like a sweep collision detection, it's also a good idea to "fill" the gap between 2 animation frames
Any particular reason ?
if you really do it well, colliders can work. But I have more issues with them than doing it with a linecast. You'll have to put them on a certain layer, then that layer can only interact with a certain other layer,... If it has a rigidbody it can flip out
and indeed collision detection isn't always optimal
if you're going fast
but it can work!
Do what you are most familiar with
Well it's working, I just don't know if it's a good way
I am working on a shooting game and we have physically accurate bullets. using rigidbodies for arrows for example. But shooting them goes so fast sometimes it clips through walls or it flips out
so we do a linecast with the previous position and current position
so we never miss a shot
Yeah for bullets I always do that
Linecast to see if you'll hit something on that frame
For projectiles it's simple since they have a simple movement
I was looking at smash bros and the way the extend the weapon colliders between frames
To cover the whole area, that's another way
Yeah true, I don't have a lot of experience with fighter games so maybe I'm not the best reference :p
It's funny how implementing what I would consider the most basic combat system of a game is also what's giving me the most struggles
I'd guess you could cast a collider some distance forward.๐ค
It's kinda like extending the collider.
This is what I did on my prototype a while back, the problem is when the frame rate drops, the hit detection can become inaccurate when the sword movement is curved but the linecast it straight line.
I'm yet to try splitting the linecast and use curved/spline path
Also, I need to be very precise with the animations, especially with vertical attacks, if the attack animation is off/angled to the side, it will easily miss
What about doing sphere casts between anim frames ?
Kinda like smash bros have multiple sphere hitboxes on their characters that extends to cover the damage area
Oh but I guess with low fps you'll just cover a straight line between begining and end too
That's true! Didn't consider that ๐
And about when and how to properly activate the hit detection to synchronize it with the animation, what do you'll think ? Animation events ? State behaviour ? A coroutine checking the current frame of the anim ?
Is it possible at all to see some sort of list or graph of all the references? I've got a package showing up in the build that should only be used in the editor, and I'm not sure what's pulling it in.
put it in the Editor folder.
https://assetstore.unity.com/packages/templates/tutorials/3d-game-kit-115747 this asset has a pretty good melee system worth checking out.
packages typically have asmdef file in them
you can check it
or package.json
package/editor/asmdef, see if its properly setup
sunLight.color =Color.HSVToRGB(0, 0,0.5f+(Mathf.Sin((((Mathf.PI*2f)/(4f*DayCycle))*t)+(Mathf.PI/2f))/2f));
``` A day to Night cycle with sin curve
took me so friggin long to math this out lmao
Day-1
Night-0
is there a good way to load all scriptable objects (of a particular type, in a particular folder) at runtime without addressables? i've seen a few very old posts that suggest using Resources.LoadAll() but i assume that's now discouraged.
Well done. I would have just increased a timeOfDay float variable over time and used it to sample a gradient.
Are you talking about some pre existing function or the variable used in the code?
interesting
would probs have gone the lazy way like MentallyStable + it offers the possibility to tweak it different from reality
Btw, I had a question. To connect between two scripts, I used an If statement in update of scripts A to call a function in script B.
The function switches the light coming out of a streetlight .
I'm thinking of moving it to script B where the update function checks for the day factor in script A (lets say the y value in the curve I sent above) affecting the streetlight
Does these both two cases actually make a difference in the frame rate of the game?
Or am I just being too paranoid about FPS lmao
Haha I have a thing where I try to do one liners, that's how I did that.
And again, I think of all that time gone to a waste because
This is how a real world lightning cycle looks like
So I'll have to work for having a period of difference between the maximas and minimas
Could probably just define that curve in an Animation Curve and then sample it based on currentTime / maxTime (0.0 to 1.0 value). Rough curve for an example.
Ah shit, I just came back to unity from 2019, didn't know that existed lol
I wasted 30 mins on the thing I made earlier, could've done it 3 instead xD

// 0.0 to 1.0
_currentTime += Time.deltaTime / _maxTime;
_currentTime = Mathf.Repeat(_currentTime, 1f);
// get the 0.0 to 1.0 output on the curve
float curveSample = _curve.Sample(_currentTime);
// map to the max height you want
curveSample *= peakValue;
// voila
Simple usage as well
me every time I make something in unity
Oh gonna check this out this week end thanks a lot !
at runtime if you want to load multiple assets without any reference, then you dont have any other option than Resources.LoadAll or Addressable's LoadAssetsAsync
ok cool, good to know i'm not missing anything. thank you!
Alright, I asked in #archived-code-general , but this might actually be a more difficult question, so I'll ask here
basically I would prefer to have as much control over the player's movement as possible, so I went and ported a stateful character controller I wrote for a 2d game to 3d and I'm realizing that using raycasts for collision doesn't work too well on the XZ plane instead of on just the X axis
for obvious reasons - needing to detect collisions from all directions, for starters
would it be better to just bite the bullet and use Rigidbody and whatnot to deal with that?
@gloomy nova i'm probably not super qualified to answer, but my understanding is that you don't really want to use the built-in unity physics for anything that needs to control really responsively
Yeah, I'm just sort of having an issue with horizontal collisions now.
That was the reason I wrote a 2d controller independent of the physics system
yeah totally understood. based on my limited knowledge though, i think the idea is that physics systems (not just unity's) are great for like, making props bounce around realistically, and for making funny physics puzzlers, but horrible for responsive tight controls
yes. that's why I'm not using it lmao
so my concern now is detecting horizontal collisions properly and efficiently, because the horizontal axis has become a horizontal plane
yep gotcha. that one's far beyond my knowledge right now unfortunately
all good
but you're on the right track doing it yourself at least
oh and, since you're talking about collision stuff
i think it's totally fine to use unity's collider stuff
just not the rigidbody physics
that could be a non-starter for you depending on how your game works, but i've used colliders without physics a few times and it worked great
Alright, so I bit the bullet after all and used Unity's CharacterController (which does handle collisions with colliders without needing Rigidbody)
time to fix the 800 bugs relating to collision detection now LOL
Does anyone know a more efficient/elegant way of packaging together an enum and a function?
My goal for this is to use an enum in inspector to pull a function that lives in a class and store all my effect logic there.
Depends on how you are going to be accessing it. But just making it a list might be better if you don't need to do a lot of lookups.
{
Effect effect = EffectDB.effects[effectID];
EffectInstance instance = new EffectInstance(effect, effect.duration, power);
if (!effect.canStack)
{
foreach (EffectInstance i in Effects)
{
if (i.Effect == effect)
{
return;
}
}
}
Effects.Add(instance);
GameEvents.OnGenerateDialog(DialogType.combat,
$"{CharacterName} {effect.effectStart}");
ProcEffect(instance);
}```
this is an older version so the exact naming might be off. It is all borked cause I am mid change.
{
instance.Effect.OnEffect(instance, this);
}```
The idea here is to get all my functions to live in a single class so they don't clutter things up.
but I cannot think of a way to make a class with a public burning function and poison function ect modular.
thus my desire to pair the enum and function.
I wouldn't, I would have a single file and have each one a class in that file. It will make things easier for you, should have better performance, and in the future you are able to add other methods or data that is per-effect if you need it.
(Each class inheriting from a base class of course)
How would you make them accessible from a scriptable object?
I've got abilities, items, equipment, ect that all need to get an OnEffect.
What do you mean "accessible". In editor? Through code?
Ah! Just use TypeCache.GetTypesDerivedFrom()
what strange sorcery is this.
So in the hypothetical ```
public class Burning : {
OnEffect(){}
}
public abstract class EffectBase {
public abstract void OnEffect();
}
public class BurningEffect : EffectBase {
public override void OnEffect() {}
}
And on the scriptable object goes public EffectBase effect?
how does the TypeCache.GetTypesDerivedFrom() get in there?
You use it to get a list of all the effect types and make it like a dropdown where when you select one it creates a new instance of it and assigns it to the field.
Alright. Thank you.
Sure thing, if you have questions about the editor side of things there is always #โ๏ธโeditor-extensions
Roger that.
My concern with this solution is now I will have a billion public classes making my programming life harder.
Think of it this way:
Burning Effect and Posion Effect,
They both probably do tick damage. So perhaps you only need 1 class for both
Like "TickDamageEffect"
and settings aside from the class that actually decide what visuals happen
You are going to have a lot of public class, you are making a game. Two solutions though is to put them in their own namespace, or to put them inside of another class, though this feels like a code smell to me.
Hi there
does anyone know how to prevent missing reference exceptions through coroutines if the level was destroyed?
won't deny I am probably doing alot that isn't by the book and I reinvent the wheel often as I am self taught with no industry experience.
Doesn't mean you can't work to learn the 'right' way to do things still. Some of it may seem pedantic, but they really do help your code be more stable, extendable, and readable (especially by others)
With an if statement...?
at all ref points? doesnt seem right to me
It's less unwillingness to do it right and more youtube tutorials are hardly shining examples of sound programming practices.
No, just at the start or after a yield.
that's still a lot
and what am I checking for?
Are you doing a lot of yielding?
if (level == null) return;
like, my current problem is that none of my scripts work after I reload a level, all I'm getting right now are some missing refs made by some coroutines that are still running
You can use a try catch if you want to.
Seems kind of a dirty way to handle it to me though.
ok nvm... it's not the missing refs that cause this
You're right. And it's already awesome you're aware of that. You need to meet other devs to not lock yourself in bad habits. Maybe do game jam in teams (to learn from other devs), take part in open source, and so on....
anything with a community, because like you said you're not in the industry
Anyone know a way to prevent pirating?
Ship it on Stadia
Lol I dont even know where that is.
Google's game streaming service
Considering how much money AAA is putting into this without success, I really wouldn't bother wasting time on it
Most indies have a lot bigger problems.
Anyone have any insight as to why my code behaves like this?
if (Physics.SphereCast(groundCheckAnchor.transform.position, groundCheckSphereRadius, Vector3.down, out groundCheck, groundCheckSphereDistance, groundLayer))
{
PlayerStates.grounded = true;
Debug.Log($"{this.name} hit {groundCheck.transform.name}, normal={groundCheck.normal}, {groundCheck.normal} != {Vector3.up} = {groundCheck.normal != Vector3.up}");
Debug.DrawLine(groundCheckAnchor.transform.position, groundCheck.point, Color.red);
if (groundCheck.normal != Vector3.up)
{
//Debug.Log("ON SLOPE");
//Debug.Log($"{groundCheck.collider.gameObject.name} -> {groundCheck.normal}");
PlayerStates.onSlope = true;
}
else if (groundCheck.normal == Vector3.up)
{
//Debug.Log("NOT SLOPE");
PlayerStates.onSlope = false;
}
}
else
{
PlayerStates.grounded = false;
}
Result:
https://streamable.com/mxsja2
apparently it thinks im on a slope...then not on a slope.....despite the normal being identical 0-0
HDRP 12.0
Vector3 equality is the same as checking Mathf.Approximately on the three vector components IIRC. It's possible that the difference is beyond the range of Mathf.Epsilon (the distance checked by Approximately), but smaller than the Vector3.ToString granularity. As a general rule I avoid this method and would instead do a threshold on a dot product between normal and Vector3.up. Why it's behaving like this exactly I'm not sure though.
Do you get the same behaviour if you do a Raycast instead of a Spherecast?
Raycast works perfectly, probably something to do with the spherical shape messing up the calculation
I agree, I bet you'd get better results reducing the number of compares from 3 to 1. Really what you care about here is groundcheck.normal.y approximately 1. Which you could also do with a dot product if against other than Up.
Hmm, then again maybe the collision point isn't always perfectly the bottom of the sphere which means the compare is probably off substantially more than epsilon
I'll be following along for the solution with curiosity ๐
Hey, could someone help out with an existing shader? Got a mesh bending shader, but failing to make it change radius with distance.
As the image shows my mesh curls, but at a specific point it will collide with itself, however I'm trying to make its radius increase with distance to give it a spiral effect.
Shader link: https://drive.google.com/file/d/1jsLVLCnn_u1OJdj-X4MGNo2C09FY42a0/view?usp=sharing
Logically tried offsetting the radius and center based on distance (Ypoint) but produces the reverse of what's expected.
cant see how this is related to c#
head to #archived-shaders
Hi there
I'm having trouble with my code working after loading a new scene
I have a "game controller" object that is persistent over 3 scenes, a main menu, a loading scene and a main scene for gameplay
whenever I try to exit the main scene back to the main menu my game somehow bugs out and I my scripts stop working
anyone ever experienced this?
It'll just be a bug in the way you are handling your script(s) lifecycles on scene load etc
the way I load my main menu and loading scene is just throufh SceneManager.LoadScene
but when it comes to loading my main scene I use this
public void LoadLevel(string levelName)
{
StartCoroutine(Seq_LoadLevel(levelName));
}
private static IEnumerator Seq_LoadLevel(string levelName)
{
PlayerSprite.MoveToOverTime(Vector2.zero, 1f);
yield return new WaitForSeconds(1.5f);
// TODO: Test on actual device
// var loadOperation = SceneManager.LoadSceneAsync(SceneManager.GetSceneByName(name).buildIndex, LoadSceneMode.Single);
var loadOperation = SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single);
loadOperation.allowSceneActivation = false;
while (!loadOperation.isDone)
{
if (!(loadOperation.progress >= 0.9f)) continue;
PlayerSprite.MoveToOverTime(new Vector2(14, 0), 1f);
yield return new WaitForSeconds(1.5f);
loadOperation.allowSceneActivation = true;
}
}
while (!loadOperation.isDone)
{
if (loadOperation.progress >= 0.9f) break;
}```
you will really want to put a yield return null; inside that loop
otherwise it will freeze the game
hol up, that was the wrong version
now it's current
it does work on a "forward path" from main menu -> loading -> main scene
but when I go back by main scene -> main menu -> loading ... the script stops working properly
if (!(loadOperation.progress >= 0.9f)) continue; is still an infinite loop
really? lemme check
ok youre right, weird, why did that work before though without fail...
you could also just do:
yield return new WaitUntil(() => loadOperation.isDone);
weird, I have to access the loadoperation progress for it to properly work
PlayerSprite.MoveToOverTime(Vector2.zero, 1f);
yield return new WaitForSeconds(1.5f);
var loadOperation = SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single);
loadOperation.allowSceneActivation = false;
while (!loadOperation.isDone)
{
if (loadOperation.progress >= 0.9f) break;
yield return null;
}
PlayerSprite.MoveToOverTime(new Vector2(14, 0), 1f);
yield return new WaitForSeconds(1.5f);
loadOperation.allowSceneActivation = true;
now it looks like this but .MoveToOverTime doesnt work
which is
public void MoveToOverTime(Vector3 destination, float timeFrame)
{
StartCoroutine(Seq_MoveToPositionOverTime(destination, timeFrame));
}
private IEnumerator Seq_MoveToPositionOverTime(Vector3 destination, float timeFrame)
{
var startPos = transform.position;
var t = 0f;
while (Vector3.Distance(transform.position, destination) > InstantMoveDistanceThreshold)
{
t += GameTime.FixedDeltaTime / timeFrame;
transform.position = Vector3.Lerp(startPos, destination, t);
yield return new WaitForFixedUpdate();
}
OnObjectStop();
yield return null;
}
any idea why that might stop working after reloading a scene?
because you're loading a new scene
every object that isn't DDOL will be destroyed
including the script you are starting the coroutine on
that script is within the scene by default
and if the script you started the coroutine on its destroyed, the coroutine will stop
wdym
is it DDOL?
if it's not DDOL it will be destroyed when the new scene loads, since you are using LoadSceneMode.Single
hol up
so I do it like this, main menu -> LoadScene(LoadingScreen) -> loading screen -> SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single);
then we're in the main gameplay scenen and I use LoadScene(LoadingScreen) again for testing to see if my script works
the movement of the object happens only within LoadingScreen by itself, It starts automatically when LoadingScreen loads up
but when reloading from main scene to LoadingScreen, the script runs and appearently does something, but nothing really happens
well i mean according to your code above you're not actually starting the MoveeToOverTime thing until after the loading is complete
did you mean to start that after you start loading but before the loading is finished?
I wanted to make a sprite move to the middle of the screen while the next scene loads and then move it to the other end
when it's finished
Let's say I would like to get into System Design, what could I do in Unity that would help me advance in this direction ?
wdym by system design?
like architecting a whole project?
you can like find how the whole of unity is built in terms of like how does it start from the c++ engine, into c# scripting , the component/gameobjects system etc
but its not open source so you can just like read about it in general from unity devs wherever they wrote about it
i'm also interested in an answer to @toxic ore's question about system design as it relates to games, i'm an experienced developer outside of game dev and i find myself spinning my wheels a lot on how i should apply that experience when architecting systems in games
the question seems quite vague to me. designing is usually done along with planning which is specific to the required goals to accomplish.
its like asking someone a design for a building without telling if thats for a small house, or a multi story apartment, or a mall, etc. i hope you understand what i mean
most games are a soft-realtime system that aims to avoid any and all waste (i.e. we use the softness of the deadline to replace the safety of regular RT systems with performance). All best practices and architecture decisions derive from that while allowing artists and game designers to express their ideas. Best way to become an architect for that stuff is attempting (and failing) to build systems (and getting actual users/players engaged) ... there are no simple answers on what the correct way is. But expert understanding of studio workflows, asset pipelines, operating systems, game engine development are certainly helpful.
Biggest stumbling block is that many design patterns, advice you hear and principles you come across, from run-of-the-mill software development (and especially web-dev), are semi-wrong in this context.
@compact ingot that's an awesome answer, thank you! do you have any recommendations for resources on learning about the best practices for architecture on this stuff? currently in the "attempting and failing" stage, and i can definitely tell when i've moved from a bad solution to a good solution, but it would be great to read/hear thoughts from people who've already been through it a bunch
i've only found that there are some patterns that repeat itself when aiming to build a general purpose engine like unity... those can be learned from books like "Game Engine Architecture by Jason Gregory" and watching conference talks (many on youtube) (caveat: never take beginner stuff as a guide, ever); along with a general feel for what people seem to consider "good ideas". What you'll usually hear from experienced people is that "everyone" with a microphone/blog on the internet repeats stuff they learned wrong themselves or heard somewhere and didn't question (a few notable exceptions exist). Always ask however from what perspecitve that person is arguing... AAA console games are vastly different from indie PC games which are vastly different from hobby games, Jams or inhouse-applications, installations, theme park rides etc. Basically don't try to figure out what is right... aim to figure out what is less wrong.
Whats right for AAA console is likely very wrong for a mini-game a company wants for their trade-fair booth.
Architecture for me has come down to starting with a hypothetical monolith and breaking it into easy-to-rewrite modules whenever i discover a significant circumstance/reason why part of it may need to change. And the less technical that change request is, the more managed/abstract that module will have to be. A "module" is anything from a config-variable to a kubernetes cluster.
Anyone know Photon Bolt here ?
thatโs awesome advice, thanks a ton! really appreciate it
figured it out, I forgot to "unpause" my game after opening a menu
hey guiys I am checkingmy edito log, I got 41% of my build report on Included dlls, can some one help me underttand how is this to high?
does unity use the fast inverse square root?
I'd assume that it depends on the hardware.
With subsequent hardware advancements, especially the x86 SSE instruction rsqrtss, this method is not generally applicable to modern computing
does that mean CPUs are actually able to compute this in a single instruction? rsqrts
Seems so.
It's not really up to unity, it's the compiler to native code that converts code to cpu instructions. AFAIK.
i mean you could code a C++ plugin that uses assembly of rsqrts
unless you want compiler flags of -ffast-math -march=native
apparently rsqrts is much faster than the quake 3 trick https://youtu.be/Fm0vygzVXeE?t=1114
I wouldn't even bother with that as a beginner... Or even as not beginner. That's not really something you should be worrying about.
well i mean someone was having issues with how slow their los was earlier while i was helping them lol
so it was hitting close when i told them to get the vector norms
if it was that circles guy, he would see far more improvement with a better algorithm than with micro-optimizing the math
yeah lol
hey guys, im procedurally generating a map in chunks that goes inside a dictionary. the chunks get flagged into a list that eventually calls destroy on the gameobject of the individual chunk and then removes it from the dictionary. however, when i go back to an old spot where it was deleted, the build chunk method doesnt recreate a new chunk instead nothing happens it remains empty and leaks. any ideas? im not too strong on memory issues
Some code would be helpful.
figured ud say that! its alot of code so i wasnt sure which part to copy
ill try to find some snippets that the problem is most likely in
For starters the part where you recreate the chunk.๐ค
cant figure out the conflict but i think its these two
adding works and removing works perfectly
but when i revisit an old chunk it doesnt create a new one in its place
i want to solve this before i move onto serialization which i figure will fix the problem in its own way
im guessing its somehow retaining the original chunks in memory
so when it returns to place the same chunk, it cant
at the moment, it adds chunks around the player and removes them when out of range based on a tick
works perfect
but as soon as i circle back round to revisit a previously deleted chunks, it doesnt create anything and it leaks which kills the fps
u can see the dilemma, the add and destroy on their own work totally fine x)
not sure if its the destroy/remove staying in GC or something or the way it's adding chunks back on the stack
How about adding some debugs for destroyed and created/loaded chunks?
i suck at remembering to add debugs
normally just debug it in my head (or use console post-runtime)
will take a minute to think where i need to put em x)
well i dont know if i did any real useful debugging here
i just chcked for the object c
but when i revisited a deleted chunk
it suddenly jumped to 999+
so thats where the fps drop is coming from
can u figure out what it is from that at all ? XD
seems to be pointing to the remove function though cant say for certain
profiler shot
update method goes crazy when a previously deleted chunk is in the camera view
so for some reason, during that time, its calling the update method and loads of objects
found the answer!
The update is of the chunk spawner
i was right in a sense
`The reason you have a memory leak and calling your garbage collector is not doing anything is because of how you are declaring
private List<GameObject> objects;
You declared this as a global variable when instantiating your public class Game:MonoBehavior.
As the garbage collection is called this will eventually put the List into a generation 2 pool of objects that will not get disposed of until the class is no longer used.
I see two options really, you can make the scope of the object smaller by placing it within a method allowing the memory to be released by the normal garbage collector since it will become a generation 1 or 0 object at that point.
or you can call TrimExcess() on your List which will reduce the memory of any allocated space of the list down to the amount of memory actual held by the objects in that list. `
for anyone else who sees this
the first one worked for me
second one didnt work
What's the top one?
"I see two options really, you can make the scope of the object smaller by placing it within a method allowing the memory to be released by the normal garbage collector since it will become a generation 1 or 0 object at that point."
๐
just made it non-global
wrapped inside function
Okay
Can you link that answer? I'm kinda curious of reading the whole thing.
ofcourse pal
my googlefu was strong tonight
thanks
I still don't understand the answer. Did you get it?
Also, according to unity docs, unity GC is not generational, meaning that the talk about gen 2 is not relevant at all...
the only part that needs to make sense
is that global and static variables stick around longer ๐
gen 0 1 2 whatever ahaha
unity is based on c#
so there will be some similar functionality going on
even tho its c++ engine it has all the hallmarks of c#
but i dont know shit tbh
still learning
I do understand a bit how GC works. And if I'm correct, GC would collect any objects that are not referenced. Which should be going on in your code.(or at least the code in the stack overflow question)
yeah, there's a reason that answer has no upvotes
^, when they did new List<> in Update, it should have collected the old list
Yeah, thus I'm confused.
can u explain that bit please
thats kind of what i ran into now
its calling new List every update call
but i need it to have the local effect of quicker gc
you will cause exactly the opposite doing that
heres the thing, it fixed my issue making it local
GC will run more often, and be slower
and is running faster
but i still think its wrong
before it wasnt allowing chunks to redraw
now it redraws and deletes perfectly
at the cost of calling new list every update()
but i need it to maintain the benefit of being local by referencing it somehow
well, when the code on stack overflow did this.objects = new List<GameObject>(); it created a new object. That implies, the old object isn't being used anymore. The GC figures that out via some magic, and then after a couple of frames collects it, i.e. deletes it from the actual memory
oh im not doing that
im just doing new List
is that fundamentally wrong still
or is that perfectly ok
in my head its like every update calling new List
not a couple frames; only when memory pressure is sufficiently high, a certain platform-dependent amount of time has passed, or there is a scene change
every time the GC runs, the entire program is paused. If it's running every couple of frames, you would have a ton of stutter
@distant kernel may I ask how you figured out that the memory is not being freed?
๐
then there must be a phantom of it
blocking the way
i.e. some form of memory allocation
I don't think that was the case.
xD are u sure
instantly fixed my issue
now im just trying to noodle my way to understanding if calling new List every update is right or not
It could be that it was referenced somewhere else, since it was global.
its not effecting fps
by making it local, you eliminated that reference, making it collectible by the GC.
it could be indeed
that is the same explanation tho
of a different perspective
ahaha
ill never know cos im not good enough at that yet
No. It's a different explanation.
The reasons are completely different. It's only the result that is the same - the GC did not collect it.
cant argue there
Hello, is it possible to create a chat program in unity, like messenger? I saw VIVOX library and going to study it but IDK if vivox supports gifs, sending photos, emojis
with any networking library you can send all file format in binary data. you'll just need a way to decode gif and display it on your front end. you have many plugins in asset store which do it for you.
other stuffs like photos and emoji are very easy
I need some ideas on how to solve a problem
im making a voxel system that generates smooth meshes
normals are calculated for each vertex as an average of triangle normals
because getting the normals from the voxel data isnt very good
the problem is the normals between chunks creates seams
how can i fix this
Align them between chunks
Depensd on how your system works
wdym
i have access to the vertex position and index of each voxel
the normals are calculated using recalculatenormals
how would i do that though
Recalculate normal does a cross product between the direction from the other 2 vertices in your triangle to the current vertex
If I recall correctly at least
it calculates it for the triangle
then after all the triangles are calculated each vertex normal is the average of the normals of all the triangles it is part of
Well, then do that but average the corner vertices with the matching vertex on the other side
Any idea why after i instatiate prefab and add button to it/ or it have it have button as prefab yet
onClick event dont appear in editor
private void LoadBuildingToShop()
{
prefab = Instantiate(partBoxPrefab);
prefab.transform.SetParent(buildingsContainer.transform, false);
Button prefabButton = prefab.AddComponent<Button>();
prefabButton.transition = Selectable.Transition.None;
prefabButton.onClick.AddListener(useFrameListener);
}
public void useFrameListener()
{
frameListener.SetNewParent(prefab);
frameListener.UpdateFrameRectTransform();
}
it doesnt appear in the inspector. you're subscribing to it via scripting.
yeah but i use to do it in few scripts yet and its appear and work
but this time not appearing neither work
Any other code affecting prefab?
Because you need to add it as a persistent listener https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.AddPersistentListener.html
Thanks
Is there any way to get unity to tell you exactly what variable is causing a null reference? Just telling me the function isn't enough in this case.
the error message contains an exact line number, not just a function
Unless you are one of those "i make crazy complicated one-liners" programmers that should narrow it down to 1-3 things max. From there, you can either just attach a debugger, add some logging, or split that lione up to find out for sure which one it is.
It was in some AI branching tree logic. Turns out it was an array I wasn't null checking before referencing.
what is the objective
your chunkspawner code is written wrong. is there an existing asset store asset that does what you want?
Does anyone have any good resources on (Sparse voxel) Octrees? I'm struggling specifically with spatial partitioning and storage. I wonder, do I have to re-build the entire tree every time a change is made? I would like to use structs but they're non-nullable so I figure the tree would need rebuilt each time it's modified to conserve on data and long-term processing
However, if use classes, they will create garbage collection and slow down the system
If you use structs and rebuild the whole tree you're still creating garbage.
Any suggestions as to how I should structure it, then? I'm stuck. I've never written an octree before and I really need to. There's lots of resources online but I can't seem to wrap my head around it, I need a more personalized approach
structs are not garbage collected unless contain non-value types
I plan to contain only value types or other value type structs, like ushort and float3
not true entirely
well if a struct is in a class then when class out of scope, gc still...
Not sure of best way to handle changing linked lists, trees etc. Could pre allocate array to max size , re-use elements, marking elements as used or not
Yeah but that ruins the point of reducing memory consumption
Maybe GC is something I'll just have to deal with
Is there a way to get occlusion probes data in script when im using shadowmask?
I don't know exactly how to express myself, so I will try explaining (and requesting help) in layman's terms. ๐
I'm trying to get a nice random beautiful movement for some 2d objects on-screen.
I've managed to AddForce in Random.Range(-1, 2); but the movement is not curved.
The objects are simply pushed towards the direction I point to.
Do you have any advice on how I can make the movement "curved", "round" or "parabolic"? (putting quotation marks because I have no idea how I need to ask for what I need)
Maybe lerp between previous and new value?
Thanks for asking. I don't know. ๐
I did see lerp in the documentation, but frankly, since I'm quite new and I suck at geometry, I'll search for a guide on that.
As a last resort, I'll also fiddle with lerp, maybe I can get the behaviour I want by coincidence.
I'm having confusion with your description. Do you want the straight line, or the curved line
Curved.
The dotted line.
I don't have a destination in mind. I am trying to simulate a floating behaviour.
Ugghhh... Then why ask in #archived-code-advanced?๐
Because I thought #archived-code-advanced is for #archived-code-advanced , not advanced coders?
๐
But that doesn't sound advanced at all. Lerping or smoothdamping should work.
Seems like I'm simply too much of a newbie. ยฏ_(ใ)_/ยฏ
Thanks for the advice guys. ๐
I'll figure things out.
And will properly post things in #๐ปโcode-beginner next time. ๐
I mean, general code should be fine for such a question.
@modest lintel Did you want to add something else? Just trying to get the exhaustive list of things before I move back to Unity from Discord.
not really ๐ , I was gonna ask whether you actually need force or you just want a curved movement. If its the latter, I think you can easily use slerp.
Yeah. Curved movement.
It sucks that I need to get random targets though, towards which I can make the curved path. ๐ค
The AddForce thing was just a hack, it seems. ๐
Anyway, yeah. Thanks for the help. I'll post something in #archived-works-in-progress when I get it to work the way I want it to. ๐
Hi !
I'm facing a probleme with cameras and Orthographic camers. i'm actually taking screenshots (high res) in a project i made of some shelves the problem i'm facing is each shelves have it's own camera, and then i happend all the pictures together so i get only one picture with high res of all the products that can be then used in comercial purpose or stuff like that
but the problem i'm facing is i can't put a custom resolution of the orthographic camera it's always taking more than it's rendering, and i have no idea why
Quick exemples here you can see each rectangles
that are my ortho cameras
but this is the output
it add a blank space between each of them
i made it taller on purpose because i wanted to add a banner on top of the shelves
but making it taller also make it biger in width
if anyone can help me with this would be awesome
I don't think you should touch that value.๐
it's exactly made for what i need to do
- no offence but this kinds of comment, with no arguments doesn't really help here
Can you explain/demonstrate what you mean here by "taking more"?
as u can see in the provided screenshot
there are big gaps between the differents shelves
https://streamable.com/rcevx1 Video of the problem
If i aim at the first enemy, track it then unaim. and start aiming at another enemy very far away from the first enemy, it completely breaks, it forces my player to look in somerandom direction and i cannot look at enemies, if i try, i am forced away.
Does anyone know what have done wrong and how to solve it? Thank you```
Scripts
https://mystb.in/RelationshipsDealingAerial.csharp Aim Assist Functionality
https://mystb.in/MixingHashIllegal.csharp Camera Controller
this is a screenshot of it
when there was no problem
but making it
only taller
make it also wider
and i don't want these big gap
but if i don't make it taller, i can't add banner like in the following screenshot
Im sure you know this, but those are just percentages of screen space. I havent used that in forever because we do almost only VR now, but the upper values are the offset (1,0.33) and below is how much to capture (either 1,0.33 or 1,0.66 - cant eemember if it is inclusive)
@wooden cedar idk, it's not really clear
since in the view of the render of the camera it's showing it like intended
It is important to note that the resolution of the camera is based on the applications screen resolution
Oh, so these gaps are the problem? Is that how your screenshots end up? How do you take them?
Oh so that's why you're in #archived-code-advanced
I'm trying to figure out how you render them? Is it just 3 cameras stacked?
nop
each one of them have a
the thing is why the render texture not being the same as rendered in Unity ?
Because camera resolutions in unity are percentage based on the applications resolution and you are manually setting the render textures size to a different value
nop
I'd guess that's because you specify the resolution of the render texture. Where in the scene view it's based on your screen and the game window.
Yep
if you are talking about this
this is only define the resolution of the picture itself
making it lower values will just down scale the overall resolution
Nop
Im not
You are specifically setting the render texture resolution to a different number than the camera. It will then render only as far as it can.
I dont want to have to repeat this a fourth time...
again
ur wrong
try it and read it
that's annoying having people that think they are right when they never worked with this kind of stuff
- that's not the issue
otherwise
it would have the same behaviour
You asked this question. There is the answer.
If you check the docs example, they use screen resolution.
https://docs.unity3d.com/ScriptReference/Texture2D.ReadPixels.html
Its annoying when someone asks for help, we give them the answer. And they stubbornly refuse to fix it
Answer is provided
since here i'm talking about multi ortho cameras rendering on objects
Whos next for help?
that's not related to the screen itself
@wooden cedar your answer is worth of nothing sorry to say
since you are obviously talking about things you never used
Fix your code.
then you should use screen width / 3 or something. Not magic numbers in code.
code is working well, but you are actually not looking at the problem
its like having a child that wont listen :D.
just to prove
ur wrong
putting back the value to what is was
everything is working fine
so it's not related
i can also
put bigger values
I already told you how to fix it. Works on my screen. Fix your code.
just to improve the quality
you haven't at all
then provide your code so we can see mr
Could anyone help me hehe
Sure. 1 sec :)
Any chance this is gimbal lock?
It could be, but my knowledge of rotation / quaterion is none existant
been a 4 day battle so far
Hmm
@mighty cipher please avoid unsolicited DMs. If you have anything to say, do it here.
This is not the line I was talking about.
Attitude like that will not get the help you require
Ok, it looks like two things to me, one appears to be gimbal lock (where it is bouncing) and aim is slightly off.
One quick alternative to test with - is to use the transform.LookAt(target) and then use lerp. It is a quick mathless way to rule out the pitch and yaw logic
you see that the texture is being set to a quality then read the screen and fill up the texture with the following quality depending on the render texture of the camera
so that's exactly the same
But i can also rewrite that to use quaternions if you like
putting screnshots of things out of context @untold moth is a bad thing especially if you don't read the lines above it
I stopped wanting / being interested / offering to help you. You are on your own. You don't need to prove anything to me.
Here's a part of your code
You're clearly using ReadPixels.
https://streamable.com/n4lh92 @wooden cedar this is with LookAt
No prob, I have an intense set of meetings this morning, but please send this to me in a DM and I'll make sure to help properly
I'm creating a compass component that's drawing some icon on my UI. The thing is, each scenes will have different interesting objects and I obviously can't set the references ahead (since some objects will be dynamic). How would you implement such component ? Some sort of singleton so that every interesting object can add themselves to the list of objects to draw ? Another idea ?
you can use GameObject.Find("name of object") in Start to get references to game objects
I was thinking about doing that (with types), but that won't handle dynamic objects (and I won't use Find methods in an update ^^')
by dynamic objects do you mean objects that are created during the game after the scene is first loaded?
Yes
things that could spawn/despawn during gameplay
like a dynamic objective marker, etc
you could make a function like AddInterestingObject for example that would create the specified interesting object and also add it to a persistent array
so whenever you want to add a new object that should appear on the compass, instead of just creating it in the script it's in, call that function in the main script
The problem is where to put that list and how to reference it ?
put it in whatever script controls what's on the compass
and wdym how to reference it?
just use the name of the variable you make to store the objects
It depends on the quantity. Assuming it is less than 50, I would probably just add an InterestingObjectManager with a list of InterestingObjects.
In a more complex environment, I would do the same but place the lists in a 2 dimensional array, so I an only collecting small clusters of points based on the players tile location.
That is a bit more bethesda style
You could also take the lazy approach, place a large sphere as a trigger. And add and remove objects that way. But I would probably just keep a list and go about it that way
Donโt use scenes. Otherwise a static variable objects add and remove themselves to is the simplest and best.
If you know monsters and pickups are always interesting, implement it as something you can just call, via a static, inside an Awake, like a static โSetIsInterestingโ
This would scale for millions of objects
The compass can render this list (really a set since order doesnโt matter)
I meant, if it's stored in a script, how does my object reference that script to call a AddInterestingObject
What do you mean by dont use scenes ?
Yeah so you think a static list + static method to add into it is the best way to go ?
Another discussion but just illustrative of the pain points of organizing your game into multiple scenes
Yep. You donโt need a script dedicated to marking if something is interesting if you already have base classes for almost everything in your game that should be seen by the radar like behavior, add the handful of calls there
Ok ok, thx for your help everyone
I think you need to set recalculate mipmaps to true, you also should set filtering on the textures, itโs just a few steps youโre missing
Also the camera youโre using to render the screenshot probably isnโt framed optimally
It may behave unexpectedly, try setting how the gate fits from horizontal to vertical
The gate fit has to make sense for your resolution
I would do something like this... Give each object that appears on the compass a script. Then search for all instances of that script with FindObjectOfTypeAll and add them all to a list in the compass.
@untold moth @wooden cedar For the record as annoying as he is Tarmack is correct about render texture behavior
You can use any resolution youโd like in a render texture and the camera will render to it
Regardless of screen size or whatever
It will not sample incorrectly
@mighty cipher so maybe just carefully check that the framing is correct.
Otherwise if you are in standard rendering pipeline you probably also want to enable anti aliasing
MSAA is only supported in Forward
Also a setting on the render texture - it has no impact on HDRP but it does on SRP
Thereโs also a better way to copy a render texture into a texture 2d but I donโt remember what it is. Look at the Unity Recorder package to learn more
Based on this you have to more carefully layout your UI elements, also the textures themselves may be problematic
I have a script for orthogonal camera which does the exact screenshot as required with a custom res. If you're interested just dm me :)
First, determine what the correct aim position would be. If there is one, interpolate between the two. The more formally you approach the problem the easier it will be to solve
I would delete everything you have and rewrite it from scratch
It is very tricky to convert camera space into input space
Donโt approach the problem that way
If you do want to do it that right way, you have to use new input system and think about how aim assisted aim is like a different input
Otherwise just use an asset store asset for this
I have a client/server architecture for a game that's getting a bit more complex than initially scoped out (duh, right?).
It's a turn based game where state is maintained on the server and the clients, and a turn can be any number of things (move an item from one grid location to another, pass the turn, use an ability, etc). The server calculates all the "stuff" and then sends them back to the clients.
I'd like to rearchitect this communication, since the "stuff" has gotten more and more variety as the game has gone on and my existing architecture is too complex to manage (bugs are hard to debug, desync issues are hard to find, animation is hard to build, etc).
I'm thinking that what I'd like to do is create a PlayerAction POCO (lightweight for serialization/bandwidth reasons) with perhaps some ... subclasses? with the details of the action. On the server, I'd like something similar, a BattleAction POCO with subclasses for the different types of actions that the server has calculated ("a new grid item appears at (x,y)") and a BattleState POCO that contains the comprehensive battle state.
Clients send a PlayerAction to the server, the server processes the stuff and sends a List<BattleAction> back to the clients so they can animate the actions. I could also send the BattleState from the server to the clients so they could.. compare their state to the known state.
Any thoughts/criticisms/advice?
This sounds right to me.
If the game is deterministic and each client has full knowledge of the game state you could potentially not send anything back beyond confirmation that the action was received.
And then just send out the other player actions to you
If it's turn based or something
Yeah.. that's how I'm doing it now, actually, but the debugging is a nightmare
IE - something happens on one client but not on the other, or the server has one state and the clients have another.. I'd like to at least write in the BattleState object as a way to more easily debug
(print out the known state, compare the "known" state against the "server" state and complain if it's different, etc)
Yeah, so you can just hash the state of the server and the client when you're debugging
And do checks now and then
I mean, theoretically, at least, I could just make it more resilient (if maybe a little jarring?) by just "setting" the client state to the server state and silently complaining, so at least the gameplay can continue
If there's a problem simply serialize the state of both into JSON and do a regular diff
Then you can pinpoint what part of your simulation was not deterministic
Aye.. OK, thanks for rubber ducking.
The problem your server needs to solve is to ensure that each client gets the actions in the correct order
Yeah - right now I was... doing these big lists of .. stateful items and unpacking them on the client and attempting to animate, but it led to some complexities (in a good way - as the game developed more abilities).. so I think redoing it in a "BattleAction" approach simplifies the animations and stuff
Hes using both render texture and reading pixels with a fixed size and wondering why it doesnt align to the screen - while proudly saying his code is flawless and generally being an ungrateful person. I couldnt care less at this point about what he needs now or ever. Sorry
He also was complaining about the quality and the scaling. Both caused by him ignoring the screen size
i'm just saying factually the screen size with respect to what gets put into the render texture doesn't matter
you can in fact start unity headlessly, where screen width and height will report 0, and render to a render texture of arbitrary size and get an image of that size
this is also how unity recorder package renders "supersized" screenshots / videos
his particular issue is pretty common, like weird alignment / lines between UI elements
it's really tricky to solve
that's probably why the user felt like you had not used render textures before
ORLY?
i think he's aware that the render texture resolution and the game view resolution are different
yes
With ReadPixels?
?
yes it doesn't depend on the screen size at all
yeah
Ah, interesting. I just assumed that it wouldn't be the case because you have to wait for the scene to finish rendering
I thought ReadPixels was reading from the render buffer
all of this functionality is demonstrated in the unity recorder package
a very very high quality package that goes through all the gotchas
with using render textures to generate images
which is what the user wants to do
i'd encourage the user to look at that
it does. but render buffer isnt limited to your screen size and you can provide any arbitrary width and height to it along with depth
for rendering to your screen the camera usually uses your resolution width and height but that has nothing to do with a render texture you create for different purpose.
this is exactly the principle why you can switch displays in unity without having too clear the buffers
yeah i honestly cannot say a lot of the time how to fix the weird spacing issues between UI elements. my guess @mighty cipher is that you should try setting repeating instead of clamped for your sprites
this stuff is very detail oriented
it is super important to read the unity recorder source here
it deals with flipping for video, a lot of stuff
i guess this can still be fixed by previewing the Game view at the target resolution in which he wants to do the final output rendering.
the only difference will be the downsampling but i dont think downsampling will make the weirdness in UI disappear
wowee
if your game state is small and logical, send a complete copy of it from the server to the client for now (don't overthink it). annotate things that should be animated, like "this is the game state associated with a 'character has moved' event," and include the information the client needs to render that event, like "the character that moved" and "the destination"
you can still make the camera render a 4k or even 8k output to a png or video while still having a 1080p/720p or even lesser res monitor
when it's a player's turn, yes, send them all their possible actions. interpret this on the client to render the UI (i.e. what they can do)
very good to know, thanks.
you should still do big list of stateful items, but do not interpret the diffs
use the diffs when it's convenient to do so, and otherwise, emit events
it's very useful to model your game as a standalone c# thread (or async task)
that isn't aware of unity api, which sounds like it's the case because you don't use the unity api for your rules
i.e. you don't use unity physics to resolve if a projectile hit
and if it does, this is hard
i'm not 100% sure. forward rendering is buggy with render textures. he would be using screen space instead of overlay because otherwise it wouldn't render Canvas at all. he has a million things he needs to try, he's gone now, and also, it was like, some kind of oil change cans so i don't know how invested i am in the outcome lol
Not sure the state is helpful here.. think more like bejeweled or candy crush: you need to see the animations of the chains disappearing, the end state of the board would be jarring by itself. The state is helpful for debugging desync bugs but theoretically if everything is working properly, shouldn't be needed
Hi, i'd like to get a more in depth explaining of when should i use events in unity ? and is that making performance more reliable and less costly as update methods can be ?
You use events when you need to know when something happens, and it isn't happening every update (generally) because that's when you'd be checking in Update
you can also use them for something that happens every frame
so its basically same thing as update performance wise
but what's really the benefit to use that
and which type of systems can benefit from that in an rpg for example
should i use that for example to notify the player that his attack landed on a certain enemy?
An example could be when the player levels up. Say you want a door to open when they reach a certain level. Without events, that door would need to check every update if the player is the correct level.
Depends on how you structure it, but yeah that could be one use for events.
well, i'm actually lost a bit about how should i architecture a system that will make communicating possible between Player, enemies and Health UI for both in a cleaner way (considering that all UI is placed in a different scene)
i also, would like to have less attaching components to every enemy for example and have that handeled automatically
ScriptableObjects are a good way to do this.
In this second devlog, we look at how we employed ScriptableObjects to create a flexible and powerful game architecture for "Chop Chop", the first Unity Open Project.
๐ Get the demo used in this video on the Github branch:
https://github.com/UnityTechnologies/open-project-1/tree/devlogs/2-scriptable-objects
(compatible with Unity 2020.2b and la...
Speaking of scriptableobjects- I'm starting to use them in place of static singletons and it's making development very enjoyable now that code hotswapping doesn't break everything like my singletons did
However, it seems that anything that's serializable on a scriptable object and gets modified during play in-editor gets saved to the asset database. I like storing ephemeral state in gameobjects and having them be modifiable during in-editor play, but don't want certain values to be saved to the original asset. Is there any way around this?
idk for your question sorry, but mutating scriptable objects is bad practice i've heard
Here's how I'd do it. You have a Player object that you don't want tied to any sort of UI. You have some variable that the UI needs to display (say, HP or something). You handle the variable in your Player object and then you "subscribe" to it in your UI object. The player doesn't know about the UI object, and the UI object gets a call whenever the value changes.
Sure is, though not that pretty.
private void OnEnable()
{
_value = _initialValue;
// OnEnable is not be called if the enterPlayModeOptions are enabled, so the value will not be reset.
// So we need to register to the event that is triggered when the play mode state changes and reset it there.
#if UNITY_EDITOR
if (EditorSettings.enterPlayModeOptionsEnabled)
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
#endif
}
#if UNITY_EDITOR
private void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
_value = _initialValue;
}
#endif
it just means that there is a lot of stuff going on in the client networked that probably doesn't need to be
it might be easier if you do it more web-development style where the client is responsible for rendering
and that's it
not for like, trying to save fractional amounts of bandwidth or whatever
by using the logic as a way to compress stuff or whatever
it is just really complicated to do things that way
as you are probably seeing
that being said hard to say without seeing your code i trust it is well written it does work after all
if you have written the game business logic in C# and it interacts with the unity api for rules at arms length, you are in a good place
for example let's say on your battlefield you can fire a missile whose effects you want to resolve using a spherecast
// in your player object..
public event Action OnHealthChanged;
private int _health = 100;
public int Health
{
get => _health;
set =>
{
_health = value;
OnHealthChanged?.Invoke();
}
}
// in your UI object...
public Player MyDude;
public void Start()
{
MyDude.OnHealthChanged += UpdateHealthUI;
}
public void UpdateHealthUI()
{
SomeComponent.text = MyDude.Health;
}
public void OnDestroy()
{
MyDude.OnHealthChanged -= UpdateHealthUI; //don't forget to unsubscribe or memory leaks
}
Right so... the client is only responsible for rendering and collecting UI, but... the client can also be smart enough to render "actions" (using the candy crush parallel - chains that get "blown up") without waiting for the server.. But keeping the state on the client as well as the server leads to complexity.. I suppose I could go full thin client but that might be a lot of work and have some other problems down the road
(But it does solve a lot of problems in the way of input validation/cheating/etc)
if your game loop looks something like this
async Task GameLoop() {
while (!gameOver) {
var playerAction = await currentPlayer.RequestAction(this, validActions);
if (playerAction is FireMissileAction fireMissileAction) {
var hits = await unityBridge.SimulateMissileHits(...);
foreach (var hit in hits) {
await DealDamage(hit.character, fireMissileAction.damage);
...
}
}
}
}
async Task DealDamage(Character character, int damage) {
await FireGameEvent(new BeforeDamageEvent(character, damage));
character.hitpoints -= damage;
await FireGameEvent(new AfterDamageEvent(character, damage));
await ResolveDeadCharacters();
}
...
in this case fire game event would, in one implementation, do nothing, and in your networked implementation, serialize the game event and send it to the client
observe "unityBridge" for a situation where you need unity to resolve rules for you. i don't know if you need that in your game
@misty glade but the key thing here is, modeling the game as this singlethreaded thing that takes "no time" between things happenining, but "things happening" is all "awaited" Tasks that COULD be stuff happening over the network, or waiting for animations to play, or whatever
in your client, using something like unirx, and this is how my game works, you can receive those "events" and do something like
// events from the network
public IObservable<Event> events;
void Start() {
// animate events
// start with an event
events
// turn the event into a coroutine, because it is an
// elegant way to express timed things in unity
.SelectMany(evt => Observable.FromCoroutine(ProcessEvent(evt)))
// wait for the previous coroutine to finish before starting
// the next one
.Concat()
.Subscribe();
// you might get a mix of game state and events. sometimes you want
// it to be delayed, sometimes you don't. For example you want the
// user to see what moves they can take as soon as it comes from
// the server, so that they can issue multiple moves in order
// quickly, but the animations of the battle will be paced
}
IEnumerator ProcessEvent(Event evt) {
// do animations ...
}
maybe you want a script for each event, then ProcessEvent would GetComponentsOfType<EventHandler>() which has a virtual IEnumerator ProcessEvent that you call
basically exactly like any other event handler, except that you assume that you always want to wait for the previous one to finish before you start the next one
and you'd like toe xpress that in a succinct way, which SelectMany . Concat does
sometimes you want many events to occur simultaneously, for example, you might want multiple damage events to all render on screen at the same time, if they're part of the same "batch"
so like you're saying, you want it to happen simulatneously sometimes, sometimes you don't
you can express these things as processing a buffer of events - which usually come from the server instantaneously, so you can take the time to process the buffer into the sequence of animations that make sense
so if you do something that results in
new Event[] {BlowupCandy, BlowupCandy, ShowGoodJobPopup, BlowupCandy, BlowupCandy}
you can use Buffer, Scan and Aggregate to turn that sequence of events into
Show all the candy blowup animations at the same time, THEN show the show good job popup
@misty glade hope this is interesting you don't have to use it you have a working thing but there are ways to be expressive with stuff you get over the network and make it work with coroutines that will help you big time
like how much does it really have to "Wait" for the server? it could be milliseconds
nobody will notice that
Sorry - was AFK in a meeting for a bit @undone coral, gimme a moment to digest the above (and thanks in advance for the care and thought on the response)
Cool - thanks for the above. Unfortunately, I think I'm a bit too far into the architecture to implement unityrx (which I've read about but previously opted to DIY it). I really like your approach of selecting and subscribing to all the events that matter with that LINQ query
Essentially my approach now is closest to the candy crush metaphor - a user sends a "move" as their turn and the server does a bunch of processing (perhaps merging a bunch of chains and adding new candies to the field) and sends the delta (changes) back to the client (no state, just the changes). The clients both animate the changes (with my own custom coroutine/queue animator) and then the client whos turn it is, is now ready to move.
My server architecture is a bit different than this -
Essentially I have a pool of Battles with the comprehensive state in that POCO - and when an incoming message from a client is received (say, "client 12345 moves an item from (1,2) to (2,3)") then it looks up the battle, processes the turn, and sends the updates to both clients in the battle. There's some .. other stuff, where the server loops through all active battles to ensure that clients are taking too long on their turn and sends "hurry up" messages to the clients (with the future implementing being "the client skipped their turn because they took too long") but we can mostly ignore that for now
But I do like your approach a bit.. in terms of "process event" enumeration and subscription .. just chew through the events as they arrive (likely in order or packaged up into one packet) and periodically get state if needed
yeah the biggest advantage to the async Task GameLoop() { } approach is you get c# stack == game stack
say that again..?
it can be very confusing when your "game stack" is splayed out as a bunch of network messages sitting on lists
Ah, yeah
One of the problems I've had with this project is the amount of manual .. uh.. state inspection? to examine various things
network messages, game state, etc..
so like, if you throw new Exception somewhere deep inside your rules, you will see a stack that looks like
FindNeighbors
FindLongestChains
PlayTurn
RunGame
Debugging state is difficult when it's all buried in Lists of objects without one clean "state" object that's easily inspectable in VS debuging tools
or you can visualize all the running games as Tasks, and you can see exactly where you are waiting for user input at that particular point of time
and the stack of the task would make sense
the best thing to do, if you have the chance to do it from scratch, is to use an IDL (protobufs, thrift, cap'n'proto, whatever) to describe your state
so that what you send over the network == what is stored inside your game
Aye - unfortunately I'm too far in for that, but I can probably whip together some sort of my own DIY IDL
if you have a "rendering version" of the thing you want to send (fore xample you do not need to send a lot of internal information like the seed of the game naturally) it's still useful
some things, like cap'n'proto, support in-place mutation much like any other blob of state
Hi there
does anyone know a way to figure out the local pos of a UI element based on input?
currently I have this function
private void UpdateVisualCircle(Vector2 screenPos)
{
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform,
screenPos,
Camera.main, out var newPos)) return;
inputVisual.transform.localPosition = newPos;
}
but it doesnt work
my parent is an expanded Rect that fits half the screen size and the child is in the middle of it
all I'm getting is just coordinates a few floats apart, regardless of input
What mode is your canvas?
it's just not how this stuff works
if you have canvas scaling for example
this will not behave the way you believe
i know it's super frustrating
"how do i get a fucking point in a UGUI UI??"
screen space overlay
Cam needs to be null then as mentioned in the docs.
aoght
that was exactly it, thanks
hey guys, anyone know if you can combine two texture UVs ontop of each other and have one have some transparency so it can stack on top
depends on the shader you are using the UV with. I.e. you can make one that behaves that way.
im making a 2d sprite game tile based by meshes/quads and uvs, i turned shaders off in this case
im just wondering if i can go about it procedurally
is there a command or functionality for combining two UV coordinates together
or maybe i can bitmask specific pixels out of the secondary layer
then would i need to make a separate UV mesh to go ontop of the other
there's no such thing as "turning shaders off"
x)
if something is drawn on screen, it's using a shader
i selected the option that disables shaders in unity or w/e
If you want some custom rendering behavior - you need a custom shader
there is no such option
which dropdown box
ahaha na ur right i just disabled some options not actually shaders
so wud u suggest some shader magic in that instance?
so im making a tile based 2d game with meshes/uvs
and im gonna bitmask the 8 tiles around it to select the texture
that part will be fine to implement
now just wondering if i can have transparent edges and a layering system so that transparent edge tiles will draw over the neighbours
that seems to invite some z-sorting headaches, especially in corners. You'll likely end up with some sort of custom handling of the edges and corners if you aren't specifically going for an alpha-accumulation effect.
trying to simplify it
i just need to know if there is a command to layer two texture uvs on top of each other
then i can just test for neighbour
and combine them
and alpha surely can just bitmask it out
as i said before, you have to make it yourself
if you're dead set on doing it via UV overlays then, yes
standard solutions are marching squares and tile lookup tables
yea so marching squares was what i was gonna do
bitmasks to create corner tiles
thats no problem
im looking for a layering so that i dont have to create a * b amount of 'inbetween' tiles
marching squares have a lot of mirror/rotationally identical cases
yea 255 can be brought down to 47
the issue will be different tile types
so an inbetween set for 'water' and 'grass'
then as many inbetween sets
but the issue of having insurmountable tiles is solved with transparent layering
usually you decide on a "height" of each terrain type, i.e. a z-order... then the boundaries/overlaps solve themselves
and advanced version would be something like this:
my only problem is having two UV textures overlayed on one single tile
or atleast thats the code i need to solve my problemo
do u reckon a bitwise command will allow me to blend two uvs
| OR & AND
like the old sprite days
wdym
bitmasking shiznit
yes, but what exactly
if i can bitmask the black channel out for transparency
you can do quaternion rotations by bit twiddling...