#archived-code-general

1 messages Β· Page 316 of 1

void tendon
#

Hello, I want to access files on my local system (a folder on my desktop, with .onnx files) with a application build for Unity. This works when I am using the Unity IDE, but when running the build it obviosuly cannot access it. Currently, I'm using Application.dataPath + directory string. I've tried to search online but some of the anwsers, i was very confused by. Any inisght into this would be great ty

leaden ice
#

Where is the folder you're trying to access?

#

You said it was on your desktop

#

that wouldn't be inside your game folder

void tendon
#

Currently, the files are in the same folder as the assets folder - which works in the IDE

leaden ice
void tendon
#

but I wish to have them on my desktop

#

Yeah..

leaden ice
#

if you want to copy some files verbatim into your build, you need to use streaming assets

void tendon
#

Yes, I've read about this. Would it allow me to access a folder on my desktop?

#

In a build

leaden ice
#

Are you saying you're putting the game install on your desktop?

#

If you want to access your desktop just use that folder path

#

e.g. C:\\Users\cailn\Desktop\MyFolder\whatever.file

void tendon
leaden ice
#

where is the Game folder

void tendon
#

Desktop, sorry

leaden ice
#

show the file hierarchy

void tendon
#

sure

leaden ice
#

like:

Desktop
  Game
  onnx
```?
void tendon
leaden ice
#

Or

Desktop
  Game
    onnx```?
void tendon
#

yeah

leaden ice
#

ok so they're next to each other?

void tendon
#

oh sorry, yeah

void tendon
leaden ice
#

Since it's outside the game itself you basically want to use an absolute path

void tendon
leaden ice
void tendon
#

And I can achieve that by using Streaming Assets

leaden ice
#

no

#

streaming assets is for including the files in the build itself

void tendon
#

Ah I see

#

So if I use an absolute path, it will work?

leaden ice
#

I wouldn't have recommended something that wouldn't work πŸ˜‰

void tendon
#

Pefect, tytytytyty appreciate it ❀️

#

I was getting mega-confused with asset bundles, streaming assets etc..

#

On a side-note, does unity have the ability to load models dynamically? as in if I did the same thing with .fbx files instead of .onnx

leaden ice
void tendon
jagged snow
#

Is there any way to apply this to a prefab and use the same stored variables for the prefabs created after?

    {
        _audioSource = GetComponent<AudioSource>();
        _caster = GetComponent<CharacterActionCaster>();
        _animator = GetComponent<Animator>();
    }```
dawn mauve
#

Just tested a couple things related to logging of a game server inside a container on my macbook based on what we talked about before, here's my findings

(1) (false) See if the non-development build produces logs into a log file in the same directory as the game directory in the container. No file is automatically produced like some of you guys thought.
(2) (true) See if the non-development build produces logs to standard out from an intel-based EC2 instance. Turns out it does.

Conclusion: looks like it is indeed my m2 macbook getting in the way. That's... frustrating. I guess I can just stick with development builds when testing my multiplayer game server locally.

knotty sun
#

wait, logs are not in the Game folder, they are in the persistentdata folder of your game

leaden ice
#

what do you mean by "the prefabs created after"?

jagged snow
leaden ice
jagged snow
leaden ice
#

what kind of event?

#

You're being really vague

jagged snow
#

A situation I'm having atm is having a coroutine spawn a projectile after a certain period of time

#

OnProcessHit which creates a bunch of information in regards to the target hit and damage calculations along with the normals and point

clear halo
#

Why do I keep getting these if I don't have anything underlined? I also have nothing that uses "_"

leaden ice
#

including UnityEvents

jagged snow
#

i thought it reset with every new instance

leaden ice
leaden ice
thick terrace
#

if by subscribe you mean subscribe in code on the prefab before instantiating it, those listeners won't be copied

jagged snow
#

I didn't know you could apply values to a prefab that hasnt been instantied

#

I thought you had to instantiate them first before doing anything like even applying functions

#
    {
        _originPos = transform.position;
        OnHit = onHit;
        _allowHitsProcessed = true;
        if (impactPrefab)
        {
            _impactPrefab = impactPrefab;
            OnImpactHit = onImpactHit;
        }
        _isInitialized = true;
    }```
Heres the setup function for my projectile
leaden ice
#

I mean technically you could do it in code but like... why?

#

plus any changes you make to the prefab in code are going to persist in the editor anyway

jagged snow
#

I cant subscribe events in the editor

spring flame
#

is there some event when a components are reordered in the inspector?

thick terrace
leaden ice
jagged snow
#

hmm i see

oak ore
#

Hey... cant anyone help me with this issue?

outer geyser
outer geyser
# oak ore Ohhhh.... will that fix it?

I'm not promising anything, it's just my guess, since input.mousePosition is not guaranteed to give you same results as data taken from input event (it can be delayed by frame and cause weird behavior you described)

oak ore
cursive kestrel
#

it seems like the awake function of my script is executed twice
anyone knows why ?

knotty sun
cursive kestrel
#

yeah i just found out

#

i thought i only had one

#

sorry for bothering you

#

no, it still seems to be called twice after removing the second instance

knotty sun
#

Debug.log this.GetInstanceID and gameObject.GetInstanceID. this will tell you exactly the gameobject and script references

#

one point, you need a return after the Destroy. Destroy does not stop code execution

leaden ice
#

Otherwise of course that code will run

cursive kestrel
plucky inlet
upper pilot
#

How is it possible for a static variable in a non static class to have persistent value across scene changes when that script doesn't exist?

using Steamworks;

public class SteamEngine : MonoBehaviour
{
    private static bool _initialized;
    private void Awake()
    {
        if (_initialized) return;//this is true even after we destroy this object when a scene changes.
        Steam.Init();
        _initialized = true;
    }
}

That's a small snippet of how it works, I can't find any references to SteamEngine(except gameObject in hierarchy) or any reference to _initialized outside of this script Awake function.

#

Basically after going back to Main Menu scene where this object doesn't exist, then coming back to the game this variable is already set to true.

knotty sun
#

static variables exist outside of any class instance. Therefore once they have been created they exist for the total lifespan of the application domain

upper pilot
#

even if the class itself was destroyed?(I assume it was as I cant find it in hierarchy)

knotty sun
#

you cannot destroy a class, only an instance of a class

upper pilot
#

right, but static doesnt care about an instance. I see

#

Thanks

quiet ferry
#

Can anyone help me implement a rarity system for my game. I have a spawner at the moment that spawns a random item in an array and at a random position around the player. How would I add a percent in which each item should spawn? I want some to spawn less often.

modern creek
#

You can use a weighted list to pull a random item from the list based on the weight. I wrote one for C# a while ago

weary swift
#

!code

tawny elkBOT
weary swift
#

Yo ! I have a problem that I don't really understand. I have two class "AnimationState (StateMachineBehaviour)" and "PlayerAnimation (MonoBehaviour)". In PlayerAnimation in the method OnEnable I do this :

AnimationState.OnRollAnimationEnd += () => _playerLocomotionReference.UpdateRollVariablesAtEnd();

The problem is in the other class. In AnimationState I have a dictionary :

Dictionary<(int animationFullLengthHash, AnimationStateEvent evt), Action>

OnStateExit I invoke the Action if the key exists in the dictionary. The problem is that everytime the event is null. My idea is that the OnEnable function of the PlayerAnimation is executed before the AnimationState, this make the event not subscribed but I'm not sure. But maybe I just don't know something about how events, or static keyword works ?

https://gdl.space/ugajiremal.cs

Can you help me please ?

leaden ice
#

You cannot unsubscribe a lambda like this

weary swift
#

Oh ok xD, why ?

leaden ice
#

because those are two different instances

weary swift
#

Ok I understand

leaden ice
#

AnimationState.OnRollAnimationEnd += _playerLocomotionReference.UpdateRollVariablesAtEnd;
AnimationState.OnRollAnimationEnd -= _playerLocomotionReference.UpdateRollVariablesAtEnd;

#

this would work

weary swift
#

Makes much more sense, don't know why I used lambda

leaden ice
#

Anyway it's not clear what AnimationStateEvent.OnExit is to me

#

oh nvm it's an enum

weary swift
#

Yes

leaden ice
# weary swift Yes

Have you tried printing the hash and comparing that to what's in the dictionary?

weary swift
#

The hash is correct

#

I printed the events and there are set to null

leaden ice
#
        if (dictionaryAnimationEvent.TryGetValue((stateInfo.fullPathHash, AnimationStateEvent.OnExit), out Action action)) {
            action?.Invoke();
        }``` Btw this would be a clearner and more performant way to do this
weary swift
#

The hash are the same and the OnStateEnter works

leaden ice
#

Oh so annyway

#

I see what the problem is here

weary swift
#

Didn't know about this method

leaden ice
#
    private static readonly int _rollAnimationHash = Animator.StringToHash("Base Layer.player_roll_animation");
    public static event Action OnRollAnimationEnd;
    
    private static readonly int _backStepAnimationHash = Animator.StringToHash("Base Layer.player_back_step");
    public static event Action OnBackStepAnimationEnd;

    private static readonly Dictionary<(int animationFullLengthHash, AnimationStateEvent evt), Action> dictionaryAnimationEvent = new() {
        {(_rollAnimationHash, AnimationStateEvent.OnExit), OnRollAnimationEnd},
        {(_backStepAnimationHash, AnimationStateEvent.OnExit), OnBackStepAnimationEnd}
    };```
So you're adding these two empty delegates to the dictionary here
#

when you do this:
AnimationState.OnRollAnimationEnd += () => _playerLocomotionReference.UpdateRollVariablesAtEnd();
OnRollAnimationEnd gets reassigned

#

the thing in the dictionary will not be affected

#

What you should do is this:

    private static readonly int _rollAnimationHash = Animator.StringToHash("Base Layer.player_roll_animation");
    public static event Action OnRollAnimationEnd;

    void WhenAnimationEnds() {
      OnRollAnimationEnd?.Invoke();
    }

    private static readonly Dictionary<(int animationFullLengthHash, AnimationStateEvent evt), Action> dictionaryAnimationEvent = new() {
        {(_rollAnimationHash, AnimationStateEvent.OnExit), WhenAnimationEnds},
    };
weary swift
#

So, the variables are put in the dictionary with their current values (null in this case) and then the event are subscribed, but not the ones in the dictionary ?

leaden ice
#

when you subscribe to the event you're pointing the event variable at a new delegate instance

#

the old (empty) one is still in the dictionary

#

and the old empty one is what you see when you get it from the dictionary in OnStateExit

weary swift
#

Ok

weary swift
#

Or can I do WhenAnimationEnds(Action evt) and call that in the dictionary ?

leaden ice
#

You could make the delegates private

#

and instead of sibscribing to the evenst you do this:

weary swift
leaden ice
#

same variable, different instance

#

or rather the variable now points at a new instance

weary swift
#

Ok I understand

weary swift
leaden ice
#

Basically get rid of the individual event variables

#

just use the dictionary as the source of truth

#

and whenever you update a delegate inside the dictionary it just needs to be rewritten back to the dict

weary swift
#

Ok, so the idea is to create a new Action, subscribe to it and then put it in the dictionary right ?

slate glacier
#

MongoDB + Unity (Realms)

nova moon
#

Is there some sort of more efficient occlusion culling above the occlusion culling Unity already does out of the box?

somber nacelle
#

by "out of the box" do you actually mean the occlusion culling you have to manually set up? because it only does frustum culling out of the box

nova moon
#

Ah maybe that's what I'm mixing up. I was thinking it did occlusion culling automatically. But you're right frustum culling is what I'm thinking of.

somber nacelle
#

in that case, you can set up occlusion culling

nova moon
#

Yea I'll look into that. Thanks!

swift falcon
whole geyser
#

my player's horizontal velocity is being lowered or reset when it hits the ground, causing it to have to accelerate again, how can I fix this?

spring creek
whole geyser
#

i have rigidbody2d added

spring creek
# whole geyser https://gdl.space/enomeqeseh.cpp

I don't see anything obviously causing the problem.
I would add some logs to tell the exact value of velocity as well as the INPUT.
Also, did you have physics materials? Might be the transition to high friction or something

swift falcon
waxen blade
#
    public Enemy EnemySelector(Enemy[] enemies)
    {
        int i = Random.Range(0, GameData.PossibleEnemySpawns.Count);
        return enemies[i];
    }

I have a method that picks a random enemy from an array of enemies. I want to expand on it by allowing it to also pick between other class objects as well with an equal chance of being selected. So for example I have another class called Hazard that will be a different spike hazard instead of an enemy.

How do I go about adding multiple classes into an array or a list, and then randomly picking one of them?

fervent furnace
#

you cant, unless they are both inheritance from same class/interface
or use object but you wont know which class the object exactly is unless you test it with all possible classes

waxen blade
#

Hmmm.. that might work, giving them all the same interface.

#

I'll give that a try, thanks.

#

Although I don't need a method for my interface, so it would just be empty. Interfaces are best used to create a contract, and in this case there isn't a contract.

soft shard
#

Interfaces can also be used for "grouping" logic, but I can also see the dislike toward essentially a empty script serving as a glorified label, though it gives you the option to create that contract later if you decide to add logic thats consistent across all your enemies/hazards

silk cairn
#

I have a ship whose position is being moved with Vector3.MoveTowards, and inside of the ship I have a playerobject that is not able to move when the ship is moving due to the ship being the parent of the player. How could I have the player move freely while the ship is still moving?

silk cairn
#

nvm

unreal temple
#

Has anyone here had success with TMP links?

#
    void Awake() {
      _text = GetComponent<TextMeshProUGUI>();
      Assert.NotNull(_text, nameof(_text));
      Debug.Log("links " + _text.textInfo.linkCount);
    }
#

The precise rich text:

<link="discord">join us on discord!</link>
#

i don't think I could get any more basic than this and it fails. I wonder if I need to turn on some setting to support link parsing?

mossy snow
#

your debug log is probably misleading because it's too early

unreal temple
#

all g, I'll experiment

#

Ah, you're correct

#

this was not my actual problem, which is that the click wasn't registering

#

but now it's working in this example

#

It was choking because I had a list bulleted with >

#

Like:

<b> > item </b>
<b> > item </b>
<b> > item </b>
<link="discord">...</link>
chilly surge
#

Yeah it's kind of suboptimal that TMP/UGUI rich text doesn't expose a way to set the rich text via some form of AST, and so you have to deal with escaping/unescaping stuffs which is really annoying.

gaunt wren
#

more of a general question, what's the best way to do Flamethrowers hitboxes? I have the particle effect ready however I suspect using the particles themselves could be a massive performance drain.

Should I just create a bunch of invisible hitboxes that roughly follow the movement of the particles or would it be fine to use the particles to call the damage functionality?

lean sail
# gaunt wren more of a general question, what's the best way to do Flamethrowers hitboxes? I ...

How many particles are there? Particle collision really might not be that bad, it sends at max 1 per frame but also has a parameter to let you know how many collisions actually happened in that frame.
instead of invis hitboxes, you could try the idea with just basic overlap functions after getting the particles https://docs.unity3d.com/ScriptReference/ParticleSystem.GetParticles.html. Possibly limit it to a certain number incase you really have a ton of particles

gaunt wren
civic igloo
#

I'm having this issue where transform.position gives me the wrong value when i get it. Basically i have this character animation holding a gun, that gun has an empty "gunTip" object at it's tip, and when i try to set another objects position to it, the second object is in the wrong place and jitters between the correct position and slightly away, anyone know what to do here? (in the picture, white sphere is the object whose position is set to gunTip.position, red sphere is child object of the gun tip, and cyan is a gizmo wiresphere being drawn at gunTip.position, which weirdly enough, is in the right place)

lean sail
lean sail
civic igloo
#

i mean the code really is just that, tempSphere.position = gunTip.position, it's in a new script file with nothing else in it

plucky inlet
#

You sure, you are getting the wrong value? Or are you just mixing up position and localposition and looking at the inspector (which is always local)?

plucky inlet
cursive kestrel
#

hello, i have a problem where my "damages" list seems to be cleared before my function CountDamages is called
The CountDamages function is called periodically by my player controller script
I never see "Called" in the debug console BUT i do see "Hit" when my player is attacked
I've checked, the function CountDamages is called but the Debug.Log and the other functions inside the condition are never called

civic igloo
plucky inlet
civic igloo
#

The white sphere isn’t a child of anything if that’s what you mean

plucky inlet
civic igloo
#

Yeah

plucky inlet
#

where do you set the position of the sphere, like the whole code, even if its not much

civic igloo
plucky inlet
#

and if you debug log both positions, they are equal?

civic igloo
#

Haven’t tried debugging both, i just compared the printed value to what’s in the inspector

plucky inlet
#

your guntip is for sure a child of something, right?

civic igloo
#

I also just tried that code with a different, simpler animation of just a cube moving back and forth, and the sphere follows that just fine

plucky inlet
#

your guntip is an empty transform or an actual mesh?

civic igloo
#

guntip is an empty gameobject parented to a gun thats parented to a hand

plucky inlet
#

And how does it look like in runtime, probably with a sphere not 1 m in diameter πŸ˜„

lean sail
# cursive kestrel hello, i have a problem where my "damages" list seems to be cleared before my f...

!code but also please show where you call CountDamage in the first place. If that "Called" debug is never ran, maybe you are clearing the list somewhere. its a public list meaning anything at all can edit it as they please. Or maybe you are calling it on the wrong object. Useful debugs would be like printing out the name of the object and also damages.Count. "Called" really doesnt tell you anything
That List<int[]> should also really be some List<class or struct> instead for readability and ease.

tawny elkBOT
plucky inlet
cursive kestrel
civic igloo
#

yea

plucky inlet
#

Only thing I can think of is, that the rigged animation smoothing things out the position is not. I guess, if you want to move it instantly, just parent it, if you want to follow, use something like vector.lerp or slerp to make it smooth and avoid glitching

golden wave
#

Anyone got some experience with System.Random?
I'm doing this on both my client & server:

random = new Random(randomSeed);
int random1 = random.Next(1, 100);
int random2 = random.Next(1, 1000);
int random3 = random.Next(1, 10000);
int random4 = random.Next(1, 100000);
int random5 = random.Next(1, 1000000);```
The server just sends the randomSeed number to the client, which then generates the 5 random values (it's just a test)
But I get results like this consistently:
27 / 26
926 / 926
1628 / 1627
83052 / 83052
965754 / 965754

Sometimes the value on my client is 1 lower than the value on the server?
knotty sun
#

Are you using the same .Net?

golden wave
#

I assumed the differences would be bigger if that was the cause, but maybe not
I've been researching how to use a cross-platform Random generator for 2 hours, but it's way too complicated for me

knotty sun
#

well there you go, not the same, so different results

#

Also the client will be using Mono .Net not MS .Net so that is an additional complication

golden wave
#

I have no idea what that means πŸ™‚
Would changing my server to .NET Core 3.1 fix it?

knotty sun
#

no, of course not, Unity does not use .Net Core 3

golden wave
#

So how would I fix this?

knotty sun
#

do not use system.random ?

golden wave
#

Well I've been searching for an alternative for 2 hours but I don't understand most of it

#

Any suggestions?

knotty sun
#

what's wrong with the Unity Random ?

golden wave
#

The server is C#, not unity, or can UGS C# CCM access that?

knotty sun
#

of course it can, Unity is just a dll after all

#

if you do not know these basic facts about using C# and .Net should you even be doing it?

golden wave
#

How would I access the Unity Random on my server then? 😣

knotty sun
#

like you would any other dll

golden wave
#

I've never used a dll

#

Seems like the Unity Random is made to be used in Unity and dependant on it's runtime environment
Doesn't sound like it's easy to use it outside of Unity

cosmic rain
golden wave
knotty sun
# golden wave I've never used a dll

wdym you've never used a dll? The whole C# .Net system is based on dll's. Where do you think the System namespace comes from. Again I say if you do not know these basic facts of C# and .Net should you be using it?

naive lake
#

I'm currently using VS on mac, should I consider using VSC with C# Dev kit? Purely because of it's support beign discontinued for mac.

knotty sun
naive lake
#

Could I ask why?

knotty sun
#

because VSC is crap

naive lake
#

lol K

chilly surge
#

VS Code is more than fine.

knotty sun
chilly surge
golden wave
knotty sun
knotty sun
chilly surge
#

Well the "text editor vs IDE" point is something people say a lot yet has zero substance behind. If you are claiming "VS Code cannot support C# without extensions" then similarly "VS cannot support C# without workloads."

#

Regardless, I'm just pointing out that VS Code is probably a better tool long term than a soon to be deserted and unsupported VS for Mac.

knotty sun
chilly surge
#

Nothing really, if it works now then it will continue to work in the short term, which is why I pointed out "long term."

knotty sun
#

And, as I said, MonoDevelop is a worthy replacement

chilly surge
#

But really the point is that VS Code is not an option that should be automatically discarded because of personal opinions.

knotty sun
chilly surge
#

That's completely fine, everyone has their favorites.

thick terrace
#

i spent 3 years working primarily on a mac and i would've gone bananas without vs code lol, visual studio for mac/monodevelop did not cut it

chilly surge
#

I'm just pointing out that "VS Code is crap" is probably not a good advice to give just because it's not your favorite.

#

VS Code is my favorite yet I recommend every C# beginner to use VS.

knotty sun
#

I used to use the Eclipse IDE for C and C++ dev on Mac and Linux, I wish I could use it for C#

thick terrace
#

oh haha, i was a java developer in a previous life and if i never touch eclipse again it'll be too soon πŸ˜‚

knotty sun
#

Eclipse was brilliant (at the time) unfortunately time has not treated it well.
Full disclosure, I now run Windows VM's on both Mac and Linux just so I can code in VS

primal wind
#

Oh yeah I almost forgot why I'm here

#

Is there a way to look into assemblies without loading them?

thick terrace
white mulch
#

Hi I'm a beginner in unity i can't get the newest ver. of unity?

late lion
knotty sun
white mulch
#

ok

knotty sun
late lion
# knotty sun will still have to load it

I made the assumption that by "loading them", they meant using Assembly.Load to load them into the runtime. As opposed to reading them from disk. I think that's a fair assumption.

#

It can be undesirable to load the assembly into the runtime if you just want to see what's in it.

knotty sun
#

you can see the namespaces and classes from the symbol file, the methods etc need the dll

blazing tiger
#

I haven't coded in a while and kinda forgot how are you supposed to lerp stuff linearly for things like walk speed and crouching and stuff. So far making variables that I increase/decrease on update under condition by delta time and 0-1 clamp, then feed them into an animation curve

#

Is there a built in thing that does this under the hood?

dusty grove
#

Hey everyone πŸ™‚

plucky inlet
blazing tiger
#

Because on the official docs they do make t as a separate variable

plucky inlet
#

You want to have a method that lets you use lerp on a T like myFloatNumber.Lerp(); ?

blazing tiger
#

Give me a minute I'm gonna be at my pc soon and explain

thick terrace
plucky inlet
#

I mean, Mathf. can also be lerped, but I think, he does not want to have the whole myfloat = Mathf.Lerp(myfloat, newfloat, Time) thing

blazing tiger
#

Actually I'm dumb I'm pretty sure it's not possible without declaring a t like so

float t = .0f;
float posY = .0f;

void Update(float dt){
  t = Mathf.Clamp01(t + dt * dir);
  posY = Mathf.Lerp(5.0f, 12.0f, t);
}
plucky inlet
#

I mean, you can write your own extension class with an extension for this, if you want cleaner code. but that extension at least will have that code.

blazing tiger
#

You could probably theoretically make a static class that remembers the property it's lerping and makes a dedicated t for it πŸ€”

#

Actually I'm not sure whether you can map properties like this in c#

plucky inlet
#

But I mean, if you do something like

        public static float LerpMe(this float value)
        {
            value += Time.deltaTime;
            return value;
        }

You should be able to use your float.LerpMe(); for example

#

Whatever you do in lerpme of course πŸ˜„ but just for the sake of simplicity

blazing tiger
#

I love overcomplicating things

plucky inlet
#

Nah, I did a lot of those extensions in. another project just to make the collaboration easier and also extend the , in my case, easing extension without having to revisit every codeline the other devs had to lerp everything manually

blazing tiger
#

Actually I probably did in one of my old projects and forgot about it

chilly surge
#

A reactivity system makes these extremely easy to express, eg in mine where player HP is a Signal<float>, to created a tweened version of it is simply hp.Tween(duration, easing), then you can just display that in the UI.

#

Most projects aren't built with reactivity at its core though.

light quartz
#

May I ask something

#

how long would it take to code a Stamina bar?

urban lintel
#

That depends on what aspects of it you're thinking of, your architecture and your skills. A stamina system can be as simple as 1 value that is increased on every update and is consumed by actions, with actions not executing if they don't meet the stamina requirement. But a stamina bar can also mean the visuals, or how it interacts with enemy attacks etc.

knotty sun
night storm
#

hi everyone, i do a raycast and hit.collider.CompareTag("player") a hundred times every frame. how to optimize this as much as possible?

leaden ice
night storm
leaden ice
#

It doesn't

#

But why are you fearing it

#

Instead of actually checking

#

With the profiler

#

The whole point of ConpareTag is to avoid GC

night storm
leaden ice
#

The regular profiler tells you about GC allocation

#

But no this isn't it

night storm
# leaden ice But no this isn't it

hmm gonna have to figure out where those are coming from then. wait so this line cant be micro optimized further? i remember hearing about animator.stringtohash to optimize strings, i guess the animator method is different from comparetag and thats why it needs that?

leaden ice
#

That has nothing to do with tags, no

#

That's for the Animator

night storm
#

ok, thank you!

lapis ether
#

heya folks, I'm trying to figure out getting a keypress event to map to it's character. I have everything pretty much figured out, but when I try to implement it, I keep getting a "blank/null" value return prior to the correct character value.

Here's my code:

        if(can_choose)
        {
            Event k = Event.current;
            if(k.type == EventType.KeyDown){
                Debug.Log(k.character);
                if((int)k.character !=0 && (int)k.character < story.currentChoices.Count)
                {  
                    Debug.Log((int)k.character);
                    OnChoiceSelect((int)k.character);
                }
            }
        }
    }```
#

The first Debug returns this when I press the 1 key

mellow sigil
#

First turn Collapse off in the console, you can't tell what corresponds to what otherwise

#

and log a meaningful message like "k.character: " + k.character

lapis ether
#

un-collapsed

#

It doesn't ever get to the second Debug

#

(which I knew already)

leaden ice
#

print the charqcter code

#

regardless of the if statement

#

Debug.Log("Character : [{k.character}] code: [{(int)k.character}]");

lapis ether
#

without an if statement it just prints that string on every frame

leaden ice
#

keep the if(k.type == EventType.KeyDown){

#

I'm jsut saying replace Debug.Log(k.character); with my longer line so we can see the character code for the invisible chars

lapis ether
#

It just prints that line directly, it doesn't replace the variable

leaden ice
#

What?

somber nacelle
#

forgot the $

leaden ice
#

Oh

dusk apex
#

Add an $ before the quotation

leaden ice
#

Sorry yeah:
Debug.Log($"Character : [{k.character}] code: [{(int)k.character}]");

#

my bad

lapis ether
leaden ice
#

from the bottom of the console window

#

for that first one

#

I guess it's probably a newline

lapis ether
leaden ice
#

What if you print the code first

lapis ether
#

yeah serious πŸ€”

somber nacelle
#

null terminator?

thick terrace
#

yeah, it's probably a NUL?

leaden ice
#

Debug.Log($"code: [{(int)k.character}] Character : [{k.character}]");

lapis ether
#

same thing

#

it returns Character: [

thick terrace
#

what does the code say?

somber nacelle
#

did you make sure to save the code so it recompiles?

lapis ether
#

yes

#
        if(can_choose)
        {
            Event k = Event.current;
            
            if(k.type == EventType.KeyDown){
                Debug.Log($"code: [{(int)k.character}] Character : [{k.character}] ");
                if((int)k.character !=0 && (int)k.character < story.currentChoices.Count)
                {  
                    Debug.Log("K Int" + ((int)k.character).ToString());
                    OnChoiceSelect((int)k.character);
                }
            }
        }
    }```
leaden ice
dusk apex
#

Can you show a screenshot of the console either way?

lapis ether
leaden ice
#

oh there we go

#

it IS printing the code first

#

and it's 0

dusk apex
#

Figures

leaden ice
#

so yeah a null terminator

lapis ether
#

great!

thick terrace
#

funny that unity respects the null terminator even though it knows the length of the string

leaden ice
#

So i guess just ignore character 0

#

if (k.character == (char)0) return;?

lapis ether
#

So that's my second if statement there

somber nacelle
thick terrace
lapis ether
#

I ask if the character is not equal to 0 then execute, but it never gets to taht second if statement

leaden ice
dusk apex
#

Unless you simply want to see the null print

lapis ether
leaden ice
#

well of course not

#

because the character is 0

#

isn't that the point of the if statement?

dusk apex
#

If the second log never prints, likely the character value is greater than your count

leaden ice
#

You also have this:
(int)k.character < story.currentChoices.Count

lapis ether
#

but it returns the correct integer

leaden ice
#

It seems unlikely to me that 49 is less than your number of choices

#

no I think you're confused

#

you think it's 1

#

because it was the character 1

#

but as your log shows

#

the character code for 1 is 49

#

you need to parse the string to an int

#

int choiceNumber = int.Parse("" + k.character);

#

as a quick and dirty example

leaden ice
thick terrace
#

this all makes me wonder why you're checking character and not keyCode ?

leaden ice
#

you can also do:

int choiceNumber = (int)(k.character - '0');```
#

(assuming the number of choices is always less than 10)

lapis ether
#

ok got it

#

thanks all

#

appreciate so many of y'all chiming in πŸ™‚

whole geyser
lapis ether
#

When I use that int.Parse method I get this error (but it doesn't pause gameplay):

leaden ice
#

only do the parsing inside the if ((int)character != 0) statement

lapis ether
#

ok cool

#

yeah perfect

leaden ice
#
            if(k.type == EventType.KeyDown && ((int)k.character != 0){
                int choice = int.parse(k.character);
            }```
#

or:

            if(k.type == EventType.KeyDown && ((int)k.character != 0){
                int choice = (int)(k.character - '0');
            }
#

you may want to also add another check like:

            if(k.type == EventType.KeyDown && k.character >= '0' && k.character <= '9'){
                int choice = (int)(k.character - '0');
            }```
#

to make sure it's a digit

thick terrace
#

this still seems kind of unnecessary to me, why not modify OnChoiceSelect to take a KeyCode so you don't have to do this conversion?

leaden ice
#

well the keycode still needs to be converted to a number to be used in OnChoiceSelect right?

#

but who knows what OnChoiceSelect is doing

#

but sure that's certainly an option as well

lapis ether
#

I'm not passing a keyCode into OnChoiceSelect as an argument

#

I'd need to convert it to an int anyway

#

Thanks all!

somber nacelle
#

also rather than manually checking against two digit characters to see if it falls in that range, you can actually just use the char.IsDigit method

lapis ether
#

s/o to @leaden ice

short osprey
#

So, i have a design question. i'm a regular non-game developer usually so forgive me if tthis is a stupid question.

i'm making a platformer with a grappling hook. Not everything is "hookable" and different objects react differently to being hooked (eg: pull the player towards it, pull it towards the player, fall down, etc.)

My first instinct is to create an interface as such:

public interface IHookPoint
{
  void ProcessGettingHooked(Vector2 origin);
}

This way every object knows how to act when it gets hooked. great. however thats also the issue: if the player is supposed to be pulled to this point, it would require the hooked point to instruct the player to move here, and i dont really like that design. it feels wrong andd breaks a coding principle too. i dont know a beter solution, though. Thoughts?

leaden ice
#
public class HookPoint : MonoBehaviour {

}```
#

it would require the hooked point to instruct the player to move here
Not necessarily

#

the player movement script can just look for if it found a. hook point and move itself there

weary swift
green ice
#

Hi guys,i am having a problem with an object,i want to make it rotate but it starts to rotate if i give him a lot of rotational force,how can i decrease it
the friction is set to 0

shell gate
#

Hello guys, I have an object that I want to rotate around another object but it just rotates around its own center and I don't know why. Does anyone have a solution please ?
Target is not at the center of the object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwordBehaviour : MonoBehaviour
{
  
    public Transform Target;
    void Update()
    {
        timer += 1 * Time.deltaTime * 75;
        if (timer >= 17)
        {
            Destroy(gameObject);
        }
        else
        {
             transform.RotateAround(Target.position, Vector3.forward, 340 * Time.deltaTime);
             transform.position = PlayerPosition.transform.position + new Vector3(-3, 0, 0);
        }
    }
}

swift falcon
kindred otter
shell gate
#

i made it rotate around the player because I realised I didn't need to make a child object and it still doesn't work (and the player is not at the center of the object btw)

#

no matter where it should rotate around it just spins

somber nacelle
#

not really a code question. it's more a question of where the pivot point on your sprite is. the sprite will rotate about its pivot when you rotate its object. so either give it a parent object that is centered on the point you want to rotate it around and rotate that object, or change its pivot point in the sprite editor

shell gate
somber nacelle
#

if you are rotating a parent object, then you need to adjust where the sprite object is in relation to the parent object

shell gate
#

ok thanks

#

it worked

short osprey
leaden ice
#

what kind of different actions do they need to have?

short osprey
# leaden ice what kind of different actions do they need to have?

My idea was to have the inferface IHookPoint to mark something as β€œhookable” and the script that implements the interface then knows how to act when it gets hooked. For example, blue hook points will pull the player to them, green ones will be pulled to the player, red ones will start falling after being hooked, greg ones may act even differently

leaden ice
cloud python
#

I think?

short osprey
#

Each different behaviour would be a unique script I assume. Why am I using a unique event per hookpoint instance though?

leaden ice
#

no?

#

you only want to react to this specific hook getting hooked, not to any hook getting hooked anywhere

short osprey
leaden ice
#

Imagine this:

public class GravityEnabler : MonoBehaviour {
  public Rigidbody rb;
  
  public void EnableGravity() {
    rb.useGravity = true;
  }
}```

Then you make a prefab called Red Hook with these components on it:
- Rigidbody
- HookPoint
- GravityEnabler

And on the HookPoint's UnityEvent you set up GravityEnabler.EnableGravity as the listener
#

Now you have a Red Hook prefab

#

Likewise you make scripts that do what the blue and green hooks need to do, and make prefabs for them with the HookPoint script and their other individual scripts, and use the event to hook things up

#

Now you have a very nice modular system that lets you very easily add new hook types without ever having to change any code for the HookPoint script or for the player's grappling hook script.

short osprey
leaden ice
#

You could even easily make a hook that mixes and matches mehaviors just by adding and removing scripts and listeners to the event

leaden ice
#

You could actually even do this if you don't want to use the inspector:

public class GravityEnabler : MonoBehaviour {
  public Rigidbody rb;
  
  void Start() {
    GetComponent<HookPoint>().onHook.AddListener(EnableGravity);
  }
  
  public void EnableGravity() {
    rb.useGravity = true;
  }
}```
short osprey
#

From what I understand, ur making a prefab that has an rb, a hookpoint (which i assume is a script) and gravity enabler (which im@not sure what its for)

leaden ice
leaden ice
#

I'm using your example from above of "red ones will start falling after being hooked"

short osprey
#

Ill admit ive not used UnityEvents just c# events

leaden ice
#

Same thing honestly

leaden ice
#

Jsut think of:

GetComponent<HookPoint>().onHook.AddListener(EnableGravity);```
like:
```cs
GetComponent<HookPoint>().onHook += EnableGravity;```
short osprey
#

So upon it touching you subscribe to the event and act it out

leaden ice
#

you could use a C# event if you want.

short osprey
#

Right

leaden ice
#

by touching the hook you invoke the event

short osprey
leaden ice
#

If you want

leaden ice
#

UnityEvent can be subscribed in the inspector, that's the main difference between UnityEvent and C# event

short osprey
#

My non-unity ass is imagining a method that subscribes to every single individual hook at a Start() call which seems.. off?

leaden ice
#

no of course not why would you do that

leaden ice
short osprey
#

Oh

#

Jesus im slow right now

#

Thiugh to move the player for blue or green hooks around another script is going to have to be notified, meanifn that script will also have to be subscribed to the event

leaden ice
#

You can really just pass whatever parameters you need as parameters in the event

#

if you need the player's Rigidbody for example to pull the player towards you (as a blue hook) you can pass that as a parameter in the event

short osprey
leaden ice
#

perhaps just passing in the "Grappler" as a parameter

#

If we look at the event as like:

public Action<GrapplingHook> onHook;``` where the parameter is the grappling hook (attached to the player) that started the action, we can do it pretty easily
short osprey
#

The question is bow do i get the reference

#

Does it come from the raycast that determines of the hook lands

#

The reference to the GrapplingHook objext o mean

leaden ice
#

we can subscribe with something like this:

void WhenHooked(GrapplingHook hooker) {
  StartCoroutine(ReelIn(hooker));
}

IEnumerator ReelIn(GrapplingHook hooker) {
  Rigidbody rb = hooker.GetComponent<Rigidbody>();
  // whatever you need to reel it in
}```
leaden ice
#

idk if you're using raycast

#

or collisions

#

or what but you can easily do like this for a raycast example:

if (Physics.Raycast(...)) {
   hit.GetComponent<HookPoint>().Hook(this);
}```
short osprey
#

Could be either, i havent implented it yet.

So youre suggesting the grapplinghook calls function? Events can only be fired from witbin the class thoug

leaden ice
#

which would look like:

  public void Hook(GrapplingHook gh) {
    onHook.Invoke(gh);
  }```
short osprey
#

I guess i overcomplicated it

#

But now why am I using an event at all since the gh already sees its target?

#

Oh

leaden ice
#

you don't have to care what is subscribed to those events etc

#

or about any other types of scripts

short osprey
#

Okay let me@mess around with this ill let u know if i get stuck or if it worked

#

Thank u a lot for ur help

static matrix
#

the words "may only be called from the main thread" have instilled great fear in my heart
how hard is the job system to learn?

rigid island
#

generally you cannot call unity API in separate thread

static matrix
#

yeah, and i needed to for this func
i was able to get around several errors by making wrapper vars that either dont change or just update framely but then it went happened for "querieshittriggers" (something along those lines) and thats a project setting so i cant wrap and reference right?

rigid island
#

have no clue what the specific setup for you is, what do you mean wrap and reference?

#

exactly why does this func need to be multi-thread?

static matrix
#

its for pathfinding, i cant have the game freeze whenever an enemy needs a new path

rigid island
#

did you actually profile and notice bottlenecks?

#

cause you could just run it "async" without dealing with multi-thread

#

depending how expensive

static matrix
#

thats what im trying

#

unless async funcs are just nonblocking even if i dont add await??

rigid island
#

async and multithread are different things btw

static matrix
#

oh

rigid island
#

common misconception

#

you can have async code be in the same thread

static matrix
#

i think async would work
just need it to be nonblocking

rigid island
#

yea thats what async does

#

doesnt block main execution

static matrix
#

ah i thought i also needed await

rigid island
#

await is part of async yes

static matrix
#

ah

rigid island
#

without await then it runs sync

static matrix
#

ahh
ok
how do i use await without task.run?

#

thanks for the help btw

rigid island
#

You need the method to be awaitable

#

usually Task

#

in unity's case you do Awaitable (2023+)

static matrix
#

shit
im on 2022

spring creek
#

They can be asynchronous (if you yield before the very end)

static matrix
#

im an idiot i forgot about coroutines😭

static matrix
#

ah for a coroutine i have to tell it when to wait for the next frame?

rigid island
#

it doesn't have to be waiting next frame

#

coroutines have more options because of custom YieldInstruction

static matrix
#

ah cool
but i cant just tell it to do the stuff and then give when done, however many frames ot takes?
or can i do that

rigid island
static matrix
#

i see
sorry im not sending code im on the bus and cant access discord from my computer

rigid island
static matrix
#

and is that non-blocking?

rigid island
#

nah they both wont block anything

#

its not like truly async cause its using some voodoo with IEnumerator, its just happening so fast

#

but yeah wont block other code at all

static matrix
#

oh its just yield return 0 instead of yield return null?
will that work?

rigid island
#

they both do the same thing

#

iirc null is better because 0 does allocation

#

i could be wrong

static matrix
#

ah
and if i need to return a value do i use out or can i return it normally

rigid island
#

tricky

#

I use an event usually

somber nacelle
#

coroutines cannot return values or use output parameters

rigid island
#

another reason why Tasks are the goat

static matrix
#

oh wait i can have the coroutine call the thing that returns something instead of having the thing that returns something be a coroutine

rigid island
#

or am I misunderstand wat you're doing

static matrix
#

the thing that returns is doing the heavy lifting
its building a path

rigid island
#

just invoke an event no ?

#

OnPathGenComplet?.Invoke(thePath)

#

or som

#

what does it return anyway

static matrix
#

lets gooo fourth different async thing
i dont know events but ive bothered you long enough so ill look into it

somber nacelle
#

events are not async

static matrix
#

list of objects, i mean

rigid island
#

event is just for saying "Yo this async task finished, here is the data "

#

nothing related to async

#

just for you to say , hey something happened here

somber nacelle
#

you don't even necessarily need an event either. you can just pass a delegate to the coroutine and invoke it. doing this is referred to as a callback

rigid island
#

oh yeah . smart

#

eg you can pass Action or Func

static matrix
#

ah i see
ill try that then

rigid island
#

i do that for custom timers using the same coroutine

static matrix
#

ok at computer

 public IEnumerator AssignNewPath(Vector2 ToWhere){//Now assign the path creaetd
            Target = ToWhere;
            ClosestNode = AllNodes.FindClosestOfType(transform.position);
            TargetClosestNode = AllNodes.FindClosestOfType(Target);
            ClosestNodeIndex = 0;
            var PosPaths = new List<List<PathingNode>>();
            for (int i = 0; i < 25; i++)
            {
                 var ThisPath = CreatePath();
                 PosPaths.Add(ThisPath);
                 yield return null;
            }
            Path = FindBestPath(PosPaths);
           

            NextNode = ClosestNode;
            
    }

like this? (ignore the very shoddy pathfinding stuff, ill work on optimizing it next)

#

ah moved the yield to the end
seems to have worked

leaden ice
#

if you only have a yield at the end and nowhere else, there's no reason for it to be a coroutine

static matrix
#

well it wasn't actually at the end, it was right before nextnode

#

but yeah ill fandangle it around

#

seemed to have worked

gusty aurora
#

Is there any counterindication to using StopCoroutine on a Coroutine that already finished its execution ?

waxen blade
#
            if (foo.EnemyData.loot != null)
            {
                lootList = foo.EnemyData.loot;
            }
            else if (foo.RareEnemyData.loot != null)
            {
                lootList = foo.RareEnemyData.loot;
            }
            else
            {
                Debug.LogWarning("Enemy has no loot!");
            }

I'm attempting to check to see if an object has a value. I already know that between the two options, EnemyData and RareEnemyData, one of them is going to be null. Normally when I check if something is null, it'll simply not run the code inside if it's null.

In my case, it's generating an exception even though I already know one of these objects is null. I'm not sure why it's behaving differently from other times where I'm checking to see if something is null. I've never had an exception when checking for null.

Is a different way I should be handling this?

somber nacelle
#

if you are receiving a NullReferenceException on one of these lines then foo or foo.EnemyData or foo.RareEnemyData is null
also why is RareEnemyData a separate property? shouldn't RareEnemyData inherit from EnemyData and just be assigned to the EnemyData property so you aren't unnecessarily checking a bunch of different properties?

waxen blade
#

In this case I know foo is not null since I ran it through the debugger.

As for inheritance, I didn't know it was an option in this case. It has been a confusing concept for me so I don't use it outside of scriptable objects or monobehaviours.

somber nacelle
#

anyway, the issue is likely that foo.EnemyData is null

waxen blade
# somber nacelle anyway, the issue is likely that foo.EnemyData is null

Yes, it is null. But I thought if I checked to see if it was null ahead of time, it wouldn't throw an exception. For example, I try checking to see if gameobjects are null sometimes, and when they are, it doesn't throw the exception, it just doesn't run the code. That's the kind of behavior I was expecting.

somber nacelle
#

you're not checking if it is null though

#

you're checking if its loot variable is null, which means that EnemyData cannot be null in order to access that variable

waxen blade
#

Okay, so I should be checking to see if foo.EnemyData != null

somber nacelle
#

yes

waxen blade
#

Not foo.EnemyData.loot

#

Interesting behavior, I didn't think it cared about that distinction.

somber nacelle
#

of course it does. that's the whole point of that exception. you are trying to access something on a null object

waxen blade
somber nacelle
#

yeah then RareEnemy should inherit from Enemy. then you only need that extra field in its declaration instead of just copying everything from Enemy into it

#

then you only need the one field that can reference either kind of SO

waxen blade
#

The exception is no longer occurring.

As for the scriptable object, this sounds a great opportunity for me to utilize inheritance since it directly applies to my use-case. Thanks for your help boxfriend.

molten vector
#

edit: fixing file format

somber nacelle
#

based on the bit of the description i was able to read before you deleted that, it doesn't sound like a code issue. but does sound like you've messed up your camera clearing flags

molten vector
#

gotcha

#

gonna change it to an mp4 so it's viewable in discord desktop

#

nvm my computer is being too slow, thanks for the help though i'll see if that does anything

somber nacelle
#

if you recorded it in obs with the default codecs selected then you can just change the extension to mp4 and it should work

molten vector
#

as it probably isn't a code issue where should i go for further help if necessary?

somber nacelle
craggy oyster
#

hey whats the difference between virtual and abstract when overriding

static matrix
#

virtual you do not have to override, abstract you do

somber nacelle
dusk apex
static matrix
#

seems most most of the bottleneck is coming from me raycasting to check if a position is valid
is there like a way to check if theres something in between two points without a raycast?

dusk apex
somber nacelle
#

raycasts are incredibly cheap. so cheap that you can do over 1000 of them in under 1ms

craggy oyster
#

thanks

static matrix
#

hmm
okay
maybe i should check profiler again then
it was boxcast before so I changed it to raycast and that didn't seem to help

#

ill check in a little bit

#

ouh I was using linecast
let me try raycast instead

somber nacelle
#

i doubt that would impact the performance in any meaningful way. use the profiler to determine where performance is being impacted the most

clear umbra
#

Can someone tell me whats going on with my LineRenderer?

For some reason when I taper the line width to 0 at the end it looks like the UV coordinates on the material don't line up with the outline of the line?

#

First photo is the error second photo is expected material but without the tapering of the line width at the end

#

I'm using shader graph to build my material, but I have 0 clue on why the UV coordinates looked skewed on the line renderer

static matrix
#
  public static T FindClosestOfType<T>(this IEnumerable<T> ListOfPos, Vector3 MyPos) where T :MonoBehaviour{
        
        T ClosestPos = null;
        float ClosestDist = Mathf.Infinity;

        foreach (var item in ListOfPos)
        {
            if(Vector3.Distance(MyPos, item.transform.position) < ClosestDist){
                ClosestDist = Vector3.Distance(MyPos, item.transform.position);
                ClosestPos = item;
            }
        }
        
        return ClosestPos;
    }

what are some ways I could optimize this function? it is searching through thousands of objects scattered uniformly around the map many times in a forloop in the implementation that is hurting perf, so I thought maybe something like autoexcluding things more than 50 or 20 units away?

#

ah but then i'm just doing the function twice and iterating through it less the second time

modern creek
#

Distance() is expensive because of some square root stuff inside it, so some ideas:

  • Put every object in a "chunk grid" and then only check items that are in the adjacent chunk grids (assuming you don't need to check items "50 or 20 units away".
  • Don't check as often. Perhaps every few seconds or more.
  • Keep the items in distance order, if your player doesn't move every frame - ie, if your player takes a turn and moves, then resort the items in this list at that time.

You could also make this quite a bit easier to read (and maybe less bug-prone) with:

public static T FindClosest<T>(this IEnumerable<T> items, Vector3 position) where T:MonoBehaviour
{
  // TODO: put some error checking in here - ie, items.count > 0
  
  // One line versus 10
  return items.Min(x => Vector3.Distance(x.transform.position, position));
}
static matrix
#

ah
lambda
I see
is the lamda version faster or nah

modern creek
#

pretty much exactly the same, but much less code (which, if you're doing stuff like this regularly, means less bugs because you forgot something like initializing a variable)

quaint rock
#

its just doing what the loop is doing

#

the lambda with linq here is really just a shorthand

modern creek
#

tbh maybe slower than writing a low level version yourself but it's gonna be much easier for you to improve this elsehow

#

you could also add the aggressive inlining to the method

lean sail
#

Using the sqrMagnitude should also help here

quaint rock
#

also if you are just wanting the cloesest object you can make it cheaper by not doing distance

modern creek
#
 [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T FindClosestOfType<T>(this IEnumerable<T> ListOfPos, Vector3 MyPos)
quaint rock
#

if you don't care about the distance and am just comparing one to the other sqrMagnitude avoides a sqrt per iteration

modern creek
#

Vector3.Distance already does the square root stuff

quaint rock
#

but also i would say if what you got works, move onto the next problem

modern creek
#

and actually, now that I check, also already does the aggressive inlining

quaint rock
modern creek
#

oh i see, sorry

static matrix
#

well it works, but the issue is when im running it a lot which im ending up doing is costing a ton of performance

quaint rock
#

is it, did you profile it

modern creek
#

well then run it less πŸ™‚ that's gonna be your immediate impact

quaint rock
#

are you running it more then required, like doing this once a frame should be fine unless you got like hundred thosand objects to iterate

modern creek
#

you probably don't need to run it at max fps - run it once per 1-2 sec and it's probably gonna be pretty close to the same experience for the player, depending on what it is you're doing

lean sail
#

I think the sqrMagnitude here will drastically improve things though I have doubts that even thousands of these are causing noticeable lag

static matrix
#

ill try sqrmag

quaint rock
#

(b - a).sqrMagnitude

static matrix
#

wait
i may be
an absolute moron

#

it is possible
that I was calling this like an additional 100k times

quaint rock
#

well cant say without extra context

#

there are many ways to optmize it btw

#

expecially cases where you do not care abut stuff more then x units away

#

and just want the cloesest within a limited range

static matrix
#

well it would be closest within limited range simply because the objects typically being searched are so numerous

#

so its such that there will always be one nearbye

quaint rock
#

so could do like a Physics.OverlapSphere first to get the ones that are realyl close first

#

then the the minby

#

also (b - a).sqrMagnitude will save 1 sqrt per iteration

steady moat
rain minnow
# static matrix ```cs public static T FindClosestOfType<T>(this IEnumerable<T> ListOfPos, Vect...

why are you running the distance check twice? store it the first time, then assign it if the shortest. only pass in the position, instead of the transform reference, it'll be faster. as everyone else stated, run the method on every X tick/second (on a timer) that you can increase or decrease. i would grab GameObjects and place them in a collection and pass that to limit the amount of objects searched . . .

summer oar
#

what am I even looking at here aaaaaaaaaaaaaaa

cosmic rain
summer oar
#

It just goes on and on drilling into internal Unity canvas code

cosmic rain
summer oar
#

yeah

#

I had to do another profile but

#

I expanded the hierarchy

#

seems I'm getting a giant Layout spike

#

I know it happens when instantiating this prefab

humble iron
#

Hello! I have a question, and i don't seem to find the answer for my specific case so that's why i'm asking here.

I'm going straight to the point: I want to smoothly rotate a gameobject using inputs,

The code i currently have is this

private void HandleRotation(){
        Quaternion inputRotation = Quaternion.Euler(new Vector3(_rotationX, _rotationY, _rotationZ));

        rb.rotation = Quaternion.Slerp(rb.rotation, rb.rotation * inputRotation, rotationSmoothness);
    }

_rotationXYZ variables are receiving values between 1 and -1 from InputSystem.CallbackContext ReadValue functions.

This doesn't work as i expect it to work, since it doesn't smooth the final rotation no matter what i do. Am i overlooking something or doing something wrong? Any help is greatly apreciated.

#

Or maybe it is working but the values that Slerp is working on are too small to notice, if that's the case, there's something else i can do to achieve smooth rotation?

calm talon
#
tilemap.CompressBounds();
(int, int) dimensions = new();
(int, int) store = new();
List<Vector3Int> tilePositions = new();
foreach (Vector3Int vect in tilemap.cellBounds.allPositionsWithin) 
{
    if (tilemap.GetTile(vect) != null) 
    {
        foreach (Vector3Int otherVect in tilePositions) 
        {
            Vector3Int relativeVect = vect - otherVect;
            if (Mathf.Abs(relativeVect.x) > Mathf.Abs(dimensions.Item1))
            {
                dimensions.Item1 = relativeVect.x;
                store.Item1 = otherVect.x; 
            }
            if (Mathf.Abs(relativeVect.y) > Mathf.Abs(dimensions.Item2)) 
            {
                dimensions.Item2 = relativeVect.y;
                store.Item2 = otherVect.y; 
            }
        }
        tilePositions.Add(vect); 
    }
}

I have this code to find the centre point of a tilemap's boundaries (where the bounds are a rectangle that encases every tile within the tilemap, i.e. tilemap.size), is there any faster method for finding the centre point?

fervent furnace
#
Vector3Int relativeVect = vect - otherVect;
if (Mathf.Abs(relativeVect.x) > Mathf.Abs(dimensions.Item1)){
    dimensions.Item1 = relativeVect.x;
    store.Item1 = otherVect.x; 
}
if (Mathf.Abs(relativeVect.y) > Mathf.Abs(dimensions.Item2)) {
    dimensions.Item2 = relativeVect.y;
    store.Item2 = otherVect.y; 
}
```you are trying to find the largest differences between two vector2int?
calm talon
fervent furnace
#

how you get the "center"? also consider use vector2int

(int, int) dimensions = new();
(int, int) store = new();
```(store+dimensions)/2?
calm talon
#

dimensions / 2 + store

calm talon
#
tilemap.CompressBounds();
Vector2Int store = new();
List<Vector3Int> tilePositions = new();
foreach (Vector3Int vect in tilemap.cellBounds.allPositionsWithin) 
{
    if (tilemap.GetTile(vect) != null) 
    {
        foreach (Vector3Int otherVect in tilePositions) 
        {
            Vector3Int relativeVect = vect - otherVect;
            if (Mathf.Abs(relativeVect.x) > tilemap.size.x)
                store.x = otherVect.x; 
            if (Mathf.Abs(relativeVect.y) > tilemap.size.y) 
                store.y = otherVect.y; 
        }
        tilePositions.Add(vect); 
    }
}

here's the cleaned up code

fervent furnace
#

pair wise comparison sounds weird to get the "center"
isnt it is the same as just using the bound/2+one corner

#

to maintain a bound of (A,B) there must be two points with x difference >=A and y difference >=B otherwise the bound will be collapsed to (A-1,B-1) or or (A,B-1) or (A-1,B) smaller

fervent furnace
calm talon
#

oh neat

#

I didn't realize that's what Tilemap.origin referenced

#

I thought it was the tilemap's world position in cell coordinates

summer oar
#

It's my game's content manager

#

It loads a bunch of content using Resources.LoadAll<T>()

#

I need to find a way to do that asynchronously

#

I guess I gotta switch to asset bundles

west lotus
#

Addressables would be the way to go yes

ocean hollow
#

i recently updated my vs and it updates != to the not equals symbol. can i make it so that it just displays != like normal instead?

ocean hollow
#

where do i find that? πŸ˜…

#

i cant seem to find a tutorial for vs, all i see is for vs code

ocean hollow
# golden wave jsut ask chat gpt

it gives me made up info a lot of times so i didnt bother, but i would be careful recommending that on this server because it actually goes against community conduct πŸ˜…

golden wave
#

I didn't post any AI generated responses
I just told you chat gpt is usually pretty good at telling you where to find a setting

ocean hollow
#

yes but ive seen mods warn people for recommending AI generated respones to questions

summer oar
#

though...

#

the dropdown ain't showing πŸ˜›

#

I was able to get asset bundles working and added one asset to it. But the moment I tried to add more, I noticed that.

devout topaz
#

hi
i have this component on the camera from the asset store
I was wondering how to change it's variables values from another script

fervent furnace
#

not code general
get the reference to this component and check the docu/ask the author about the api provided

quartz folio
hearty mortar
#

Error:

MissingMethodException: Method 'StarterAssets.ThirdPersonController.OnJump' not found.
System.RuntimeType.InvokeMember (System.String name, System.Reflection.BindingFlags bindingFlags, System.Reflection.Binder binder, System.Object target, System.Object[] providedArgs, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParams) (at <e307bbb467104258887a104f6151f183>:0)
UnityEngine.SetupCoroutine.InvokeMember (System.Object behaviour, System.String name, System.Object variable) (at /Users/bokken/build/output/unity/unity/Runtime/Export/Scripting/Coroutines.cs:30)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr) (at /Users/bokken/build/output/unity/unity/Modules/Input/Private/Input.cs:120)

Code snippet:

namespace StarterAssets
{
/* ... */
    public class ThirdPersonController : MonoBehaviour
    {
/* ... */
        private void OnJump(AnimationEvent animationEvent)
        {
            // the square root of H * -2 * G = how much velocity needed to reach desired height
            _verticalVelocity = Mathf.Sqrt(_jumpHeight * -2f * _gravity);
        }
/* ... */
    }
}

Code file attached. Anyone have a clue what is going on? I'm completely lost. Reverting to a known working copy of the code also didn't work.

quartz folio
#

I presume you can't use Invoke on something that takes an argument, your input system should be set up differently

hearty mortar
#

Pressing the jump button runs Jump(), which starts the animation, which triggers OnJump() at the correct time

quartz folio
hearty mortar
#

Huh, let me try that. The original script had private receivers for footstep sounds, which seemed to work, but maybe it'll fix it

quartz folio
#

It also seems slightly suspicious that it says "StarterAssets.ThirdPersonController.OnJump"

#

surely it should say "OnJump"

hearty mortar
#

The textbox for the animation event only says OnJump

#

It's just the error which says the fully qualified name, which... I mean, StarterAssets.ThirdPersonController is in fact the class in question

#

Made it public, same error

quartz folio
#

You're absolutely certain this is coming from an Animation Event? It mentions the input system, which makes me suspicious that it's unrelated

hearty mortar
#

Oh. See... this is why in web dev land we have nice annotations for listener methods, rather than just finding them by name. It's a name conflict. OnJump is also the name of a method in the input script on the same object

#

Not sure why that was working before, but easy to resolve now

quartz folio
#

I mean, this is only the lazy and mostly unused way of setting up the input events

#

Usually it would be much more strongly referenced

hearty mortar
#

Hm? I just left the input events untouched from the Starter Assets package

quartz folio
#

Yeah, their setup is the lazy way of doing it 🀷

hearty mortar
#

Good to know

#

@quartz folio So I just restricted that. Is there a way to similarly restrict the animation event, or do I definitely have to resolve the name conflict?

#

Since now the animation event is trying to call the method in the input handler

hearty mortar
#

Hm. I guess... longer term, I should write some sort of dispatcher script for animation events on a seperate object and have them all target it for dispatch

#

And then I can just attach listeners to that script instead

#

For now I'll just rename the method haha

#

Never fix today what can instead be fixed tomorrow.

scarlet viper
#

is pooling for input in Update and executing it in FixedUpdate not accurate?
I detect RMB up in Update(), but the variable isnt always synced in fixedUpdate.
Lets say i release up button, cache this bool in Update(), then it will fire in FixedUpdate only 70% of time

pastel holly
#

Anyone knows anything about VideoPlayer in unity?
I have MP4 video:

when I run VideoPlayer.Play()
it seems to get on first frame on Galaxy 21(tried executing mp4s as standalone on device and that works fine),
I tested it with other phones: galaxy 20, galaxy 20 pro, pixel 7a, A6, worked fine. (works well on PC/editor)

soft shard
#

This might depend on how your spawn logic works/what fires your spawn logic, one option could be to only allow spawning when you are connected to a lobby, and have your lobby connection logic load your relevant waiting scene, another option could be to maybe use a event or game state and only allow spawning from your manager when the game is in a particular state, this way your lobby scene can decide when the state changes (such as on a scene change, RPC, etc)

#

No need to DM if you need help, you can just ask here

#

You can use !code to create a codeblock or a code paste link so its a bit easier to read

tawny elkBOT
soft shard
#

Scene loading can take time so you could be facing a race condition - you can try to spawn your player after the scene has loaded, you can use SceneManager to hook into events to know when the active scene has changed and/or loaded the next scene

umbral radish
#

How can I use Rider with Unity on Mac?

mossy snow
#

are you having some kind of problem? the steps are

  1. install rider
  2. install jetbrains rider editor package from package manager
  3. set rider in external tools as your external script editor
umbral radish
#

Is there no plugin for Rider?

mossy snow
#

plugin where? in Rider? Unity support is bundled in already

lunar python
#

Hi everyone, I have a small questions regarding the Unity animator in Online games. Are the parameters stored locally on player's end? I don't want players to be able to modify params that controls codes through animator, which is very silly

vagrant blade
#

Everything is stored locally. Unity doesn't do online for you.

#

Players can change and modify anything they want client side, unless you handle the logic serverside.

opal pine
#

Hey guys. Is there a way to dynamically change a text colour half way through depending on a if statement?
e.g.

"Cash: $" + money + "\n<color=underAmount>Total Water: " + water + "/" + waterNeeded + "</color>"

then change the color underAmount else where to update the text? Can't seem to find much online

fervent furnace
vagrant blade
#

@errant shore You've been told before not to crosspost

opal pine
fervent furnace
opal pine
#

I'm gonna have to create 4 separate texts so I can do a check and apply a colour.
Thanks anyways. Wasnt sure if it was possible

upper pilot
#

How can I access a child class by using its Instance(Singleton)?

public class BaseCharacter : Singleton<BaseCharacter>
{
}

public class PlayerCharacter : BaseCharacter
{
    public void Move(Vector3 dir) {}
}

public class PlayerInput : MonoBehavior
{
    private Vector3 MoveDirection;
    void Update()
    {
        PlayerCharacter.Instance.Move(MoveDirection);
    }
}

This won't work unless I cast PlayerCharacter.Instance to PlayerCharacter.
Is there a clean way of doing it?

#

Instance is pointing to BaseCharacter class, so I can't access Move function.

fervent furnace
#
public class A{
    public virtual void Method(){
        Console.WriteLine ("i am A");
    }
}
public class B:A{
    public override void Method(){
        Console.WriteLine ("i am B");
    }
}
public static void Main(string[] args){
    A a=new B();
    a.Method();
}
upper pilot
#

ah that makes sense

#

thanks πŸ˜„

soft shard
opal pine
#

I can set it to red but I cant dynamically set it to what colour I want outside of the string. E.g. setting a if statement

fervent furnace
#

you need to rebuild the string if you want to set some words of them to be different color

upper pilot
#

or rather can I make a class that extended from Base class have its own static Instance?

#

otherwise I have to do this:

    private void SetPlayerPosition(Vector2 exitPosition)
    {
        PlayerCharacterController playerController = PlayerCharacterController.Instance as PlayerCharacterController;
        playerController.SetPosition(exitPosition);
    }
fervent furnace
#

instance is a reference to base class, static is just a modifier
maybe you can try the second

upper pilot
#

I am already using static Instance

leaden ice
#

They solve this problem easily

#

(with generics)

upper pilot
#

I already have it, but I might be using it wrong?

#
public class CustomCharacterController : PersistentSingleton<CustomCharacterController> {}

public class PlayerCharacterController : CustomCharacterController {}
leaden ice
#

You'd have to show the implementation of PersistentSingleton

upper pilot
#
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance { get; private set; }
    protected virtual void Awake() => Instance = this as T;

    protected virtual void OnApplicationQuit()
    {
        Instance = null;
        Destroy(gameObject);
    }
}

public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        if (Instance != null) Destroy(gameObject);
        base.Awake();
    }
}

public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        base.Awake();
        DontDestroyOnLoad(gameObject);
    }
}
leaden ice
#

Yeah that looks fine

#

Should work out of the box

#

No need for the cast

upper pilot
#
CustomCharacterController' does not contain a definition for 'SetPosition' and no accessible extension method 'SetPosition' accepting a first argument of type 'CustomCharacterController' could be found (are you missing a using directive or an assembly reference?)
CustomCharacterController.Instance.SetPosition(exitPosition);
#

maybe because its internal?

#

no difference

leaden ice
#

No because you did a Singleton<CCC>

upper pilot
#

right

leaden ice
upper pilot
#

Whats PCC?

leaden ice
#

PlayerCharacterController

upper pilot
#

But how do I do that?

#

let me explain my goal

leaden ice
#

If you need it to also be a child of CCC

#

You need to make CCC also generic

upper pilot
#
public class CustomCharacterController : PersistentSingleton<CustomCharacterController> {}

public class PlayerCharacterController : CustomCharacterController {}
public class NpcCharacterController: CustomCharacterController {}
#

Well its just that really

leaden ice
#

Too much inheritance though methinks

leaden ice
#

It's not adding anything

upper pilot
#

it has functions that both player and npc needs

#

should I just make it into a separate component instead?

leaden ice
#

Sounds like a case for composition rather than inheritance

upper pilot
#

and do "requireComponent"

leaden ice
#

Yeah

upper pilot
#

Sounds good, I will do that then πŸ˜„

tepid brook
#

Hi guys i use 2 editor with clone to test a network project but when i am on an editor he is like slow and its same with a build.
I have checked Run in background

tepid brook
gray mural
#

I don't fully understand your issue

tepid brook
#

Game low fps i think is a windows issue like he slow down background process

tepid brook
lethal burrow
#

I have a question about Awake(), I am trying to test ads on my game with an ad manager and I try to initialize the ads on awake and I put debug.log lines in there to see if it is successful yet when I run my game it just skips that part

cosmic rain
lethal burrow
cosmic rain
knotty sun
lethal burrow
cosmic rain
#

Oh, if it's not a build it should be even simpler than that.

lethal burrow
cosmic rain
#

Attach a debugger and place a breakpoint in the awake method. See if it breaks. If it doesn't then the script is either not in the scene or is not enabled.

#

So you only debug if the ads are initialized and supported. They are definitely not supported in the editor, and I'm not sure if they get initialized as well.

lethal burrow
#

I am new to the whole ads stuff so I do not know what I am doing wrong here

#

I followed a tutorial on youtube

#

the current build platform is android by the way

cosmic rain
#

Does the tutorial tell you to put a debug log there and that it would print in the editor?

lethal burrow
#

no the tutorial does not have the debug.log line in awake() I put that there when I realized that my ads do not initialize

cosmic rain
#

And supported?

lethal burrow
#

yes

#

but I found out why it did not work

#

I for got an ! in
if (!Advertisement.isInitialized && Advertisement.isSupported)

#

when I put that it all worked out

#

thank you for your help

#

I feel stupid now for missing that part

cosmic rain
#

Ah I see. You initialize it iniside.

gusty quail
#

is it optimal to use playerprefs to save player data

lethal burrow
cosmic rain
knotty sun
gusty quail
#

thought so, thanks

gusty quail
cosmic rain
knotty sun
subtle basin
#

I have an icon object whose sprites I change. I want to add upgrade, with which you can inspect sprites by clicking on them with the mouse and do some actions when you find an Easter egg on a sprite. How to store associations between the existence, position and size of an Easter egg and a sprite to set a clickable collider?

past kite
#

Is there an extension to NavMeshAgent that lets one use your own physics to get from one waypoint to the other. Basically, I want Nav to give me the next way point, and I'll look how to get there.

The reason: I want to use a double PID controller (x and y) to simulate different movement characteristics of enemies. I don't want to implement path planning though.

somber nacelle
exotic kelp
#

erm I'm having this very weird issue where the physics on my player gets weird and sloppy when I add a audio source to another object. Does audio source affect physics or is unity tweaking right now

leaden ice
#

what do you mean by "weird and sloppy"?

exotic kelp
#

wait i can show

#

Ok so the beginning is without audio source and the second is with audio source. Im going to the side all the time but i get slowed down everytime the ball hits when audiosource exsists

leaden ice
exotic kelp
#

I'm not professional with coding but what method can be used to fix this?

leaden ice
#

The "method" would be to look at and analyze your code for things that are framerate-dependent and resolve those things.

exotic kelp
#

ok thanks

static matrix
#

if I check transform.parent and it is a child but several levels up, does that return true?
like
if C is child of B child of A, and I check if A is the parent of C
is that true or no

#

seems not

static matrix
#

dang
is there an easy way to check for that?

summer oar
#

Is it possible to tell Unity to never include a specific object type like

public abstract class EvilObject : ScriptableObject
{

}

in asset bundles, and instead just let it keep assets of this type in the normal game build?

static matrix
#

not specifically grandparent, but just "is ancestor"

#

what are asset bundles anyways?

gray mural
# static matrix not specifically grandparent, but just "is ancestor"

I doubted whether there was a built-in method for that, but now I found the Transform.IsChildOf.

true if this transform is a child, deep child (child of a child) or identical to this transform, otherwise false.

Still, I wonder whether the "deep child" may also include the "ancestor", not just a child of a child. You gotta test it out. If in this case it returns false, you may want to impelement your own method by enumerating thru the child's parents until you, perhaps, find the one needed.

vapid lynx
#

Im tryign to rotate "attack opint" around my cannon game object

#

but its spinning weirdly like that

#
float rotationAngle = Vector3.Angle(direction, cannon.transform.forward);
attackPoint.transform.RotateAround(cannon.transform.position, Vector3.up, rotationAngle);```
leaden ice
mystic jetty
#

Is there a way to reference a Script/Class instead of an instance of it?

#

so basically referencing a type rather than an object of type

leaden ice
#

Why do you ask?

#

What are you trying to do?

mystic jetty
#

I have a class which all of my game's abilities inherit from.
I want to be able to keep references to those abilities, then add those abilities to characters

leaden ice
mystic jetty
#

so for example Fireball inherits Spell class. I want to keep a reference to Fireball then attach the Fireball component to the player.

leaden ice
#
Type fireballType = typeof(Fireball);

myPlayer.gameObject.AddComponent(fireballType);```
mystic jetty
#

exactly!

#

thats what I'm looking for.

#

Google just kept giving me how to reference objects.

#

Thank you I appreciate it

leaden ice
#

I kinda feel like having your spells be MonoBehaviours isn't exactly the greatest pattern, but this can work in a way.

#

You'll have to jump through a few more hoops to actually interact with it nicely

#

E.g.

Type fireballType = typeof(Fireball);

BaseAbility baseAbility = (BaseAbilityClass)myPlayer.gameObject.AddComponent(fireballType);
basedAbility.Use();```
#

as a dirty example of how you'd actually call functions on it

mystic jetty
#

I made them MonoBehaviors because they don't have a strict pattern that they follow. One can be a simple stat upgrade, while another ability can spawn things around the player.

vapid lynx
#

Im trying to shoot bullets in the direction attack point faces but they keep shooting forward only

leaden ice
#

it should be target - source

#

and if you wanted "the direction attack point faces" that would just be attackPoint.transform.forward

#

so just: Vector3 directionWithoutSpread = attackPoint.transform.forward;

vapid lynx
#

hood up

#

yeah it still does that 😭

leaden ice
#

get rid of it for the moment

#

Vector3 directionWithSpread = directionWithoutSpread;

#

just do this right now

vapid lynx
leaden ice
#

yeah but you did this: directionWithoutSpread + new Vector3(x, y, zOffset);

#

it's adding some z offset

#

which is going to tend to make it shoot forward

vapid lynx
#

oh

leaden ice
#

even if x and y are 0

vapid lynx
#

wait z offset was also 0

leaden ice
#

the better way to do spread is to rotate the vectors

#

just try disabling all this

leaden ice
vapid lynx
#

yeah

solid slate
#

Is quaternion.identity 0,0,0 or just the objects rotation

leaden ice
#

numerically it's 0, 0, 0

#

but if you do like transform.localRotation = Quaternion.identity; then it will get the same rotation as its parent, for example

solid slate
#

Ohh

#

Ok that makes sense

fervent coyote
#

Would raycasting to make sure there is no obstacles are in front of my NPC, or spherecasting in "front" of my NPC be faster? It would check every 20 frames, and if there is something in front of my character, find a way around it

spring creek
fervent coyote
#

I ask cause my NPC doesn't seem to register walls sometimes...

dusk apex
#

Are you moving using RB?

fervent coyote
#

CharacterController

spring creek
leaden ice
#

or the frequency

#

Or perhaps your other code

fervent coyote
#

I'm using Raycasting currently

spring creek
#

It would be the same issue with ray or sphere

#

If you want more help, show the code

fervent coyote
#

Oh wait, I think I discovered an issue

#

It didn't include the character controller's radius into the calculations

lunar python
#

is there anyway of getting array of vertices of a composite collider 2d inside a trigger zone?

#

i dont want to iterate through thousands of vertices each seconds because the entire ground is a composite collider

rugged storm
leaden ice
#

ALso, definitely not a code question

rugged storm
rugged storm
#

playing with the number doesn't seem to do much, maybe i should ask in #archived-shaders or just find a simpler health bar solution so I'm not mixing meshs and sprites;

leaden ice
#

yeah IDK, it would be something with the shader probably

#

might need to share the shader code even

topaz sapphire
#

anyone have any idea why this timer float doesnt reset to 0? ```f (other.CompareTag(activatorTag))
{

        other.GetComponentInChildren<UiManager>().interactMessage = intMessage;


        if (other.GetComponent<InputManager>().interactFlag)
        {
            timer += Time.deltaTime;
            if (preOwned)
            {
                if (timer >= timeToOpen && other.GetComponent<PlayerDataManager>().canAfford(ammoPrice) && weaponDataHolder.currentAmmo != weaponDataHolder.weaponData.maxAmmo)
                {
                    timer = 0;
                    weaponDataHolder.currentAmmo = weaponDataHolder.weaponData.maxAmmo;

                }
            }
            else {
                if (timer >= timeToOpen && other.GetComponent<PlayerDataManager>().canAfford(buyPrice))
                {
                    timer = 0;
                    weaponHolder.getWeapon(buyGun);

                }
            }
        }```
#

it should as the code on the lines underneath get called

cosmic rain
topaz sapphire
cosmic rain
#

If that's true, then the only other option is that it's reset to a different value somewhere after being reset to 0

topaz sapphire
cosmic rain
#

You won't believe how many people said "I don't need to confirm" just to be proven wrong in the end...

#

"I don't need to confirm" is basically a major sin for a developer

#

people should be prosecuted for that if you ask me πŸ˜„

topaz sapphire
#

dont give me the three dots man, I know my code works because there are gameplay flags

cosmic rain
#

Can't help you further if you can't make a simple confirmation

topaz sapphire
#

dont act so condescending when youre "trying" to help someone

cosmic rain
#

Ok, not gonna try to help you then.

topaz sapphire
cosmic rain
#

At least I didn't start calling names and being rudeπŸ€·β€β™‚οΈ
I don't know what made you so offended in my messages. There's was really no intention to offend anyone. But there're some requirements for you to receive help here, just so you know.

topaz sapphire
smoky plover
#

hey I'm kinda new to game development, and i wanna make a game. i have a basic idea what the game is named and the stuff that's going to be in it, i just need help trying to figure out how to 3d model and all that. i have it all in a google doc i just need help learning to code or help making the game in general. I'm very new to coding but i have teached my self some stuff. any help would he appreciated.

topaz sapphire
cosmic rain
tawny elkBOT
#

:teacher: Unity Learn β†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

smoky plover
#

Thanks Guys

topaz sapphire
#

(uneccesarily spending points while standing inside of the detection box)

quartz folio
topaz sapphire
# quartz folio They have made reasonable suggestions to confirm your assumptions and have said ...

I already told the dude there were onscreen flags. Hell I even humored him and put in the debugs he asked for and it was the same effect as the onscreen flags. Still no explanation on why the timer wont reset, I just worked around the fact it wont and made use of out it. There wouldnt be a problem with me if he actually wasnt jerking off his ego as he was. exclaiming stuff like "Can't help you further if you can't make a simple confirmation" and " I don't need to confirm" is basically a major sin for a developer
people should be prosecuted for that if you ask me πŸ˜„" isnt helpful. He should at least know how to use the english language in a manor that doesnt look down on others.

spring creek
quartz folio
#

!warn 419646589808803850 also I've just noticed you've decided to call someone a nonce. At no point did you ever humor them in this channel, and just decided to namecall. Don't continue with this shitty attitude.

tawny elkBOT
#

dynoSuccess naidiac has been warned.

topaz sapphire
#

yeah man this server is great I love getting help from people who cant dare speak without stroking thier ego

quartz folio
#

You are welcome to leave if you're going to continue like this

solid slate
#

πŸ’β€β™‚οΈ 🍿

edgy stump
#

Yooo what happened? :(

gray mural
wintry gust
#

Is there a way to stop all Audio Clips from triggering? I thought AudioListener.pause was what I was looking for, but that just halts them until the listener is unpaused. It doesn't actually stop the triggers.

gray mural
leaden ice
spring creek
simple ridge
#

Hi all, I was wondering if someone could point me in the direction for assigning a custom windows tab layout in the editor. I'm working on a analysis tool for a project to playback player data and would like to add a timeline to the bottom of the scene view.

Right now I have a secondary window opening for this timeline on opening the analysis custom editor window, but it currently appears as a hovering element. I have seen online that you can pass in another window to make them share a tab but I would like to have it be visible below the scene view so I would need to add a new tab in this location.

This is what I cant seem to find any info on, if anyone has an idea I would appreciate it.

leaden ice