#archived-code-general
1 messages Β· Page 304 of 1
You can get the collider that is involved from the Collision event
how expensive is it to instantiate bullets in an online game, GetComponent<RigidBody> for each of them and thrust the bullets forward?
I assume it's a less-than-ideal solution
just hold a reference to the rigid body in your projectile class
and then hold the prefab as a Projectile
then you dont need to use getcomponent
wouldn't I still need to access the projectile's class with GetComponent?
this
oh I think I get it
you dont need to hold a prefab as a GameObject
why not just store the prefab reference as a Rigidbody in the first place
oh sorry Umbra got you sorted
If there's a Projectile script - use that instead
and have that script interact with the Rigidbody, which you can directly reference since it's in the same prefab.
then I can just thrust the projectile forward on their own Start(), right?
or am I missing the point
just set the rigidbodies velocity to some vector and it will move in that direction with whatever magnitude
well not all projectiles will be thrust forward at the same velocity, as I'd ideally get that data from the gun's scriptable object
well you need a direction as well
not just a magnitude
when you instantiate the projectile you would multiply some unit vector for the direction by the velocity on the guns SO
the direction isn't a problem, that's been sorted
Since save data is meant to save runtime data, should I use properties in my save data?
[SerializeField]
public class PlayerQiData
{
private float _Qi;
internal float Qi {
get
{ return _Qi; }
set
{
_Qi = value;
if( _Qi > QiMax)_.Qi = QiMax;
else if(_Qi < 0) _Qi = 0;
}
}
internal QiMax { get; set; }
}
Is this going too far? Should I store it in my Character class, and keep saveData as a backing field for my properties?
I am doing that
whats the issue then?
the one and only problem is accessing the rigidbody
i already told you how
well, doing so in a less dumb way
not yours, mind. mine.
and hold a reference to the rigidbody in that class
yeah I'll do the second approach
does anyone know how do i select multiple variables that have the same name at the same time in VSC like how you press alt in pycharm and select multiple selections ? is there a shortcut for doing that in visual studio?
ctrl r r
you can use properties, its not like theres really a correlation between it and runtime data. it would be the same as if you had a method which returned the specific data
[Serializable]
public class CultivationData
{
public float Qi;
public float QiMax;
public float QiMaxForBreakthrough;
}
//Player class
private CultivationData CultivationData { get; set; }
internal float Qi {
get
{ return CultivationData.Qi; }
set
{
CultivationData.Qi = value;
if( CultivationData.Qi > CultivationData.QiMax) CultivationData.Qi = CultivationData.QiMax;
else if(CultivationData.Qi < 0) CultivationData.Qi = 0;
}
}
So this is how I do it now, just not sure which way is better.
I am even storing private reference to the data, so I dont have to look it up each time.
actually @merry stream to prevent this issue from arising again in a different scenario, I'm unsure what you mean by "hold the reference as a rigidbody" in the first possible solution
Maybe I am going against the whole idea of separating save data from the object.
are you currently holding the reference to the projectile prefab as a gameobject?
it is, yes
you can instead use any component also on that prefab
so Projectile, Rigidbody, etc
right, but then how would I instance it?
there is a clamp function which you can use to shorten down that setter, but if it works then its fine as is
the same way
Mostly unsure how Json will save the data, should the save data only store data, or should I have some functions in there?
I was under the impression unity could only instance gameObjects
doesnt change anything
Why does my player rotate around himself everytime i press the WASD keys to move the player himself?
https://gdl.space/dayeqabaqo.cs < CharacterController script
https://paste.ofcode.org/KvAHCNW6XANHwqx7nuzQgK < CameraManagement scirpt
Sounds good, thanks.
that reference still holds your whole prefab
which is a gameobject
it just is under the type Projectile
so I can change the type to Projectile, reference that from the prefab, and the instance will be acquired just fine?
yes
so what, do I just instance, say, bullet.gameObject?
no just insantiate it like normal
ProjectileMB projectileMB = Instantiate(projectilePrefab, spawnLocation, Quaternion.Euler(0, 0, Random.Range(-150, -200))); this is what i do for example
could've sworn rider was throwing an error my way trying that, one second
maybe because you are still doing GameObject x = Instantiate
that is correct
pretty silly thing not to notice
alright, thanks a million for the help
np
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
public void OnCollisionEnter2D(Collision2D collision)
{
Vector2 newVelocity = collision.relativeVelocity;
Debug.Log(newVelocity);
if (collision.gameObject.tag == "Vert Wall")
{
Debug.Log("Velocity to change to: " + new Vector2(newVelocity.x, -newVelocity.y));
rb.velocity = new Vector2(newVelocity.x, -newVelocity.y);
} else if (collision.gameObject.tag == "Hor Wall")
{
Debug.Log("Velocity to change to: " + new Vector2(-newVelocity.x, newVelocity.y));
rb.velocity = new Vector2(-newVelocity.x, newVelocity.y);
}
}
I cant seem to find problems in this code except setting the rb.velocity. Im not sure what to do
sorry for pasting twice, just i think they are having another problem in the beginner chat, and i didnt want mine to be overlooked
what is wrong with it?
the goal is for when a ball hits a wall its velocity corresponding to the wall reverses, but it just stops. the correct vector is logged, but for some reason not set.
okay i found the problem but im not sure how my logic was wrong
Seems like you have the logic for vert wall and hor wall reversed
well, a vertical wall goes up and down, so x value is towards and away from it, while y value is up and down as well (along it)
i tagged my objects wierdly for some reason. the walls above and below the player are tagged vert walls, and to either side hor walls
Well if that were the case, the code should have worked. hmmm
im so confused π
well uh i mean i guess it works for now so im just gonna pretend i know whats going on
let me know if you find what i got wrong
Sounds good to me hahaha.
And I will
tysm for the help :D
Is there a cleaner way to do this:
public Party(int index)
{
this.index = index;
PartyData partyData = SaveManager.Instance.SaveGameData.PartyData[index];
if (partyData == null) SaveManager.Instance.SaveGameData.PartyData[index] = new PartyData();
PartyData = SaveManager.Instance.SaveGameData.PartyData[index];
}
Basically, I check if dictionary has data with key index, if it doesnt I make new instance then I assign it to my variable.
public Party(int index)
{
this.index = index;
Dictionary<int, PartyData> partyDict = SaveManager.Instance.SaveGameData.PartyData;
PartyData partyData;
if (!partyDict.TryGetValue(index, out partyData))
{
SaveManager.Instance.SaveGameData.PartyData[index] = new PartyData();
}
PartyData = partyData;
}
Updated to this, is it any better?
it's smelly to my eyes. This looks like something whatever SaveGameData is should be doing. Instead its guts are hanging out and you're manipulating its internal state externally
I agree, there will be more similar cases so having it in SaveGameData might be a better idea.
You forgot this:
this.index = index;
Dictionary<int, PartyData> partyDict = SaveManager.Instance.SaveGameData.PartyData;
PartyData partyData;
if (!partyDict.TryGetValue(index, out partyData))
{
partyData = new PartyData();
partyDict[index] = partyData;
}
PartyData = partyData;```
But out partyData returns partyData since I check for !
Yeah but you're not assigning it properly in the case it doesn't exist
PartyData = partyData; is going to assign null to PartyData in your code
if (!partyDict.TryGetValue(index, out partyData))
{
SaveManager.Instance.SaveGameData.PartyData[index] = new PartyData();
}
PartyData = partyData;
If(doesnt exist) new PartyData();
else out partyData
huh
partyData never gets the new object reference here^
doesnt out return partyData?
oh see
I think, let me check again to be sure
I see yeah
Hmm I should probably have a function GetParty on SaveGameData class which would handle this and return new party
PartyData GetParty(int index) { }
But tbf, when a new party is created, that data shouldnt exist + I should delete that data if party is deleted.
This is just extra check to be sure.
Final code would be:
[Serializable]
public class SaveGameData
{
public GameData GameData = new();
public Dictionary<int, PartyData> PartyData = new();
public PartyData GetParty(int index)
{
PartyData partyData;
if (!PartyData.TryGetValue(index, out partyData))
{
partyData = new PartyData();
PartyData[index] = new PartyData();
}
return partyData;
}
}
hey guys i know this isnt code-related but I dont know where to ask this. What's causing this sort of blur from a certain distance on the texture? It also shows when in the editor
it happens on pretty much every texture/material as well
No expert here, but I'd check camera settings
Clipping
Forcing Anisotropic Textures in the Quality tab under Project Settings fixed it, thank you!
They also mention mip map settings
https://forum.unity.com/threads/textures-blurry-from-some-distance-but-normal-when-very-close.507260/
There is some code solution, not sure if related.
Turning Off Mip Maps will solve the issue but will cost extra computation the optimal solution would be aniso level to 16.
https://stackoverflow.com/questions/56589040/howcan-i-prevent-blur-in-far-away-textures
aye i think youre right its to do with mipmaps
thanks for the help dude im sure i can figure out a solution now that i know the cause
Np, good luck ;]
@leaden ice oh no...I did all of that work, but JSON doesnt seem to serialize dictionaries? lol
I mean Unity by default doesnt serialize them
kinda but you need newton soft
Unity's json utility will only serialize what you can usually serialize with the editor'
yeah we went there before, but I was convinced to use JsonUtility.
Guess I might just use Newton soft and try it again.
you can pretty much serialize key value pairs as structs then construct the dictionary in awake if you wanted
as structs?
oh
like having a list of List<structData> and structData stores key/value
yeah, that's how you'd normally do it
Well the idea was to use saveable data at runtime too, so I read from it, and save it.
If I add another layer, I might as well not use dictionaries?
or both I guess
or maybe when saving/loading I recreate a List of structs
if you want that quick access time you'd make the dictionary, otherwise a list orhash (well, you can't actually serialize hashsets without newton) of save data which you don't care how it's managed you can probably leave alone
such that you iterate over it without the care of ordering just to load your data
Yeah I do want a dictionary, but newton soft works good so far so I might stick with it.
yeah it's good. No reason to not use it
proly consider using array instead if they're structs ? so later on you can do AsSpan() for fast ref iteration. Array + value type is the best combo ever
side note, you can easily(accidentally) make copies when iterating over value types due to the internal enumerator which you might not want that
Might wanna ask in #archived-hdrp
So basically i'm better of googling it, ok.
Oh, why?
I mean, googling is good too π€·ββοΈ
Yea i've been trying that, this was my last resort
Well #archived-hdrp is gonna get you the best help. Uri and spazi know it well, there is even a unity dev that works on it (iirc) that frequents the channel
Random question but do interfaces in lists have issues when checking if theyre null? I cannot figure out what this bug is but it's saying I should check the script before trying to destroy it. This is because IPickupable destroys itself after x amount. All I need is to check if the interface script has been destroyed but its not working
{
if (pickupable != null)
{
pickupable.Destroy();
}
}```
pickupable.Root too which refers to its gameobject
wdym by "it's not working"?
No interfaces don't have issues checking if they're null BUT if you're trying to detect if the obejct is destroyed, this won't work
because the interface doesn't follow Unity's overridden == operator
you'd have to do this:
foreach (var pickupable in IPickupables)
{
if (pickupable is UnityEngine.Object uobj) { // it's a unity object
if (uobj != null) { // this does the special unity null check
// it is not null nor has it been destroyed
}
}
else if (pickupable != null) // it's not a unity object, so this does a normal true null check
{
}
}```
i think I ran into this before and this helped ill give it a shot
Your script should either check if it is null or you should not destroy the object.```
Still happening unfortunately
Its trying to run one of the functions
HealthPickupable.Destroy ()
for such an error you'd have to show the line it's happening on
that's not related to this code
When I destroy the interface/object I can't remove it from its list can I? If I were to iterate through the list at the same time its destroyed there wilbe an error
of course you can remove it from the list
and you should
Destroy(pickupable);
{
OnDestroy?.Invoke();
Destroy(gameObject);
}```
you failed to check if it was already destroyed here though
check my example
ahh right
see how I did the if (uobj != null) part?
but yeah you really should just remove it from the list when you destroy it
got it ill do that firstg and see
lets say that I have a coroutine that iterates through a list after X time, but that object is removed from the list as its iterating. What are the chances of that happening?
your ide will yell at you dont worry
you mean it iterates with a yield inside the loop?
that's a terrible idea for a list that is liable to change over time
right so in this case, after X seconds it will destroy theobject but if the player picks it up
it wil destroy
if there is no yield in the loop, there is 0 chance
Hi guys, i got some problems with cinemachine, i got 2 target in cinemachineTargetGroup, 1 target with "weight: 1", other is "weight: 2", so that i can get a 2ndtarget stand a little more in the middle of the screen, but got problem that 2 target will can not keep in the screen when they moved too far each other (1st target will go out of screen)
I'm trying to create an asset using AssetDatabase.CreateAssset(), but multiple will be created with the same name. How do I add a number at the end so assets don't overwrite each other? My code is abstracted, so it's not as simple as putting it into a for loop and just appending an int onto the end of a string.
Have some kind of counter that all the places where you create an asset have access to.
Maybe some kind of context object that keeps track of what's of different assets created so far.
What does the 'is' do exactly? Is it force declaring pickupable as the object?
What do you mean by context object?
It's pretty much the same as ==
it checks if the object is of that type
What really? I've always been mistaken I guess
so can I use this to check if lets say if its another interface? Kind of like trygetcomponent?
It does different things in different contexts
GetComponent is very different
GetComponent grabs a component of a specific type from a GameObject
It's always worked for me even though I've been using it wrong π what a world
this checks the type of the object you have a reference to
for some reason this doesn't work:
GetComponent<MeshRenderer>().materials[0] = Materials[arrayIndex];
Again it has different uses in different contexts.
.materials returns a copy of the array
you need to assign the whole array at once
Material[] mats = myRenderer.materials;
mats[0] = whatever;
myRenderer.materials = mats;``` @dull glade
An object that you pass around that contains the current context(data or info) of whatever it is you're doing.
Look up context design pattern
Never heard of AsSpan(), I read that it is used on a string?
proly bcos most examples for spans are for char arrays π
Just wondering on the topic on timers, can a fluctuating framerate create problems with methods that operate on an interval, such that perhaps the interval is short enough that perhaps you skip over one when your frames suddenly dip?
assuming you compare these timer operations by real time
like, should I expect to need to implement some catch up
I do notice that lerp operations sometimes won't complete if the operation itself is done in very few frames, so it's recommended to set the final value after completing the lerp operation
This is what FixedUpdate is for
Physics calculations can't afford to vary their dt too much
Compare the values of Time.deltaTime in Update(), and Time.fixedDeltaTime in FixedUpdate
thing is, stuff like say effects that linger over a time is usually shown using real time and not frame time, so I'm not sure how correct it is to do it by frame time
I assume you can probably do it by fixed time though
It is indeed by fixed time
lerp on the other hand for like visuals you do in update
// making an effect linger for 1 second.
float progress = 0;
[SerializeField] Transform particleTransform;
Vector3 startingPosition, endingPosition;
void FixedUpdate() {
progress += Time.fixedDeltaTime;
Mathf.Lerp(startingPosition, endingPosition, progress);
}
over 1 second the particle travels from the starting position to the ending
progress is the amount of time passed since starting, in seconds
Do you have any example of what you're doing, or with numbers. I dont believe there is any issue that cannot be solved in this
You most definitely dont need to use fixed update
In general, say you have something with a 5 second duration, but let's say you have 1000 intervals
so you're expecting to execute this code every 0.005 seconds
maybe im over thinking it and need to do more testing, but the program should catch up, it just confuses me a bit with coroutines in update and such
yet sleep using real time
Are you talking about a case like trying to run something more than once per frame?
why do you need 1000 intervals
that's just a extreme sample
It's a hypothetical..
when it comes to unity we try to keep stuff within Update(), happening once a frame
and you won't get 1000 FPS all the time
it would be over whatever amount of frames until 5 seconds real time
maybe it should be fine. I bring this up because lerp can skip in update which is why you do want to set the final value after lerping
your code is gonna be run every 0.005 seconds right
float progress = 0;
void Update(){
progress += Time.deltaTime;
if(progress > 0.005) {
float catchupRatio = progress/0.005; // the multiplier for your code to catch up with
}
}
I really don't understand why you want a fixed interval
still should be easily solved like basically you have
float timer = 0f;
float intervalDuration = 0.005f;
void Update()
{
timer += Time.deltaTime;
while(timer > intervalDuration)
{
timer -= intervalDuration;
DoSomething(); // will be called multiple times per frame if needed
}
}
then plus whatever extra logic to stop this at either 1000 intervals or 5 seconds
also typed on discord so might be a typo
right, but assume you want to be accurate as possible. Here you just say for every 0,005f secs, but assuming you do want all 1000 instances to happen in those 5 seconds
but let me test that code a bit and see how it works out with me destroying my frames a bit
i believe i wrote a similar code lately for my DOT system
yeah exactly
I can't say this ability is going to tick 10 times in some duration and it only ticks 9 becomes some fluctuating haha
i have test scripts already setup, give me a moment too ill see if its accurate somewhat
thats actually something i was worried about with my system
the option is basically either check if the elapsed duration is over 5, or manually track the number of intervals. Either one is gonna require an extra float regardless
wouldnt be hard to do some catchup and check how many intervals happened and apply it all at the end of the duration
the while loop is the catchup part
if someone lags for 5 seconds (DT is now 5) then it becomes timer += 5. The while loop will subtract until its "caught up"
the only issue of course being if they lag for 6 seconds. Now they've taken more damage (oops damage is related to my DOT system not your ability) if theres nothing inbetween the while loop
make sense. I was thinking fixed update too as it does do some catchup itself, so that's something else to test
no good resources on this issue I've came upon
i believe fixed update has a limit to its catchup
beyond like network catchup issues
fixedDeltaTime will not exceed the duration specified in Project settings, by default it's 0.02
or 50 updates per second
you can increase the updates per second but unexpected things might happen
right, technically fixed can also run more than update if your frames drop far enough below
just another thing to add to my backlog of testing when ever I get to it
theres really no reason to add it to fixed update, i think you'll get more inconsistent results anyways by doing so
compared to the above while loop
I'm ngl this has a bit of a problem because you will get more than 1000 intervals in 5 seconds
e.g. if the DT is 0.0124,
it gets executed thrice for 0.005, 0.005, and 0.0024
https://docs.unity3d.com/Manual/TimeFrameManagement.html
The section on Time variation and the physics system somewhat goes into the catchup
we arent talking about moving an object though
if we were, id include the timer as part of it
we are just talking about running something exactly 1000 times in a 5 second interval
i was keeping track of the elapsed duration, but itd require (1 line) more math to avoid doing extra logic like 1002 intervals. It seems to be working fine now with this
public bool Tick(float deltaTime)
{
tickTimer += deltaTime;
while (tickTimer >= tickRate && tickCounter < maxTicks)
{
// Apply damage and reset the timer for the next tick
DamageInfo info = new(sender, target, damageType, damagePerTick, true);
info.DealDamage();
tickTimer -= tickRate;
tickCounter++;
}
// Return true if the DOT duration has ended
return tickCounter >= maxTicks;
}
tickRate * maxTicks = total duration
this is just a part of my DOT stuff, so ignore the damage parts
aye, alright ty was just making sure I wasn't overthinking it
not that I am going to make some extremely small intervals, but I am allowing the modification of it at runtime
The answer to my problem was AssetDatabase.GenerateUniqueAssetPath().
Hello everyone, I have a small question about firebase
public static async UniTask<AuthOperationResult> SignInWithEmailAndPasswordAsync(FirebaseAuth auth, string email,
string password)
{
try
{
var result = await auth.SignInWithEmailAndPasswordAsync(email, password);
Debug.Log($"Login succeeded with {result.User.Email}");
return new AuthOperationResult(AsyncOperationStatus.Success, user: result.User);
}
catch (FirebaseException exception)
{
Debug.LogWarning($"LoginFailed : {exception.Message}");
return new AuthOperationResult(AsyncOperationStatus.Failed, (AuthError)exception.ErrorCode);
}
}
Here I have a simple login by mail to Firebase
and itβs very strange, but for example, when entering a non-existent account (email) or when entering an incorrect password, it does not give me the corresponding error codes
but simply displays the code Failure internal error
you might have a better chance at help in a Firebase discord server. There's one called Firebase Me
Here's the link that got caught https://discord.gg/kTZ4x4K9
Hey, i'm using an Additive Loading Scheme with a master scene (which is at 0 in the build index and should always be loaded).
How do I Unload all the currently loaded scenes Except the Master Scene so i can freshly load a new unrelated scene?
Does anyone know which one I should pick I want to overite the branch with my local:
I feel like i'm difusing a bomb
I have the following error:
UnityException: get_isPlaying is not allowed to be called during serialization, call it from Awake or Start instead. Called from MonoBehaviour 'MyMonobehaviour' on game object 'MyGameObject'.
See "Script Serialization" page in the Unity Manual for further details.
MyMonobehaviour.OnAfterDeserialize () (at Assets/Scripts/MyMonobehaviour.cs:54)
I am trying to check the isplaying because otherwise a tryparse fails:
public void OnAfterDeserialize()
{
#if UNITY_EDITOR
if (Application.isPlaying == false)
{
return;
}
#endif
//2021-10-27 10:23:55
if (DateTime.TryParse(EndTime, out DateTime time))
{
EndTimeDateTime = time;
}
else
{
EndTimeDateTime = ServerSync.CurrentTime.AddMinutes(10);
Debug.LogException(new InvalidConstraintException($"Parsing of the EndTime failed (EndTime: {EndTime}"));
}
}
Anyone knows a good solution?
use the modified file
hold on, why does that cause datetime parsing to fail?
why is the tryparse failing?
As in editor the Endtime is null by default
so check for null instead of isPlaying
Then I won't have errors if it is null in runtime
you will if you want to have them
a serialization callback is probably not the right place to do that validation
How would it do Debug.LogException in runtime but not in editor if I check for null before hand?
Where would be a good spot?
by wrapping it in a define
That's not how defines work though, they are compile time not runtime. If I wrap the error with a #if UNITY_EDITOR it will still log exception since playing in editor is still in editor
To clarify, I want no errors outside of playmode, only inside playmode (a.k.a. runtime)
let the serialization callback just leave the value as empty if the EndTime isn't set, then whenever you use it in runtime code you can tell that if EndTime is null then EndTimeDateTime must also be invalid
maybe in an OnValidate method?
That's an interesting idea, depending on order of execution that might be the solution
Otherwise, your other idea will work although I am not a fan of it
is it normal that when saving the script in visal studio Unit lags like a few second to update the code?
Yes
you mean you want the exception in a build but not in the editor?
I'll stay away from OnValidate as the documentation highly recommends to only keep it to validating data and my case would be also setting data to see if I can disregard the error in the callback. But ty for the suggestion
I want the error in a build AND in the editor but ONLY in the editor if I am in playmode. With playmode I mean if you're hitting the play button and your game runs.
Currently, the error happens outside of playmode in the editor whenever code recompiles
maybe just do it before the first use of it in game code then i guess?
Yeah I'll figure out a workaroudn of some sorts
thank you both for looking into it @knotty sun @thick terrace β€οΈ
you can subscribe to these
https://docs.unity3d.com/ScriptReference/AssemblyReloadEvents.html
and set your own bool to check in your script
Thanks for this!
Working with OnGUI and this is what I get on screen:
That should be a readable string. Any idea what the cause might be?
Whats the difference between Start() and Awake()?
I am working on a legacy project π
Hope this helps: https://docs.unity3d.com/Manual/ExecutionOrder.html
Awake is called before start during the initialization, start is called after awake and before update on the first frame of the game
Thanks
I am attempting to stop all coroutines on a script from the outside, by using the StopAllCoroutines(). To my surprise, the code is not stopping my coroutines.
From what I've read, it seems the issue is that if a Coroutine is started with "yield return MyCoroutine" instead of "StartCoroutine(MyCoroutine)," then StopAllCoroutines() will not stop it.
Is there a workaround to this?
i thought there'd be more to it
Yes, but that's just to stop a single coroutine if you have stored it in a reference.
I want to know if there's a way that I wouldn't have to individually store and stop every coroutine that happens, and I thought I would be able to utilize the already existing functionality of StopAllCoroutines.
If it doesn't stop the one started from yield, it sounds like you'll have to store and stop them yourself
why do I get this error
merge conflicts open the text editor and fix them
Yeah I would say your file has merge conflicts in it.
@chilly surge As i promised, i will update ya. I was using a readonly struct which had some reference-type values inside but as far as from my re-searches, this is not a problem you can use reference variables inside a struct as needed.
The main problem is, C# CLR on the backend uses boxing to compare values unless your struct didn't override the Equals() method(s).
Quote from Senior Engineer(2018):
The way the CLR is designed, every call to a member defined in
System.ValueTypeorSystem.Enumtypes cause a boxing allocation. Which means default implementations are pretty slow and using boxing for each member. Unless the method is a JIT intrinsic. For instance, in Core CLR 2.1 the JIT compiler knows aboutEnum.HasFlag(x)and emits a very optimal code that causes no boxing allocations.
So that is the reason why i was getting that Garbage overhead. Do not forget to override yourEquals()method in your struct as your needs next time and enjoy your development β€οΈ
this made me curious enough to try and i can't reproduce it, i only get two lines logged with this code, as i'd expect:
IEnumerator Start() {
StartCoroutine("A");
yield return null;
StopAllCoroutines();
}
IEnumerator A() {
yield return B();
}
IEnumerator B() {
for (var i = 0; i < 4; i += 1) {
Debug.Log($"hello world {i}");
yield return null;
}
}
If only Unity had high enough C# version to support record struct, that would save all the annoying manual labor.
I guess record is good enough if you aren't allocating tons of them, and Unity supports record.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/records
Could you tell me what is a record does it is quite complicated to understand the difference from their examples.
well why not just use yield return StartCoroutine(...)
Compiler generates the code for Equals/==/!=/etc for you so you don't have to write them yourself (and side benefits like nice syntax sugars)
your struct will just keep the reference, while the reference itself will still land on the heap. yeah shouldn't be an issue here
sad that defensive copy still exists on record structs π
To add to that: Before any object's Start runs, all other objects Awake is guaranteed to have ran. This is why I like to do internal initialization in Awake, and anything that depends on outside stuff in Start.
for reference, if you:
Instantiate(objA);
Then before you get to the next line, Awake() and OnEnable() have already been called on all its scripts
Start() might not even be invoked until next frame
doesn't marking methods readonly or using readonly record struct help with this? i can never remember the exact rules
that wouldn't save you even
if it's a read-only and the object is manipulated, like for example from within the struct itself (via methods) it might create a defensive copy still
right, but the compiler knows calling a readonly method won't do that, doesn't it?
the compiler does not now in this specific case, it just assumes as part of their safety mechanism thus defensive copy
which specific case do you mean?
hii, is there like a help section in this server?
like a uhh "how can i achieve this effect"
Isn't the entire record struct marked as readonly so defensive copy isn't a concern?
And doesn't defensive copy only kick in if you are passing with ref?
no, it's still suffer the same issue like with the regular struct
you're thinking of readonly record struct
Ah, is that not the default?
nope, you can make mutable records
Makes sense. In my head mutable records kind of defeats the purpose so it doesn't cross my mind.
I meant this whole defensive copy stuff.
You can test this on Sharplab, make a custom struct define a method in it to increase a number to one of it's member, instantiate the struct, execute the method in that struct then right after it call ToString() from anywhere in other classes and whatnot. You will see it'll create a copy right before the ToString()
Hi, I would appreciate your help
I'm trying to make a line rotate to a certain angle, and I want that angle to be the angle formed between vector3
Can you be more specific about "line"? What kind of components are we talking about?
And what does your code look like right now? And what's going wrong?
https://www.developmentsimplyput.com/post/defensive-copy-in-net-c
Uh there is exact example about that. Was reading about it after you say 
yeah it's an easy and simple test that's alos used in the official dotnet repo
you can check there too
i don't think we're talking about the same thing because if you mark a method readonly you can't increment a member
what I meant is this somenumber += someReadOnlyField;
It says this. So editing a field in the readonly struct directly would not trigger the behaviour it right? Complicated a little ._.
So it's not an issue if you mark the struct as readonly then.
it might still
How so?
yes, this article says marking a struct as readonly gets rid of defensive copies, and i'm pretty sure marking a single method as readonly achieves the same thing
Genius solution
while (isBuilding)
{
RaycastHit hit = playerManager.RayCast();
if (hit.collider != null && hit.collider.tag == "Floor" && hit.point != Vector3.zero)
{
temp.transform.position = hit.point;
}
if (Input.GetKeyDown(KeyCode.E))
{
print(build_Child.canPlace);
if (build_Child.canPlace)
{
Vector3 loc = temp.transform.position;
Quaternion rot = temp.transform.rotation;
Destroy(temp);
Instantiate(building_Item.Prefab, loc, rot);
isBuilding = false;
Destroy(caller);
}
}
float scrollDelta = Input.mouseScrollDelta.y;
// Check if the scrollDelta is not zero
if (scrollDelta != 0)
{
if (scrollDelta > 0)
{
temp.transform.Rotate(0, 15, 0);
}
else
{
temp.transform.Rotate(0, -15, 0);
}
}
//if (Input.GetMouseButtonDown(0))
//{
// Destroy(temp);
// caller.SetActive(true);
// isBuilding = false;
//}
print(isBuilding);
yield return null;
print(isBuilding + " End");
}
print("Done");
```
the lines that isnt working is these
```cs
print(isBuilding);
yield return null;
print(isBuilding + " End");
``` the first print works and is printing but the second one never executes. when the return null is dosnt execute anymore code in the entire coroutine
are you perhaps disabling the gameobject or stopping the coroutine somewhere?
when you pass the read-only struct via in
Your object is being destroyed or deactivated
no the gameobject is still active and has the script
doubt
as sad as it sounds the compiler might creates a defensive copy if it's passed via in
is that not the defensive copy that readonly types are designed specifically to avoid?
put a log in OnDisable and you'll see that the object is likely being disabled or destroyed
and it's the GameObject not the component being disabled
yea i know but it dosnt get disabled as of what i have seen but i will try to log OnDisable
sure you may not see it be disabled, but that doesn't mean it isn't. even if it is disabled for less than a frame it will stop the coroutines running on it
no it dosnt get disabled
private void OnDisable()
{
print("Disable");
}```
@chilly surge see that
if you are not seeing that print to the console then something is calling StopCoroutine or StopAllCoroutines on it
i've read that article before, this is what i'm referring to
yeah, read one more line exactly under that screencap
It means that you should never pass a non-readonly struct as in parameter.
yes, that's what i'm saying too
if the object that started the coroutine is disabled will it stop the coroutine
yes because that is the object that owns the instance of the coroutine
Yeah, so if a struct is readonly then it shouldn't have defensive copy issues.
alright then that the issue
you can still fall into accidental boxing hell though lol
Whatever object that StartCoroutine was called on
it can,, give me a sec, I'll throw sharplab link here
Hello guys!
In the built-in pipeline is there any way to directly access the shadowmap of a directional light source?
Yes, your code doesn't work, as StopAllCoroutines method does just stop the Coroutines that are currently running in the class it's being called, so in order to stop the Coroutine from a specific class, you'll have to call the StopAllCoroutines method directly from that class.
There are several methods to do it.
1. Stop all Coroutines directly from the class.
Create a class deriving from MonoBehavior with a StopCoroutines method to avoid troubles with the same names (MonoBehavior.StopAllCoroutines).
Derive every class, which Coroutines should be stopped, from this one.
public class XebarsisBehavior : MonoBehaviour
{
public void StopCoroutines() => StopAllCoroutines();
}
2. Create a method
Create a method which gets all the Coroutines from the Behavior and stops them.
private static void StopAllCoroutines(Behaviour behavior)
{
FieldInfo[] fields = behavior.GetType().GetFields(BindingFlags.Instance |
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeof(Coroutine))
{
Coroutine coroutine = (Coroutine)field.GetValue(behavior);
if (coroutine != null)
{
print($"Coroutine {coroutine.GetType().FullName} stopped.");
StopCoroutine(coroutine);
}
}
}
}
was this AI generated? because none of it is necessary
What do you mean?
They have asked how to stop the coroutines from the another class
right. and did you generate that code to share with them or did you write it yourself?
This is not AI-generted. I wrote it myself.
I assume, AI would have given a totally different answer
then perhaps you should look up the StopAllCoroutines method and learn that it is a public instance method so they can just call it on a reference to the MonoBehaviour they would like to stop the coroutines on
Damn, exactly
I even wrote MonoBehavior.StopAllCoroutines there
Dang. The second suggestion is wiiiild
Completely unnecessary
First one is a weird abstraction from just calling StopAllCoroutines() directly. I don't get the reason for it
Hello, Im looking for resources to learn how to plan my game (non ecs) including systems, state machines, event buses, gobjects, points of extension so i can see where to use interfaces and where i will probably only use single class etc.
The kind of planing where u draw it out on visual boards such as miro or figma.
Or should i just mvc or ecs for everything? But that also requires afromentioned planning phase i think
current attempt: https://cdn.discordapp.com/attachments/558684020381188097/1227661196770017330/image.png?ex=66293796&is=6616c296&hm=4105003c9fde956d29faa4af45c756c6d5d8951a58bbe1b56f4e0079e3696c10&
its not separated by namespace but i dont think that will help much and its hard to plan like this in terms of object inheritance or composition and its obvious im reinventing the wheel
please show me the wheel
there's not really a universally right answer because games are so varied, it depends heavily on the design and gameplay
so basically learn as many different patterns as you can and pick one that fits your design π₯²

MVC is great for heavy ui games, but not much use if your game is 90% physics
im feel like any game can be abstracted to systems -> thing interactions handlers (coupling where two+ users talk to each other but depend on this kind of system yet system dont care about its users) -> abstract things / concrete things -> inherited things from the abstract things -> concrete things
or at least im coping to find such a method
i'd say planning out your states is a good starting point for most games too, whether or not you structure the code into states like that
You're right. I first read the answer and was planning to iterate through every class in the solution, but then forgot it and just iterated through every field in a Behaviour. Honestly, I haven't even mentioned how dumb it was to create a class to just call StopAllCoroutines methods.
I should have reread it first
DOTS is driving me crazy actually
I'm not making a dots post yet because I don't even know where to begin
it feels like the entity inspector and what is happening on screen is only tangentially related
like the thing I see in game view and the thing the inspector sees are two different entities that only sometimes get the same systems applied to them
Am I going crazy?
I made idle entities float up
I make them go somewhere and float down
inspector shows them going there and floating down
game view shows them keep floating up in the original spot
am I going crazy?
basically, each piece of your game is a system. once you create the system, e.g., a damage text system, you figure out how it or other systems communicate. this is usually done via events. each system can have their own events or send them to an event bus that sorts everything out . . .
i thought usage of events for interactions compared to calling methods by reference is only a tier higher but still not high enough to be considered a good practice
event bus sounds fun, cant wait to look into that
thanks
an event bus is the same as using events; it's just a dedicated class for handling them . . .
seems better than just events since i imagine it acts as centralised place where all of the events go which should slightly organize code flow and probably separates event part of classes concerns
would fix my current issue of "idk where exactly i should subscribe to" which is caused by unregulated usage of events
wouldn't you subscribe to the system handling the event?
for the event bus, each system subscribes their event to an event from the script; then everything will subscribe to the events from the event bus . . .
hey, i need help. I have a scoremanager in my project, to manage highscores. I want to store 2 highscores. Well, i have two almost identical scripts to manage the two highscores. They work nice, but in the "scoremanagereasy" script, the variable "scoreEasy" doesn't reset when you get to the menu or game scene. The thing is, in the "scoremanager" script, this works perfectly. What is happening??
Scoremanager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager scoreManager;
public int score = 0;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI highScore;
private void Start()
{
highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
score = 0;
if (scoreManager == null)
{
scoreManager = this;
DontDestroyOnLoad(this);
}
else
{
Destroy(this);
}
}
private void Update()
{
if (scoreText == null)
{
scoreText = GameObject.Find("Score").GetComponent<TextMeshProUGUI>();
scoreText.text = score + "";
}
}
public void RaiseScore(int s)
{
score += 1;
scoreText.text = score + "";
if (score > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", score);
}
}
}
ScoremanagerEasy script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class ScoreManagerEasy : MonoBehaviour
{
public static ScoreManagerEasy scoreManagerEasy;
public int scoreEasy = 0;
public TextMeshProUGUI scoreTextEasy;
public TextMeshProUGUI highScoreEasy;
private void Start()
{
highScoreEasy.text = PlayerPrefs.GetInt("HighScoreEasy", 0).ToString();
scoreEasy = 0;
if (scoreManagerEasy == null)
{
scoreManagerEasy = this;
DontDestroyOnLoad(this);
}
else
{
Destroy(this);
}
}
private void Update()
{
if (scoreTextEasy == null)
{
scoreTextEasy = GameObject.Find("ScoreEasy").GetComponent<TextMeshProUGUI>();
scoreTextEasy.text = scoreEasy + "";
}
}
public void RaiseScoreEasy(int s)
{
scoreEasy += 1;
scoreTextEasy.text = scoreEasy + "";
if (scoreEasy > PlayerPrefs.GetInt("HighScoreEasy", 0))
{
PlayerPrefs.SetInt("HighScoreEasy", scoreEasy);
}
}
}
neat
im dealing with self induced spaghetti where i used state pattern for the ui only while i shouldve made a big state machine for everything
also some systems delegate things to something else and idk how to make them interact between each other properly
also they're all statics with monobehaviour script glueing them together and passing object references
ive dug myself a hole its so over
why have two scripts that do the same thing??
at first i had the two in a same script, but with the things i want to do, i think its better to have two
definitely not
they do the same thing
you could just attach the same script to two different objects
no need to rewrite the code twice
For the things that are slightly different like the name of the object with the text and the name of the player pref - you can just have string fields you set in the inspector to differentiate
Anyway doing this in Start is a terrible idea:
scoreEasy = 0;```
i have two because i want to use two "update", and with two scripts i think i can use it
you don't need two updates
both of them do the same thing
yeah, i think if i erase that it doesn't matter i think
well the thing is you're doing that even before your singleton checking stuff
so when you reload the scene it's going to set to 0 no matter what
I think the only different you have here is which scenes have which objects in them
but yeah I don't see any good reason to duplicate all this code
i dont understand you very much, sorry
Your scripts are attached to objects in the scenes
that's how Unity works
There's basically no difference between your two scripts
the actual difference will only be in which scripts you have on objects in which scenes.
the object that stores that scripts has got the two scripts. Yeah, its a little bit nonsense but i understand it better like that
so in the scenes the scripts are the same
And I['m telling you there's more to it than that
you have the script on some other object(s) in at least one of the scenes
well, i have the object with the scripts with "don't destroy on load"
I'm aware
I can see the code
You're actually not using it correctly though
Aren't you getting errors for that?
nope
Are you looking at your console?
yeah
Yeah
don't ignore your errors
You're calling DontDestroyOnLoad and Destroy on the wrong things
those need to be called on the GameObject
I have a ClampedFloatParameter parameter and one Input Field. I want the value of this ClampedFloatParameter to be equal to what I wrote in the Input Field. How to do that?
but with "destroy(this);" is destroying the gameobject??
Use the OnValueChanged event in the input field to handle the value changing.
Idk how to do that
You need to do some conversion because inputfield gives u a string
float parsing is not working
oh opps i got sidetracked
as i understand, bus would be better since u couple callers to the system (it is safe to assume that it will always be there) instead of coupling to some objects event (which might be moved elsewhere), meaning you get better modularity with this approach and less headache when refactoring
but then again i havent used event bus yet so i might be saying nonsense
private void OnValueChanged(string aye)
{
if(float.TryParse(aye, out float value))
{
}
}```
You can probably use TextMeshPro to use Regex and only include numbers
ye, I know how to float parsing
and how to use onValueChanged on input fields
great!
You just said you didn't know π€
but ClampedFloatParameter not have parsing
its just a foat
to put in the param
clampedFloatParameter.value= value;
vignette intensity getting only clampedFloatParameter
I'm stupid π₯Ά
.value gives you the float
no lie
Did you check the docs for ClampedFloatParameter?
the thing is, i dont know why in one script works perfectly and in the other simply doesnt reset the score
as I mentioned, likely due to you having copies of the script in the scene you are loading
but, what do you mean??
What are you confused about? in the scene you're loading you have a copy of the script
your code does score = 0; in Start
before it destroys itself
So presumably if that's NOT happening, then the script doesn't exist in the scene you loaded.
but in the game running, the gameobject with the scripts doesn't really destroys i think
of course it doesn't
I already told you why
Remember back here? #archived-code-general message
float.TryParse(intensityField.text, out intensity.value);
A property or indexer may not be passed as an out or ref parameter
What he mean?
intensity.value is a property
you can't pass a property in as a ref param
You can do your own variable as an out, then somply assign that to intensity.value after
yeah, i tried to destroy and dontdestroyonload the gameobject, but i dont really know how to do it, note that i made this script like 2 years ago i dont really remember much
Maybe start over then
there's not much here
start over and understand everything as you write it.
if (float.TryParse(intensityField.text, out parsedIntensity))
{
intensity.value = parsedIntensity;
}
Tried this method. Float parsing is working, but parsed float not applying for intensity value
well, i will try to destroy the gameobject and see what happens. The thing that i dont understand is why in one script works but it doesnt in the other, but i take note of your help
the score = 0 part happens in Start
so like I said already
you likely don't have a copy of the script in the scene you're loading
if you're trying to change Post Processing Effects there is another way to do it iirc
say me pls
I'm very stupid β οΈ
but i dont understand why it cant be in start, i dont know if im explaining
well technically there are two ways to do it, one is very simple that involves less code and the other is changing it directly on the Volume's Profile
I didn't say it can't be in Start. Why put words in my mouth?
I said: "you likely don't have a copy of the script in the scene you're loading"
just changing intensity value of vignette shader of volume profile
for example if (volume.profile.TryGet<Vignette>(out value))
ok, so how i can have a copy of the script in the scene im loading and how that would help me?
Put it there.
It would run the Start code.
My code:
!code
π Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
π Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also its probably easier to just make an additional Volume that you fade in with Weight value
what do you mean as "put it there"??
I'm not sure how to explain it any more simply
drag/attach the script onto a GameObject in the scene
it's sending like fileπ₯Ά
yeah, i have the two scripts in a gameobject
Scripts need to be attached to a GameObject in the scene to do anything in Unity.
in which scene though
and which scene are you loading
did you actually read the bot message lol
it has instructions on Large Code
it's created in the main menu scene, and how it has the "dontdestroyonload", it keeps on all the scenes
Ok but if you don't have it again in the game scene then it's obviously not going to run Start again
so it's not going to do score = 0
So my guess is the WORKING one, you have a copy of it in the game scene
for the non working one, you do not.
that's all I've been saying this whole time.
Start only runs once for each instance of the script.
but the game object has got always the two scripts, i dont know if i am understanding you
show me
show screenshots
we're talking in hypotheticals
show the scene
with the object in it
etc
okey one moment
as I recall correctly, you can only modify the profile values as I shown above..
The easier way is just to create Another volume that only has the Intensified vignette value u want and then slowly blend that in with the Weight property of volume
This in the main menu
ok now
show the game scene
I bet you have a copy of one of those in the game scene
and not the other
this on the game scene (note that i have two game scenes, one for the normal mode (the script that works well) and this scene)
So during runtime, the object from the main menu is gonna persist into the game scene. Thus you would have two
Looks like you have missing references
and also probably more errors in your console
that references are the high score texts, i dont know if i should keep them in all the scenes
basically this
private void OnValueChanged(string valueInputField)
{
if (volume.profile.TryGet<Vignette>(out var value))
{
if (float.TryParse(valueInputField, out var parsedValue))
{
value.intensity.Override(parsedValue);
}
}
}```
then, this in the game over scene
and in the main menu after playing, this happens
Writing value in input field, but not changing
I added this line
are you sure the line is running ? put debug.log or breakpoint inside
Ye, working
instead, try debugging values of each function. see where the disconnect is happening
I'm gonna spin up unity again real quick, its been a while since I touched Profile values directly
Wait, so you're trying to change the TEXT? But is the value actually changing elsewhere?
Is it only the text not changing?
Because this is where I see you setting the text:
if (floatValue < 0.1)
{
intensityField.text = 0.1.ToString();
}
Is there anywhere else?
working for me
I am trying to change the Clamped Float Value that will receive the value from the Input Field
private void OnValueChanged(string valueInputField)
{
Debug.Log("Changing");
if (profile.TryGet<Vignette>(out var value))
{
Debug.Log("Changing1");
if (float.TryParse(valueInputField, out var parsedValue))
{
Debug.Log("Changing2");
value.intensity.Override(parsedValue);
}
}
}
All logs are displaying
value is not changing
Yeah, I was just about to say, I missed that second picture. I had it in reverse
script (also keep in mind intensity is 0-1 value)
https://hatebin.com/fitsgbdlcw
i am practising async methods
```public List<NavMeshSurface> navMesh = new List<NavMeshSurface>();
private void Start()
{
UpdateNavMeshAsync();
}
public async void UpdateNavMeshAsync()
{
await Task.Run(() => UpdateNavmesh());
Debug.Log("Made Mesh");
}
private void UpdateNavmesh()
{
if(navMesh.Count > 0)
{
foreach (var mesh in navMesh)
{
mesh.BuildNavMesh();
}
}
} ```
when i tried to run the code it game me this error: get_isPlaying can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene
after alot of trail and error i made these changes:
private void Awake()
{
UpdateNavMeshAsync();
}
public async void UpdateNavMeshAsync()
{
await UpdateNavmesh();
Debug.Log("Made Mesh");
}
private async Task UpdateNavmesh()
{
if(navMesh.Count > 0)
{
foreach (var mesh in navMesh)
{
mesh.BuildNavMesh();
}
}
await Task.Yield();
} ```
and now it works but can anyone tell me what i did wrong? i dont really understand it yet
anything Unity related can only be called on the Main thread
aka BuildNavMesh
fun fact: Unity has an async entry point for Awake
private async void Awake()
( i know void cringe, but it works)
why is void wrong the return?
typically async methods are Task
i mean i know its allowed but is there something wrong with it
many drawbacks from void async explained by microsoft themselves but some things cannot be helped
idk if you ever worked with WPF and such, you can only get their void async from UI events like click for example
Async void methods are difficult to test. Because of the differences in error handling and composing, it's difficult to write unit tests that call async void methods. The MSTest asynchronous testing support only works for async methods returning Task or Task<T>.
https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void
if you want an entry point to async
without needing TaskRun for example
like cs async void Awake() { await Task.Delay(1000); }
anyway your issue isn't related to that , just you using Unity API functions in another thread
unless they are specifically async
i think Update navmesh has a async version no?
im not sure
either way its unitys own version of AsyncOperation
not standard async
is there a difference in how they work?
well for this you would use a Coroutine so unity handles all that stuff
its a "YieldInstruction" like WaitForSeconds etc..
ill check the documents you sent maybe its better than what i have now
yeah look into the UpdateMeshDataAsync method I think is far less expensive then building navmesh each time
if i want to update it durring runtime would this still work?
for example i am using for enemypathing in a level that has moving objects
iirc it should, been a while since i've done runtime navmesh update
Okay, I see I came in at the wrong time
mb bro XD
im still new so i didnt rlly know the answer
thanks ill look into it
guys i need help quick
im inheriting from a parent class and im using virtual void A() and in the child im doing override void A() and then when i call parent.A(); its not calling the overrided one
what am i missing
what is parent.A() supposed to be? base.A()?
is the base class im inheriting from
i have a reference to the base class and call the function A()
shoudlnt it call the overrided one in the child class
If you override without calling base() inside the override, the base implementation is gone
oh like this a() : base()
Thatβs a constructor
like this base.a()
i did that but it still doesnt work
Maybe show the code
how do you know its not executing right?
becasue i put the debug log
in both
and its only running the one in the base class
both scripts are on my gameobject
and you are sure you've put the SoldierAttack on the gameobject?
yeh
i mean, you've probably made an incorrect assumption somewhere about what you did
maybe doublecheck
maybe you're calling it on the wrong object, or put the base class where the derived class is supposed to be... idk
something like that
it doesnt seem like there is many areas to fail here
true
dont they both have to be on there
no
soldier implements all of unit and all the extra stuff + overrides
if you have soldier + unit components, you have 2x unit and 1x soldier, effectively
but if i reference unitattack and its not on the object i wont be able to get it
right
you can reference "soldier" by its base type "unit"
if you GetComponent<UnitAttack>() but only have a SoldierAttack on there, you'll get the SoldierAttack instance, but in the form (type) of UnitAttack, you can then cast it to (SoldierAttack) if you like or just use as is, since you dont care that it is a a Soldier for running the Attack()
I don't Wana have to cast it though
in that scenario, with your Soldier GameObject from the screenshot, you are probably getting the UnitAttack, and not the SoldierAttack.
I know it's getting the unit attack but I thought the function would be overrided
seems you still don't understand
if you override a class, it is still the base class, but ALSO the overridden class
I Wana call unitattack.attack and if I have soldier attack archer attack cavalry attack etc
I Wana call uniteattack.attack and it calls the right one
Which ever one is on the gameobject
They all inherit from the base
and you want archer, soldier, cavalry all on the same object?
well, then, remove the "UnitAttack" from them and proceed, problem solved
You would be surprised by what is "obvious" to some people we help
If I call get the component of the unit attack will it put the child ones instead of it's not attached
no
Parent classes know absolutely nothing about their children. It will only expose what is in the type you declare
This example here is a good case for composition over inheritance. Consider having just different attack components that you add, and a single general unit class that has all the commonalities
Not necessary, but it's an idea
So how can I call each of their attacks
I think I may have misunderstood your question
if you getcomponent UnitAttack it will return the first one of that class or inherited from that class
So it will add the solder attack script? If that is the one on the gameobject
yes if SoldierAttack inherits from UnitAttack
Ah ok that's good
You're better off asking this in a Blender forum
It's neither a Unity question nor a code question
hi, is there any way to diagnose why domain reloading is taking upwards of 3-4 minutes at a time
my project is quite large, there are not a lot of assemblies because everything is unfortunately very coupled together, but this wasnt a problem until recently
its killing my productivity so any help with diagnosing the issue would be greatly appreciated
wild chance you can try to refresh library folder
close the project, delete library folder, let it rebuild
oh and a blank scene will be open after process, until you open your scene again
this sometimes rids of any weird hanging issues for me
I have an interesting case, I need to make a visual lead so the player knows where to shoot at a plane
A pretty common problem. https://officialtwelve.blogspot.com/2015/08/projectile-interception.html
The math is basically the same
shouldn't be too hard to adapt it to 3D
I see, let me try
I'm having a problem with the lead jittering around
here's my code
Every frame has different delta time, so your velocity valie is gonna be different as well.
Instead of trying to find the velocity, normalize the direction and multiply it by some constant value.
what would that look like in code?
leadPos = pos + dir * leadDistance
Yes
Could someone please advise how youβd convert a csv/xls file into a dictionary? In this case itβs just 2 columns, so string in column 1 row A should be key, string in column 2 row A is value, and so on.
i have pathfinding for enemies in a 2d platformer game, how can i stop enemies from getting inside each other?
i'd normally add force when enemies get too close to each other or just have collisions between them
but doing those messes up my pathfinding
i cant find any examples that do this because i dont know many 2d platformer games that have pathfinding
of course, maybe i could try to make enemies not cross paths by changing the pathfinding algorithm but that would be very hard to implement + would make the thing even more resource intensive
In my package cache, it gives off script errors for my packages, how do I get rid of it?
If you're seeing errors from package code and you haven't manually installed specific package versions (which would let you install a version that's incompatible with your version of unity), it's probably the Mysterious Package Cache Corruption
What do you mean by manually installing?
Oh, haven't done it that way
I mention this because I saw someone a few days ago who had installed a newer version of the AI Navigation package than their version of unity supported
It's a Unity Registry package
so it wound up causing compile errors
this allows you to install different versions of packages from theu nity registry
What package is producing the error? Can you show your console?
Oh
Yeah, one second
TextMeshPro
show me the errors it's producing
click on an error so that the full text appears in the bottom half of the console
and then show the entire error (or just copy that text into here)
also, what version of unity?
and always look at the first error, not the last
any chance you've copied TextMeshPro code into your project?
moving code from the package into the Assets folder, for example
no, but i've tried fixing some of the code
so i've modified some of the package's code
You can't edit code that's in the Library. It will get overwritten by Unity.
oh
close unity, delete the entire com.unity.textmeshpro@3.0.8 folder from Library/PackageCache, and then reopen the project
Alright, give me one moment to do so
If the issue persists, follow the instructions for "Reacquiring corrupted packages" here https://unity.huh.how/package-manager/package-errors#reacquiring-corrupted-packages
would i delete folders for packages with scripts errors as well?
like other packages?
if you have a huge pile of errors from many packages, I guess I'd just delete the entire Library folder and let Unity reimport everything
this will take some time
it will also make unity forget which scene you had open, so you'll get an empty scene when it finishes reimporting
thanks a lot for the support
What's the best way to change the speed of an audiosource before playing it? I'm trying to find answers online but nothing really seems to suit what I'm looking for.
it still has errors when i tried that as well
check the instructions in the page I linked, then -- it describes how to completely get rid of cached packages so that unity has to redownload them
set its pitch
yea tru i just found that out. odd that it sets speed and pitch when only labelling it as one
changing the speed that you play a sound at changes its pitch
if you halve the playback rate, a sound that used to be 1000Hz is now 500Hz
changing speed and pitch independently requires more complicated processing (and tends to produce noticeable artifacting)
whats up with this error and how do i fix it? working with netcode with gameobjects using the facepunch transport, looking it up brings me to a thread discussing this as a bug... from 2 years ago... it has to been fixed by now right?
( i am using Unity 2022.3.23f1 )
wait nvm i got it, turns out the default network prefab list has been autopopulating with the correct prefabs, while i diddnt bother checking it
does anyone know if its a better idea to have a pool of audio sources and translate them to a (enemy) transform when needed? or to have them always on an enemy? ( keep in mind up to 500 enemies can be on screen at any given moment)
also anyone know of good places to get good looping sounds? (sounds that sound great when looping )
If the total number doesn't change, it doesn't really matter that much.
The point of a pool is to avoid overhead of instantiating and destroying new objects in the expense of some constantly allocated memory.
If the only thing different between the sounds is their position and the audio clip, then maybe it's better to have just one audio source and use the play one shot method.
so that answers most of my questions. but just to be clear. If i'm pooling hundreds of enemies, should just just give them each an audio source? ( my main concern is massive enemy groups containing to much "data" while translocation ? idk
but the one shot audio source is what i'm currently doing, (not working well) since 20 sounds playing at the same time at any given time is probably the most 'ill need but also the least i'll need
Not sure what you mean by "translocation", but generally it shouldn't matter much where these audio sources are in the scene. The one shot would help reduce the memory footprint, though probably not by a lot. Just whatever memory an audio source object occupies * 499.
Realistically speaking though, I'm not sure if a human can discern 500(or even 20) sounds playing at the same time. It's probably gonna turn into indiscernible noise.
i mean just translating a transform. while hundreds of enemyes are hunting the player down, i want to create audio sources that overlap sounds, no clipping. during a bullet hell
Audio source doesn't care about the transform component afaik, so that shouldn't be a problem. At least it shouldn't care when it's not playing.
Anyways, you should probably be confirming all that by testing and profiling
Hey, dealing with a pretty large state issue in a jam project I'm working on. Figure I could ask here and see if people have any ideas. Mostly for like, a design pattern or structure for handling this situation.
Essentially, I have a bunch of one use powerups in my game. They modify the players behaviours and controls pretty aggressively. My initial design was sorta just stacking everything in one file, and having booleans for tracking state.
That got hectic, so i broke it in components and tried to sorta spread behaviours out, and that has worked in a coding sense, but has made my animation life pretty hellish.
Basically, how do you guys handle complicated characters / objects that can have behaviours added and removed, especially if some behaviours modify previous ones.
Like for example, my regular player jumps and falls. But lets say I have a powerup that allows for a fast fall. I then have two, or three options:
Modify the original fall code to enable this behaviour with some state variable internally to manage (gets bad if I have too many things that modify this behaviour)
Disable / Enable original code once new code runs / stops running (Gets bad if I have like 30 potential scripts that have to manage eachother)
Have multiple characters and scripts for each character set that I replace the current with whenever a new powerup is gained (Currently thinking about trying this)
Maybe more options?
Regardless, just hoping for a nudge, or just some outside thought rather than my own for how to tackle this
I keep trying to sorta look into games like TBOI for how they modify their player, but lots of google just leads me to powerup classes with actions that like change a float, which is a pretty useless example for any more complex task
so something weird is happening, when i add the audioSource to an enemy, it's not working? if the audio source is moving and playing at the same time, is that an issue?
the clip is added to the gameobject. i'm calling audioSource.Play(); and nothing is woprking?
No
You'd need to share more details.
here is the code ```public void Damage(float amount)
{
float damage = enemyManager.bulletManager.CalcDamage(amount + Random.Range(-amount / 4f, amount / 4f));
bool isCrit = damage > amount * 1.5;
enemyManager.statisticManager.totalDamage += damage;
enemyManager.HandleHitText(transform.position, damage, isCrit);
audioSource.Play(); <=============================================== playing sound
if (isImmune) return;
health -= amount;
if (health <= 0f)
{
enemyManager.statisticManager.kills++;
enemyManager.Kill(this);
}
BlinkHitRoutine();
}```
here is a screenshot of enemy Prefab
Up
this is all i need to play the clip correct?
Yeah. Is the clip assigned at the time when you call Play?
yes
I'd add some debug to see if it's being called and when
during runtime, the prefab is exactly how it looks in the screen shot
i did Debug.Log(audioSource.isPlaying); comes up true
so i tried the same thing on the player, working perfectly fine.. must have something to do with instatiating enemies disabled?
How often?
Make sure you don't run play every frame on the same component. That would reset the play time and never pactually play anything
i think i know the issue... maybe the enemy is dying before the clip has any time to play?
yeah foudn the issue, clip isn't playing becuase it's being disabled to soon.
@cosmic rain since i am disabling units istead of destroying them i need to translate it to location enable it, and play sound, then disable it after clip finishes
Thank you very much! You helped me a lot!
does anyone know how i can prevent a bullet from hitting 2 enemies? i want the bullet to stop checking once it finds a target and only do things to that specific target
hasHit = true;
that doesn't work because the fixed update can somtimes hit two colliders in the same frame
this is my code and it doesn't work ( meaning it hits two or more objects before destroying
{
collider2D.enabled = false;
if (other.gameObject.GetComponent<Enemy>())
{
other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
// FindObjectOfType<SoundManager>().PlaySound(0);
Destroy(gameObject);
}
}```
I keep hearing that there are duplicate messages with trigger/collision methods, but I thought a lot of this is single-threaded
This because actual destruction happens at the end of the frame. You can still do what Mao suggested.
Ah, right Destroy isn't a good indication
https://unity.huh.how/physics-messages
There's this too
so...
hasHit = false
then
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.GetComponent<Enemy>())
{
hasHit = true; <--------------- ????? works?
other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
// FindObjectOfType<SoundManager>().PlaySound(0);
Destroy(gameObject);
}
}```
well, the bool itself isn't going to do anything
so what did you mean by this?
ya need a statement to back up the bool
oh right lol
if(hasHit) return;
so...
hasHit = false
like this!?
private void OnCollisionEnter2D(Collision2D other)
{
if(hasHit) return;
if (other.gameObject.GetComponent<Enemy>())
{
hasHit = true; <--------------- ????? works?
other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
// FindObjectOfType<SoundManager>().PlaySound(0);
Destroy(gameObject);
}
}```
btw...
if (other.gameObject.TryGetComponent(out Enemy enemy))
{
// use enemy
}
Instead of GetComponent twice
Hello guys, I am trying to live stream my YouTube channel in my game in editor I have a quad mesh with an unlit texture on it and it is attached to the Video player component but every time I put the URL of my YouTube live stream Unity is having problems with it. I checked the assets for that available but they are quite expensive. Is there any other way^^.?
Is there a way too know if 2 material properties have thesame values?
If they are sharedmaterials you can probably just compare references
otherwise
https://docs.unity3d.com/ScriptReference/Material.html
Use the Get method types and compare values
Hey guys. I'm working on an interaction system for my game, and started using interfaces for the first time. I think I got the main idea on how to use them, but I have a little bit of a problem when it comes to the input I expect before calling the Interact() function on my interactables.
I would like to make it so that some interactables can only be interacted with if the player is standing next to them and pressing a key, others if the player clicks on them, others if the player just presses a key no matter where they are in the world, etc. Basically each interactable would expect a different kind of input. I'm a bit confused on how I should implement that though and thought maybe I could get some help. π
Hello, I've recently updated my 2020 project to unity 2023, and RigidBody2D.Cast stopped working. Is there something obvious that I am missing?
RigidBody2D rb = GetComponent<RigidBody2D>();
filter = new ContactFilter2D();
filter.useTriggers = true;
filter.useLayerMask = true;
filter.layerMask = 128;
List<RaycastHit2D> rays = new List<RaycastHit2D>();
int cc = rb.Cast(Vector2.zero, filter, rays);
print(cc); //cc is 0, even though there is a collider inside```
It used to work just fine in Unity 2020.3
This is a simplified version of the code
How are you obtaining the information for what gameobject you are near? OnTriggerStay, ect
Using Vector2.Distance (the game is 2D). The way I have it set up how is a bit weird though, I think. Instead of having the player character check for objects around it, the interactables that need the player to be next to them check for the player - since there's only one instance of it.
Weird indeed
Hmm, in that case I feel like the interface is less useful as it's the object itself checking for the player?
What you can do is throw a scriptable object onto each type of item and give it a keycode
and check the current input against that item's keycode
Hmm... The reason I want to start using an interface for all interactables is to better structre my code. I think having a bunch of scriptable objects for the keycodes would just add more complexity than needed.
Well, you need specific instances somehow
some sort of identifier for each item you instantiate
The item checking if the player is nearby and the mouse input is already some chaos. If you want a nice structure, this code should all be with the player and they should check what interactables are near. Then you call some public function on the interactable object
For interactables which can be interacted via the player standing near, you could just use OnTriggerEnter & OnTriggerExit, the same thing could be easily applied for mouse click, just make a collider follow your mouse in the world. For key press just.. go through each key-press interactable and check if the key assigned to them was pressed
An InteractionManager script would be useful here
Alright, thanks for the ideas guys! I'll give it a try.
I know this is a specific question but is there a method to capture the state of all relevant game objects (enemies, important objects...)
Capture?
Store
At runtime?
Yes
Implement a serialization strategy for the relevant objects, then serialize them when you want to store their state.
Unity has no built in functionality for run time saving so you will need to build your own or use a 3rd party solution
You could make a script purely for the serialization of one game object, then make it register to a master serialization script that triggers the functionality when needed
Thanks guys. i will try to implement it
When does unity trigger inputAction.cancelled event (new input system)?
I have a custom on-screen joystick, and I want it to be THE ONLY source which sends value to my "Move" action (the move action only has 1 binding: GamePad Left Stick, the custom joystick sends value to the binding).
But during drag Unity itself sends 0,0 to the control and triggers a cancelled event.
How to avoid that?
What would be the right place to ask about bugs in the localization system?
I'm using Localization 1.4.4 on Unity 2021.3.25f and setting LocalizationSettings.SelectedLocale on console goes into infinite loop
stop crossposting everywhere. you can use id:browse to find the most relevant channel
There is no localization channel
i never said "look for the channel specifically for localization" i said "the most relevant channel". so if your issue is a code related issue, then here is fine. otherwise ask in the most relevant channel to your issue
It is code-related, but it's related to something Unity wisely decides not to support directly on here
alright well i'm not even going to bother attempting to help you at this point even if you do decide to provide any details about your issue
If you've encountered a bug, you should report it. !bug
πͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
π If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click βReport a problem on this pageβ!
π‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
@vagrant blade I'm afraid I can't wait for a bug fix or be told to update my Unity version to something that my project will 100% certainly not survive an upgrade to
Okay, good luck!
I need a workaround as quickly as possible, since we are stuck in cert thanks to this problem
I guess Twitter is it, then
Can't really help you if you don't share any details.
@cosmic rain What details do you need?
All I know is that running the game without setting LocalizationSettings.SelectedLocale works fine
Another developer found that settings LocalizationSettings.SelectedLocale caused AsyncOperationHandles to get created and released in an infinite loop
For example breaking with the debugger during the issue and taking a screenshot of the main thread callstack
Working on that, but game won't launch with a debugger attached π₯²
That doesn't make sense. Also, you can attach it after launching it.
I've made a build that pops the "You can attach a debugger now" window, attached and then run, and the process starts but no window appears and the process sits in taskman with ~150MB of memory usage and ~3% CPU usage forever
Going to have to solve that first, it seems
Build it normally and attach the debugger when it's already running
That kinda sounds like you didn't attach to it and it's still waiting for the debugger
On advice from a developer on the localization package I updated the localization package, which seems to have wrecked the game and builds. Builds don't work any longer regardless of whether I allow or attempt debugging
So I'm gonna need to revert the loc package, rebuild a bunch of stuff and try againβ’οΈ
So i have a json object
{
"name": "Hi",
"data1": "Hello World!",
"data2": "etc"
}
And i'm trying to deserialize it into a class pretty much identical to this one but with a lot more stuff that's irrelevant
public class MyClass
{
public string Name { get; private set; } = "Name";
public Dictionary<string, string> Strings { get; private set; } = new Dictionary<string, string>();
public MyClass(Dictionary<string, string> strings)
{
if(strings.TryGetValue("name", out string name)) Name = name;
}
}
How do i do that exactly with Newtonsoft.Json?
This is kinda hard to google
Don't know how to phrase it without it sounding like something else
@cosmic rain Got it running again, with great success:
Going to do some manual breakpointing and see if that helps
What exactly did you do to get that error?
Attached debugger to windows build, waited for the point where the game freezes, then pressed break in the Visual Studio debugger
It didn't want to do that
Doing a new build with a breakpoint instead to see if that changes anything
Was the previous build built on your machine?
Either use a custom jsonconverter or JObject
https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
Also, how did you attach the debugger?
Everything I've been testing here is built locally
Using Debug > Attach Unity Debugger
Then picking the process
The attachment works fine, but breaking doesn't
- It could be the wrong process.
- It's sometimes better to use the attach to process option instead of the unity one.
you can use JsonExtensionData although i think you'd have to modify your class slightly, the extension dict has use values of type object or JToken because you can't make it validate what gets deserialized at that point so it can contain anything
like this:
public class MyClass {
public string Name;
[JsonExtensionData]
public Dictionary<string, object> Data;
}
Definitely not the wrong process, but I'll try not using the Unity option
@cosmic rain Hooray, attaching without using the Unity helper did the trick!
Let's see what we have here ...
@cosmic rain Ok, I doubt this is particularly helpful for you buuuuuut ...
... this is where it halts. Trying to get the call stack, but being a somewhat inveterate debugger, I'm Still Looking
Not really helpful. Looks like decompiled code..?
the callstack window can be added from debug - windows
Yeah, it's IL
@cosmic rain Here we go
More friendly dump: https://hastebin.com/share/ogoyizecun.scss
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Kinda hard to interpret that. Can you take a screenshot instead? Preferably of the whole IDE window.
@cosmic rain You might want to specify what's interesting to you here:
There's a lot of IDE window going on
That's good enough. I wanter to confirm that it's the main thread.
This seems relevant:
You should probably be looking at the last call in the GameAssembly
Yeah, it's the main thread.
You should look in here first
As well as in the last call before ntdll(assuming it shows anything)
Just to underscore
Nope, no symbols π₯²
Disassembly is a bit raw for me π
underscore?
As in, provide evidence that yup this is main thread
when i place objects on the ground for some reason they get placed a little bit into the air, and that distance is very inconsistent and is sometimes affected by how far away from the place position i stand
pos is the raycasthit.point position
if i don't do the bounds/2 calculation they always get placed perfectly halfway into the ground
it just seems like the bounds size is really inconsistent for some reason
Show the inspector for one of the objects
big cube
Ok, the center is 0,0,0 so that is good. Wanted to check that
Scale is also 1,1,1 which is good
also, the further away i am from the hit pos im standing, the closer to the surface it gets placed
I see you are setting LOCAL position. Are these children of something? Have you tried just using position?
they were a child of player. when i activate the Place() function, i first set their parent to null before changing its values
Ohhh, the scale IS being changed then
I guess I should have guessed considering the image π€¦ββοΈ
Well, I would do what mao said
yes, when i grab the object first it gets a new scale for being held. but i save the scale it had before being picked up. when i place it i give it its original scale again
i really couldnt find any pattern
Did you try using position?
yes, same thing
im honestly a bit confused, look at this
it gets parented to this
which does have a weird scale
but i feel like that shouldnt matter since i set its scale when i place the object, and after that do the bounds calculation?
debug says the object has a varying bounds size, differing from the one in its inspector
I'm not sure when bounds gets calculated
It's possible that it only updates later on
try whacking it with a Physics.SyncTransforms();
It doesn't look like Collider offers a localBounds property (like Renderer does), which would allow you to do transform.TransformVector(something.localBounds);
(that would actually be different from the world-space bounds, though, so i guess it's not helpful anyway)
since it wouldn't be axis-aligned
would i do this right before doing the calculation with the bounds?
Right.
I dunno how the bounds property actually works (it just calls some native code)
but I could believe that it asks the physics system for its current understanding of the collider's bounds
I've seen similar issues where people try to use a physics query immediately after setting something's position
I tried SyncTransforms, no change
Here's what bounds.size.y is different times when i place it
note that the bounds size will depend on the rotation of the object
oh, that's definitely it
you're resetting the rotation after you use the bounds
Collider.bounds is axis-aligned. A rotated box will wind up with a larger bounds.
oh my god thank you!!! you're right!!!