#archived-code-general

1 messages Β· Page 304 of 1

lone narwhal
#

ok thank you

unreal temple
#

You can get the collider that is involved from the Collision event

swift delta
#

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

merry stream
#

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

swift delta
#

wouldn't I still need to access the projectile's class with GetComponent?

merry stream
swift delta
#

oh I think I get it

merry stream
#

you dont need to hold a prefab as a GameObject

leaden ice
#

oh sorry Umbra got you sorted

leaden ice
#

and have that script interact with the Rigidbody, which you can directly reference since it's in the same prefab.

swift delta
#

then I can just thrust the projectile forward on their own Start(), right?

#

or am I missing the point

merry stream
#

just set the rigidbodies velocity to some vector and it will move in that direction with whatever magnitude

swift delta
#

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

merry stream
#

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

swift delta
#

the direction isn't a problem, that's been sorted

upper pilot
#

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?

merry stream
#

then just set the rigidbodies velocity

#

and it will move

swift delta
#

I am doing that

merry stream
#

whats the issue then?

swift delta
#

the one and only problem is accessing the rigidbody

merry stream
#

i already told you how

swift delta
#

well, doing so in a less dumb way

merry stream
#

just hold the reference as a rigidbody

#

or if you have a projectile class, use that

swift delta
merry stream
#

and hold a reference to the rigidbody in that class

swift delta
#

yeah I'll do the second approach

cyan hornet
#

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?

merry stream
#

ctrl r r

lean sail
upper pilot
# lean sail you can use properties, its not like theres really a correlation between it and ...
[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.

swift delta
#

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

upper pilot
#

Maybe I am going against the whole idea of separating save data from the object.

merry stream
#

are you currently holding the reference to the projectile prefab as a gameobject?

swift delta
#

it is, yes

merry stream
#

you can instead use any component also on that prefab

#

so Projectile, Rigidbody, etc

swift delta
#

right, but then how would I instance it?

lean sail
merry stream
#

the same way

upper pilot
#

Mostly unsure how Json will save the data, should the save data only store data, or should I have some functions in there?

swift delta
#

I was under the impression unity could only instance gameObjects

merry stream
#

doesnt change anything

cyan hornet
merry stream
#

that reference still holds your whole prefab

#

which is a gameobject

#

it just is under the type Projectile

swift delta
#

so I can change the type to Projectile, reference that from the prefab, and the instance will be acquired just fine?

merry stream
#

yes

swift delta
#

so what, do I just instance, say, bullet.gameObject?

merry stream
#

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

swift delta
#

could've sworn rider was throwing an error my way trying that, one second

merry stream
#

maybe because you are still doing GameObject x = Instantiate

swift delta
#

that is correct

#

pretty silly thing not to notice

#

alright, thanks a million for the help

merry stream
#

np

rocky dust
#
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

spring creek
rocky dust
#

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

spring creek
#

Seems like you have the logic for vert wall and hor wall reversed

rocky dust
#

yeah that was the problem but im not sure why?

#

i might just be stupid lol

spring creek
rocky dust
#

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

spring creek
rocky dust
#

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

spring creek
#

Sounds good to me hahaha.
And I will

rocky dust
#

tysm for the help :D

upper pilot
#

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?

mossy snow
#

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

upper pilot
#

I agree, there will be more similar cases so having it in SaveGameData might be a better idea.

leaden ice
upper pilot
leaden ice
#

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

upper pilot
#
        if (!partyDict.TryGetValue(index, out partyData))
        {
            SaveManager.Instance.SaveGameData.PartyData[index] = new PartyData();
        }
        PartyData = partyData;

If(doesnt exist) new PartyData();
else out partyData

#

huh

leaden ice
#

partyData never gets the new object reference here^

upper pilot
#

doesnt out return partyData?

leaden ice
#

it assigns it

#

but to null if it doesn't exist

#

it won't get your new PartyData();

upper pilot
#

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;
    }
}
radiant elm
#

it happens on pretty much every texture/material as well

upper pilot
#

No expert here, but I'd check camera settings

#

Clipping

#
Forcing Anisotropic Textures in the Quality tab under Project Settings fixed it, thank you! 
radiant elm
#

its already on forced on settings i should have mentioned

upper pilot
#

They also mention mip map settings

radiant elm
#

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

upper pilot
#

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

latent latch
#

kinda but you need newton soft

#

Unity's json utility will only serialize what you can usually serialize with the editor'

upper pilot
#

yeah we went there before, but I was convinced to use JsonUtility.
Guess I might just use Newton soft and try it again.

latent latch
#

you can pretty much serialize key value pairs as structs then construct the dictionary in awake if you wanted

upper pilot
#

as structs?

#

oh

#

like having a list of List<structData> and structData stores key/value

latent latch
#

yeah, that's how you'd normally do it

upper pilot
#

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

latent latch
#

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

upper pilot
#

Yeah I do want a dictionary, but newton soft works good so far so I might stick with it.

latent latch
#

yeah it's good. No reason to not use it

craggy veldt
spring creek
dusk rain
spring creek
#

I mean, googling is good too πŸ€·β€β™‚οΈ

dusk rain
#

Yea i've been trying that, this was my last resort

spring creek
jagged snow
#

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

leaden ice
#

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
      {
      }
  }```
jagged snow
#
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 ()

leaden ice
#

that's not related to this code

jagged snow
#

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

leaden ice
#

and you should

jagged snow
#
            {
                pickupable.Destroy();
            }```
The destroy line
#

ok ill do that

leaden ice
jagged snow
#
    {

        OnDestroy?.Invoke();
        Destroy(gameObject);
    }```
leaden ice
#

check my example

jagged snow
#

ahh right

leaden ice
#

see how I did the if (uobj != null) part?

#

but yeah you really should just remove it from the list when you destroy it

jagged snow
#

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?

latent latch
#

your ide will yell at you dont worry

leaden ice
#

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

jagged snow
#

right so in this case, after X seconds it will destroy theobject but if the player picks it up

#

it wil destroy

leaden ice
#

if there is no yield in the loop, there is 0 chance

jagged snow
#

ahhh

#

ok good

swift falcon
#

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)

wheat spade
#

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.

cosmic rain
#

Maybe some kind of context object that keeps track of what's of different assets created so far.

jagged snow
#

What does the 'is' do exactly? Is it force declaring pickupable as the object?

wheat spade
ocean hollow
leaden ice
leaden ice
#

it's a type check and a cast

ocean hollow
jagged snow
#

so can I use this to check if lets say if its another interface? Kind of like trygetcomponent?

leaden ice
leaden ice
#

GetComponent grabs a component of a specific type from a GameObject

ocean hollow
#

It's always worked for me even though I've been using it wrong πŸ˜… what a world

leaden ice
#

this checks the type of the object you have a reference to

dull glade
#

for some reason this doesn't work:
GetComponent<MeshRenderer>().materials[0] = Materials[arrayIndex];

leaden ice
leaden ice
#

you need to assign the whole array at once

#
Material[] mats = myRenderer.materials;
mats[0] = whatever;
myRenderer.materials = mats;``` @dull glade
cosmic rain
#

Look up context design pattern

upper pilot
craggy veldt
#

proly bcos most examples for spans are for char arrays πŸ˜„

latent latch
#

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

fleet gorge
#

Physics calculations can't afford to vary their dt too much

#

Compare the values of Time.deltaTime in Update(), and Time.fixedDeltaTime in FixedUpdate

latent latch
#

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

fleet gorge
#

It is indeed by fixed time

latent latch
#

lerp on the other hand for like visuals you do in update

fleet gorge
#
// 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

lean sail
#

You most definitely dont need to use fixed update

latent latch
#

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

lean sail
fleet gorge
#

why do you need 1000 intervals

latent latch
#

that's just a extreme sample

lean sail
#

It's a hypothetical..

fleet gorge
#

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

latent latch
#

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

fleet gorge
#

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

lean sail
#

then plus whatever extra logic to stop this at either 1000 intervals or 5 seconds

#

also typed on discord so might be a typo

latent latch
#

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

lean sail
#

i believe i wrote a similar code lately for my DOT system

latent latch
#

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

lean sail
#

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

latent latch
#

wouldnt be hard to do some catchup and check how many intervals happened and apply it all at the end of the duration

lean sail
#

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

latent latch
#

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

lean sail
#

i believe fixed update has a limit to its catchup

latent latch
#

beyond like network catchup issues

fleet gorge
#

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

latent latch
#

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

lean sail
#

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

fleet gorge
#

e.g. if the DT is 0.0124,
it gets executed thrice for 0.005, 0.005, and 0.0024

lean sail
fleet gorge
#

but it's still gonna move the same dist

#

you need to accumulate the overflow

lean sail
#

if we were, id include the timer as part of it

fleet gorge
#

or whatever happens in the code

#

yea

lean sail
#

we are just talking about running something exactly 1000 times in a 5 second interval

lean sail
# latent latch wouldnt be hard to do some catchup and check how many intervals happened and app...

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

latent latch
#

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

wheat spade
nocturne wyvern
#

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

prime sinew
sleek bough
subtle idol
#

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?

dull glade
#

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

wise arch
#

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?

thick terrace
knotty sun
wise arch
knotty sun
#

so check for null instead of isPlaying

wise arch
#

Then I won't have errors if it is null in runtime

knotty sun
#

you will if you want to have them

thick terrace
#

a serialization callback is probably not the right place to do that validation

wise arch
wise arch
# knotty sun 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)

thick terrace
# wise arch Where would be a good spot?

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?

wise arch
#

Otherwise, your other idea will work although I am not a fan of it

grizzled urchin
#

is it normal that when saving the script in visal studio Unit lags like a few second to update the code?

knotty sun
wise arch
# thick terrace maybe in an OnValidate method?

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

wise arch
thick terrace
wise arch
#

Yeah I'll figure out a workaroudn of some sorts

#

thank you both for looking into it @knotty sun @thick terrace ❀️

wise arch
#

Working with OnGUI and this is what I get on screen:

#

That should be a readable string. Any idea what the cause might be?

vapid condor
#

dont use ImGUI, especially for runtime UI

#

that thing is old and deprecated

marsh mesa
#

Whats the difference between Start() and Awake()?

wise arch
vapid condor
marsh mesa
#

Thanks

waxen blade
#

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.

See https://forum.unity.com/threads/stopallcoroutines-should-clarify-that-it-only-works-after-using-startcoroutine.1267616/

Is there a workaround to this?

marsh mesa
#

i thought there'd be more to it

waxen blade
#

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.

wise arch
#

If it doesn't stop the one started from yield, it sounds like you'll have to store and stop them yourself

dull glade
#

why do I get this error

latent latch
#

merge conflicts open the text editor and fix them

leaden ice
#

Yeah I would say your file has merge conflicts in it.

swift falcon
#

@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.ValueType or System.Enum types 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 about Enum.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 your Equals() method in your struct as your needs next time and enjoy your development ❀️

thick terrace
chilly surge
#

I guess record is good enough if you aren't allocating tons of them, and Unity supports record.

swift falcon
leaden ice
chilly surge
craggy veldt
craggy veldt
hexed pecan
# marsh mesa Thanks

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.

hard viper
#

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

thick terrace
craggy veldt
thick terrace
#

right, but the compiler knows calling a readonly method won't do that, doesn't it?

craggy veldt
#

the compiler does not now in this specific case, it just assumes as part of their safety mechanism thus defensive copy

thick terrace
#

which specific case do you mean?

hasty prairie
#

hii, is there like a help section in this server?

#

like a uhh "how can i achieve this effect"

chilly surge
#

Isn't the entire record struct marked as readonly so defensive copy isn't a concern?

chilly surge
#

And doesn't defensive copy only kick in if you are passing with ref?

craggy veldt
thick terrace
chilly surge
#

Ah, is that not the default?

thick terrace
#

nope, you can make mutable records

chilly surge
#

Makes sense. In my head mutable records kind of defeats the purpose so it doesn't cross my mind.

craggy veldt
# thick terrace which specific case do you mean?

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()

devout silo
#

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

leaden ice
swift falcon
craggy veldt
#

you can check there too

thick terrace
craggy veldt
swift falcon
#

It says this. So editing a field in the readonly struct directly would not trigger the behaviour it right? Complicated a little ._.

craggy veldt
#

exxactly that πŸ‘†

#

takes a minute to test it on Sharplab, really 😌

chilly surge
#

So it's not an issue if you mark the struct as readonly then.

craggy veldt
#

it might still

chilly surge
#

How so?

thick terrace
#

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

proven robin
#
        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
somber nacelle
#

are you perhaps disabling the gameobject or stopping the coroutine somewhere?

craggy veldt
leaden ice
proven robin
#

no the gameobject is still active and has the script

leaden ice
#

doubt

craggy veldt
thick terrace
proven robin
somber nacelle
#

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

proven robin
#

yea i know but it dosnt get disabled as of what i have seen but i will try to log OnDisable

somber nacelle
#

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

proven robin
#

no it dosnt get disabled

    private void OnDisable()
    {
        print("Disable");
    }```
somber nacelle
thick terrace
craggy veldt
thick terrace
#

It means that you should never pass a non-readonly struct as in parameter.
yes, that's what i'm saying too

proven robin
somber nacelle
#

yes because that is the object that owns the instance of the coroutine

chilly surge
#

Yeah, so if a struct is readonly then it shouldn't have defensive copy issues.

proven robin
#

alright then that the issue

thick terrace
leaden ice
craggy veldt
ocean heath
#

Hello guys!
In the built-in pipeline is there any way to directly access the shadowmap of a directional light source?

gray mural
# waxen blade I am attempting to stop all coroutines on a script from the outside, by using th...

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);
            }
        }
    }
}
somber nacelle
gray mural
#

They have asked how to stop the coroutines from the another class

somber nacelle
#

right. and did you generate that code to share with them or did you write it yourself?

gray mural
#

This is not AI-generted. I wrote it myself.

#

I assume, AI would have given a totally different answer

somber nacelle
#

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

gray mural
#

I even wrote MonoBehavior.StopAllCoroutines there

spring creek
faint crag
#

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

thick terrace
#

so basically learn as many different patterns as you can and pick one that fits your design πŸ₯²

faint crag
thick terrace
#

MVC is great for heavy ui games, but not much use if your game is 90% physics

faint crag
#

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

thick terrace
#

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

gray mural
#

I should have reread it first

wintry crescent
#

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?

rain minnow
faint crag
rain minnow
faint crag
#

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

rain minnow
#

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 . . .

dense scroll
#

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);
        }
    }
}
faint crag
# rain minnow wouldn't you subscribe to the system handling the event?

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

leaden ice
dense scroll
leaden ice
#

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;```
dense scroll
leaden ice
#

both of them do the same thing

dense scroll
leaden ice
#

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

dense scroll
leaden ice
#

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.

dense scroll
#

so in the scenes the scripts are the same

leaden ice
#

you have the script on some other object(s) in at least one of the scenes

dense scroll
#

well, i have the object with the scripts with "don't destroy on load"

leaden ice
#

I'm aware

#

I can see the code

#

You're actually not using it correctly though

#

Aren't you getting errors for that?

dense scroll
#

nope

leaden ice
#

Are you looking at your console?

dense scroll
#

yeah

leaden ice
#

Show a screenshot of your console

#

when the game runs

dense scroll
#

well

#

thats right

#

im dumb

leaden ice
#

Yeah

#

don't ignore your errors

#

You're calling DontDestroyOnLoad and Destroy on the wrong things

#

those need to be called on the GameObject

edgy stump
#

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?

dense scroll
leaden ice
#

no

#

it's destroying the script instance

leaden ice
rigid island
edgy stump
#

float parsing is not working

leaden ice
faint crag
# rain minnow wouldn't you subscribe to the system handling the event?

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

rigid island
#

You can probably use TextMeshPro to use Regex and only include numbers

edgy stump
#

and how to use onValueChanged on input fields

rigid island
#

great!

leaden ice
#

You just said you didn't know πŸ€”

edgy stump
#

but ClampedFloatParameter not have parsing

leaden ice
#

You don't parse that

#

you parse the input field thing

#

to get a float

rigid island
#

its just a foat

leaden ice
#

to put in the param

rigid island
#

clampedFloatParameter.value= value;

edgy stump
#

I'm stupid πŸ₯Ά

rigid island
#

.value gives you the float

edgy stump
#

gonna try

rigid island
#

no lie

leaden ice
#

Did you check the docs for ClampedFloatParameter?

dense scroll
leaden ice
leaden ice
#

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.

dense scroll
leaden ice
#

I already told you why

edgy stump
#

float.TryParse(intensityField.text, out intensity.value);

A property or indexer may not be passed as an out or ref parameter

What he mean?

leaden ice
#

you can't pass a property in as a ref param

spring creek
dense scroll
leaden ice
#

Maybe start over then

#

there's not much here

#

start over and understand everything as you write it.

edgy stump
dense scroll
leaden ice
#

so like I said already
you likely don't have a copy of the script in the scene you're loading

rigid island
edgy stump
#

I'm very stupid ☠️

dense scroll
rigid island
# edgy stump say me pls

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

leaden ice
#

I said: "you likely don't have a copy of the script in the scene you're loading"

edgy stump
rigid island
dense scroll
leaden ice
rigid island
tawny elkBOT
rigid island
#

also its probably easier to just make an additional Volume that you fade in with Weight value

dense scroll
leaden ice
#

drag/attach the script onto a GameObject in the scene

edgy stump
dense scroll
leaden ice
#

Scripts need to be attached to a GameObject in the scene to do anything in Unity.

leaden ice
#

and which scene are you loading

rigid island
#

it has instructions on Large Code

dense scroll
leaden ice
#

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.

leaden ice
#

Start only runs once for each instance of the script.

dense scroll
leaden ice
#

show screenshots

#

we're talking in hypotheticals

#

show the scene

#

with the object in it

#

etc

dense scroll
#

what scene

#

the main menu??

#

the game or what

leaden ice
#

Both?

#

all

#

show some details

dense scroll
#

okey one moment

rigid island
# edgy stump https://paste.ofcode.org/GbyxwJuYPirP3VqqWrMGPS

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

dense scroll
leaden ice
#

ok now

#

show the game scene

#

I bet you have a copy of one of those in the game scene

#

and not the other

dense scroll
#

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)

spring creek
leaden ice
#

and also probably more errors in your console

dense scroll
rigid island
dense scroll
dense scroll
edgy stump
#

I added this line

rigid island
rigid island
#

I'm gonna spin up unity again real quick, its been a while since I touched Profile values directly

spring creek
#

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?

rigid island
edgy stump
#

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

spring creek
dark fossil
#

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
rigid island
#

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)

dark fossil
#

why is void wrong the return?

rigid island
#

typically async methods are Task

dark fossil
#

i mean i know its allowed but is there something wrong with it

rigid island
#

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

dark fossil
#

i have not

#

in what cases would i use the async awake?

rigid island
#

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?

dark fossil
#

im not sure

rigid island
#

either way its unitys own version of AsyncOperation

#

not standard async

dark fossil
#

is there a difference in how they work?

rigid island
#

well for this you would use a Coroutine so unity handles all that stuff

#

its a "YieldInstruction" like WaitForSeconds etc..

dark fossil
rigid island
dark fossil
#

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

rigid island
wise kindle
#

Okay, I see I came in at the wrong time

dark fossil
#

im still new so i didnt rlly know the answer

dark fossil
winged shadow
#

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

cold parrot
winged shadow
#

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

cold parrot
#

If you override without calling base() inside the override, the base implementation is gone

winged shadow
#

oh like this a() : base()

cold parrot
winged shadow
#

like this base.a()

cold parrot
#

Something entirely different

#

Yes

winged shadow
#

i did that but it still doesnt work

cold parrot
#

Maybe show the code

winged shadow
#

sec

#

in my other class im calling the function unitAttack.Attack(target);

cold parrot
#

how do you know its not executing right?

winged shadow
#

becasue i put the debug log

#

in both

#

and its only running the one in the base class

#

both scripts are on my gameobject

cold parrot
#

where do you put the debug logs?

#

where exactly?

winged shadow
#

just at the top inside the attack function

#

outside of the timer loop

cold parrot
#

and you are sure you've put the SoldierAttack on the gameobject?

winged shadow
#

yeh

cold parrot
#

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

winged shadow
#

it doesnt seem like there is many areas to fail here

cold parrot
#

true

winged shadow
#

they are on the go

cold parrot
#

they are both on there

#

why is that?

winged shadow
#

dont they both have to be on there

cold parrot
#

no

winged shadow
#

but if the soldier one isnt on there

#

it will only run the base function?

cold parrot
#

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

winged shadow
#

but if i reference unitattack and its not on the object i wont be able to get it

#

right

cold parrot
#

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()

winged shadow
#

I don't Wana have to cast it though

cold parrot
#

in that scenario, with your Soldier GameObject from the screenshot, you are probably getting the UnitAttack, and not the SoldierAttack.

winged shadow
#

I know it's getting the unit attack but I thought the function would be overrided

cold parrot
#

seems you still don't understand

#

if you override a class, it is still the base class, but ALSO the overridden class

winged shadow
#

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

cold parrot
#

and you want archer, soldier, cavalry all on the same object?

winged shadow
#

No

#

Each on its own obviously

cold parrot
#

well, then, remove the "UnitAttack" from them and proceed, problem solved

spring creek
winged shadow
#

If I call get the component of the unit attack will it put the child ones instead of it's not attached

spring creek
winged shadow
#

So how can I call each of their attacks

knotty sun
winged shadow
#

So it will add the solder attack script? If that is the one on the gameobject

knotty sun
#

yes if SoldierAttack inherits from UnitAttack

winged shadow
#

Ah ok that's good

winged shadow
#

nice

#

its working nicely now

simple egret
#

You're better off asking this in a Blender forum

#

It's neither a Unity question nor a code question

carmine iris
#

ohh my bad wrong discord

#

going straigth to blender

tough storm
#

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

rigid island
#

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

elfin hull
#

I have an interesting case, I need to make a visual lead so the player knows where to shoot at a plane

leaden ice
elfin hull
#

oh, thanks!

#

This is for 2D, I'm looking for a 3D script

leaden ice
#

shouldn't be too hard to adapt it to 3D

elfin hull
#

I see, let me try

elfin hull
cosmic rain
#

Instead of trying to find the velocity, normalize the direction and multiply it by some constant value.

elfin hull
cosmic rain
#

leadPos = pos + dir * leadDistance

elfin hull
#

hmm, I'll try it

#

something like this?

cosmic rain
rocky basalt
#

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.

leaden ice
#

Use a csv parser library

#

Just iterate over the rows and add them to the dictionary

low horizon
#

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

buoyant scroll
#

In my package cache, it gives off script errors for my packages, how do I get rid of it?

heady iris
#

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

buoyant scroll
#

What do you mean by manually installing?

heady iris
#

something like this, where you actually ask for a specific package version

buoyant scroll
#

Oh, haven't done it that way

heady iris
#

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

buoyant scroll
#

It's a Unity Registry package

heady iris
#

so it wound up causing compile errors

heady iris
#

What package is producing the error? Can you show your console?

buoyant scroll
#

Oh

buoyant scroll
#

TextMeshPro

heady iris
#

show me the errors it's producing

buoyant scroll
#

it's filled

#

pretty filled for me

heady iris
#

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?

quartz folio
#

and always look at the first error, not the last

buoyant scroll
heady iris
#

any chance you've copied TextMeshPro code into your project?

buoyant scroll
#

what do you mean

#

can you elaborate on that?

heady iris
#

moving code from the package into the Assets folder, for example

buoyant scroll
#

no, but i've tried fixing some of the code

#

so i've modified some of the package's code

heady iris
#

You can't edit code that's in the Library. It will get overwritten by Unity.

buoyant scroll
#

oh

heady iris
#

close unity, delete the entire com.unity.textmeshpro@3.0.8 folder from Library/PackageCache, and then reopen the project

buoyant scroll
#

Alright, give me one moment to do so

heady iris
buoyant scroll
#

would i delete folders for packages with scripts errors as well?

#

like other packages?

heady iris
#

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

buoyant scroll
#

thanks a lot for the support

golden garnet
#

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.

buoyant scroll
heady iris
golden garnet
#

yea tru i just found that out. odd that it sets speed and pitch when only labelling it as one

heady iris
#

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)

hybrid harness
#

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

faint hornet
#

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 )

cosmic rain
#

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.

faint hornet
# cosmic rain The point of a pool is to avoid overhead of instantiating and destroying new obj...

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

cosmic rain
#

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.

faint hornet
cosmic rain
#

Anyways, you should probably be confirming all that by testing and profiling

delicate oak
#

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

faint hornet
#

the clip is added to the gameobject. i'm calling audioSource.Play(); and nothing is woprking?

cosmic rain
#

You'd need to share more details.

faint hornet
#

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

faint hornet
faint hornet
cosmic rain
cosmic rain
#

I'd add some debug to see if it's being called and when

faint hornet
#

during runtime, the prefab is exactly how it looks in the screen shot

faint hornet
faint hornet
cosmic rain
#

Make sure you don't run play every frame on the same component. That would reset the play time and never pactually play anything

faint hornet
faint hornet
#

@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

edgy stump
faint hornet
#

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

latent latch
#

hasHit = true;

faint hornet
cosmic rain
#

Fixed update doesn't hit anythingπŸ˜…

#

It just updates

faint hornet
#

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);
    }
  }```
latent latch
#

I keep hearing that there are duplicate messages with trigger/collision methods, but I thought a lot of this is single-threaded

cosmic rain
latent latch
#

Ah, right Destroy isn't a good indication

faint hornet
latent latch
#

well, the bool itself isn't going to do anything

faint hornet
latent latch
#

ya need a statement to back up the bool

faint hornet
#

oh right lol

latent latch
#

if(hasHit) return;

faint hornet
# latent latch ya need a statement to back up the bool

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);
    }
  }```
quartz folio
#

btw...

if (other.gameObject.TryGetComponent(out Enemy enemy))
{
  // use enemy
}

Instead of GetComponent twice

amber depot
#

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^^.?

rancid frost
#

Is there a way too know if 2 material properties have thesame values?

latent latch
#

If they are sharedmaterials you can probably just compare references

simple sable
#

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. πŸ™‚

patent kiln
#

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

latent latch
simple sable
wide dock
#

Weird indeed

latent latch
#

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

simple sable
#

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.

latent latch
#

Well, you need specific instances somehow

#

some sort of identifier for each item you instantiate

lean sail
wide dock
#

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

simple sable
#

Alright, thanks for the ideas guys! I'll give it a try.

digital creek
#

I know this is a specific question but is there a method to capture the state of all relevant game objects (enemies, important objects...)

digital creek
cosmic rain
digital creek
cosmic rain
#

Implement a serialization strategy for the relevant objects, then serialize them when you want to store their state.

knotty sun
# digital creek Yes

Unity has no built in functionality for run time saving so you will need to build your own or use a 3rd party solution

tame quartz
#

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

digital creek
#

Thanks guys. i will try to implement it

stoic ledge
#

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?

civic palm
#

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

somber nacelle
#

stop crossposting everywhere. you can use id:browse to find the most relevant channel

civic palm
#

There is no localization channel

somber nacelle
#

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

civic palm
#

It is code-related, but it's related to something Unity wisely decides not to support directly on here

somber nacelle
#

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

vagrant blade
#

If you've encountered a bug, you should report it. !bug

tawny elkBOT
#

πŸͺ² 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

civic palm
#

@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

vagrant blade
#

Okay, good luck!

civic palm
#

I need a workaround as quickly as possible, since we are stuck in cert thanks to this problem

#

I guess Twitter is it, then

cosmic rain
civic palm
#

@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

cosmic rain
civic palm
#

Working on that, but game won't launch with a debugger attached πŸ₯²

cosmic rain
#

That doesn't make sense. Also, you can attach it after launching it.

civic palm
#

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

cosmic rain
#

Build it normally and attach the debugger when it's already running

cosmic rain
civic palm
#

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ℒ️

primal wind
#

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

civic palm
#

@cosmic rain Got it running again, with great success:

#

Going to do some manual breakpointing and see if that helps

cosmic rain
civic palm
#

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

cosmic rain
#

Was the previous build built on your machine?

cosmic rain
civic palm
#

Using Debug > Attach Unity Debugger

#

Then picking the process

#

The attachment works fine, but breaking doesn't

cosmic rain
#
  1. It could be the wrong process.
  2. It's sometimes better to use the attach to process option instead of the unity one.
thick terrace
# primal wind How do i do that exactly with Newtonsoft.Json?

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;
}
civic palm
#

@cosmic rain Hooray, attaching without using the Unity helper did the trick!

#

Let's see what we have here ...

civic palm
#

@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

cosmic rain
#

Not really helpful. Looks like decompiled code..?

#

the callstack window can be added from debug - windows

civic palm
#

Yeah, it's IL

cosmic rain
#

Kinda hard to interpret that. Can you take a screenshot instead? Preferably of the whole IDE window.

civic palm
#

@cosmic rain You might want to specify what's interesting to you here:

#

There's a lot of IDE window going on

cosmic rain
#

That's good enough. I wanter to confirm that it's the main thread.

civic palm
#

This seems relevant:

cosmic rain
#

You should probably be looking at the last call in the GameAssembly

civic palm
#

Yeah, it's the main thread.

cosmic rain
#

You should look in here first

#

As well as in the last call before ntdll(assuming it shows anything)

civic palm
#

Just to underscore

civic palm
#

Disassembly is a bit raw for me πŸ˜›

cosmic rain
civic palm
#

As in, provide evidence that yup this is main thread

dreamy atlas
#

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

spring creek
dreamy atlas
#

big cube

latent latch
#

debug the values

#

wouldnt expect scaling would affect the bounds values but maybe

spring creek
# dreamy atlas 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

dreamy atlas
#

also, the further away i am from the hit pos im standing, the closer to the surface it gets placed

spring creek
dreamy atlas
#

they were a child of player. when i activate the Place() function, i first set their parent to null before changing its values

spring creek
#

Ohhh, the scale IS being changed then

#

I guess I should have guessed considering the image πŸ€¦β€β™‚οΈ

#

Well, I would do what mao said

dreamy atlas
#

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

dreamy atlas
spring creek
#

Did you try using position?

dreamy atlas
#

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

heady iris
#

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

dreamy atlas
heady iris
#

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

dreamy atlas
#

I tried SyncTransforms, no change

#

Here's what bounds.size.y is different times when i place it

heady iris
#

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.

dreamy atlas
#

oh my god thank you!!! you're right!!!