#archived-code-general

1 messages · Page 276 of 1

chilly surge
#

Unless you have specific reasons to not use C# Dev Kit (eg licensing), it should be the way to go.

#

AFAIK editorconfig should be respected automatically, if it's not working you can double check if you have set your formatter to the C# Dev Kit one.

wind needle
#

yes, it has worked more or less flawlessly before.

idle flax
#

Hey everyone, I have this code that automatically adds prefabs to a list. I was wondering if it's possible to have it trigger every time a new asset/prefab has been created?

private void FindPrefabs()
    {
        prefabs.Clear();
        prefabBank.Clear();
        string[] lGuids = AssetDatabase.FindAssets("t:GameObject", new string[] { "Assets" });
 
        for (int i = 0; i < lGuids.Length; i++)
        {
            string lAssetPath = AssetDatabase.GUIDToAssetPath(lGuids[i]);

            if(AssetDatabase.LoadAssetAtPath<GameObject>(lAssetPath).GetComponent<Saveable>())
            {
                prefabs.Add(AssetDatabase.LoadAssetAtPath<GameObject>(lAssetPath));
            }
        }

        for (int i = 0; i < prefabs.Count; i++)
        {
            AddObjectToPrefabBank(prefabs[i]);   
        }
    }
knotty sun
radiant elm
#

Hey all. So I have a script that uses spherecast to detect enemies, to then inflict damage. Each of my enemy objects has multiple body parts with tag Enemy. I want to limit the spherecast to register only once per enemy. At the moment it just registers too many hits and lags a lot.
For example, the moment a body part of enemy 1 is registered, the rest of the spherecast cannot register hits for any of the children colliders of enemy1.
Any ideas?

steady moat
radiant elm
#

im using foreach (RaycastHit hit in hits)

steady moat
leaden ice
radiant elm
#

sorry, youre right i use capsulecastall

#

my mistake

steady moat
#

But yeah, usually you should have a rigidbody to prevent such situation.

leaden ice
#

then your set contains the enemies that were hit, no matter how many colliders you hit

radiant elm
#

Okay thanks a lot I will try that and report back!

mossy minnow
#

hey, im trying to make a leaning mechanic in an fps controller, and it only seems to work when the rotation target is positive (leaning left)
when i try and lean right, it spins the whole camera around 360 degrees and keeps doing that until i let go of the button.

    private void CalculateLean()
    {
        //if(inputLean == 0 ) return;

        Vector3 tgt = Vector3.zero;
        tgt.z = -inputLean * leanAngle;
        Debug.Log(tgt);
        if (Vector3Int.RoundToInt(leanHolder.localEulerAngles) != tgt)
        {
            leanHolder.localEulerAngles += Move(leanHolder.localEulerAngles, tgt, leanSpeed);
        }
    }
    private Vector3 Move(Vector3 start, Vector3 tgt, float secs)
    {
        Vector3 diff = tgt - start;
        Vector3 move = diff * (secs / 50);
        return move;
    ```
knotty sun
mossy minnow
#

what do you mean?

knotty sun
#

I mean than if you put a Vector3 into an euler angles and then turn the euler angles back into a Vector3 the chances of them being the same are virtually zero

mossy minnow
#

thats why ive rounded to int in the check

#

it works fine going left

knotty sun
#

no you misunderstand.
you do leanHolder.localEulerAngles += which will be converted into a Quaternion
so when you read leanHolder.localEulerAngles that is being converted from the Quaternion and so the value that went in will not be the value that comes out

leaden ice
mossy minnow
#

ive tried using quaternions to do this but im not sure how to do the maths in Move() with them

leaden ice
#

Also not sure what this Move function is but it seems like Quaternion.RotateTowards is more what you want?

mossy minnow
#
    {
        Quaternion tgt = Quaternion.identity;
        switch (inputLean)
        {
            case 0:
                break;
            case 1:
                tgt = Quaternion.Euler(0,0,-leanAngle); 
                break;
            case -1:
                tgt = Quaternion.Euler(0,0,leanAngle);
                break;
        }
        Debug.Log(tgt);
        if(leanHolder.localRotation != tgt)
        {
            Quaternion.RotateTowards(leanHolder.localRotation, tgt, Time.deltaTime);
        }```
#

this is what ive got now, the tgt is being updated properly but it just isnt rotating at all

#

wait

#

i think i used the method wrong 1 sec

leaden ice
mossy minnow
#

ayyy, there we go

#

yeah just fixed that

#

working great now

leaden ice
#

also Time.deltaTime should be multiplied by a speed

mossy minnow
#

yep, done that too

leaden ice
#

otherwise it will be 1 degree per second

mossy minnow
#

thanks for the help!

hard viper
#

(nvm me, chat didn’t update)

tropic kiln
#

Heya all, I'm doing a bit of procedural world generation and I'm having some problems with textures on sharp edges. This is because there is literally no vertices between the top of the cliff here and the bottom. This is done as it's based on x and z world coordinates. I know how to fix the uv, that's not a problem, but If I wanted to add some detail onto it using more vertices, how would you recommend doing so? https://gyazo.com/d57b21696448347019528691a7407a0a

#

Also ignore how shitty it looks for now

leaden ice
karmic kelp
#

I have an issue with a ArgumentException: method arguments are incompatible error that i can't understand the reason of and can't seem to make it go away no matter what i try. Here is my code. The error is on the line object value = property.GetValue((object)node);

tawny elkBOT
rigid island
karmic kelp
rigid island
#

why object btw

karmic kelp
#

because GetValue returns the value as an object

leaden ice
hard viper
#

also hastebin might keep the indentation of your code for us to read it better. instead of the .txt

karmic kelp
#

i figured out the issue. The class whose properties i was trying to access was derived from a class wich had an indexer. I fixed it by only getting the properties declared directly in the class i needed.

#

`var derivedType = node.GetType();

    foreach (var property in derivedType.GetProperties())
    {
        if (property.DeclaringType == derivedType && property.CanRead)
        {
            object value = property.GetValue(node);
            if (value != null)
            {
                nodeData.properties.Add(property.Name, value);
            }
        }
    }`
leaden ice
#

Makes sense. The indexer would be a property that has a parameter, which would cause that error if no param was provided.

rigid island
#

Wait Unity 2023 supports Live/Hot Reload or what ?

wicked scroll
#

iirc you could kind of always do that, it just works inconsistently depending on what you changed/where

rigid island
#

Ahh ok , never noticed, ig a simple Debug.Log isnt exactly a breaking change lol

#

added reference to a transform and able to move via translate and still didnt break while in playmode, kewl

chilly surge
#

I have the hot reload asset and it's pretty good, but even that still feels kind of sad in comparison with JS frontend world, where you get hot reload in two digit milliseconds and there rarely ever are things that can't be patched and requiring a full reload.

leaden ice
#

That's always the tradeoff of compiled vs interpreted languages

chilly surge
#

Hmm it certainly contributes, but I wouldn't say that's why hot reload is bad. Even in regular C# hot reload is pretty decent, nowhere near Unity's tens of seconds or even minutes to do a rebuild.

rigid island
chilly surge
#

That's no longer frontend if you are talking about Node.js, but even with Node.js the restart time is still sub two digit milliseconds.

rigid island
#

oh vanilla js ig sure, but thats boring 😛

chilly surge
#

The past few days I've been writing WebSocket stuffs and I have a Node.js WebSocket server running on watch mode, it auto restarts faster than I can even Alt + Tab away.

rigid island
remote kelp
#

I am trying to remove a line from a TMP Text how could i do that? for example if i have 9 lines how do i delete the 9th line?

rigid island
remote kelp
#

Yes

rigid island
#

so you have an array of lines?

chilly surge
rigid island
#

combines HTML with just writing C#, you can also add JS functions/frameworks ofc

remote kelp
#

this is how im trying to do it right now

#

which isnt working

tropic kiln
remote kelp
leaden ice
rigid island
#

ahh wrote it faster

chilly surge
remote kelp
#

yes

#

exactly

chilly surge
#

Do you get each message individually?

remote kelp
#

its just pulling a random string from a list depending on what is going on in game

rigid island
#

Much better with string builder, I was doing Split n Join 😛

remote kelp
#

should i just remove my old code?

#

for the line removing

leaden ice
chilly surge
#

If that's the case, rather than "adding the latest message to the full text, if it goes past 8 lines, split the text and remove the excess" which is a lot of unncessary work, you could instead use a Queue<string>

remote kelp
#

Im pretty new, how would i implement a queue into this?

chilly surge
#

Enqueue one every time you get a new message, and dequeue one whenever it goes past the 8 limit.

rigid island
remote kelp
#

Dequeueing will manually remove the line?

leaden ice
# remote kelp Dequeueing will manually remove the line?
Queue<string> messages = new();

void Display() {
  StringBuilder sb = new();
  foreach (string message in messages) sb.Append(message);
   
  myText.text = sb.ToString();
}

void AddMessage(string message) {
  messages.Enqueue(message);

  while (messages.Count > maxMessages) messages.Dequeue();
}```
#

this is pretty much what you need

remote kelp
#

Okay ill try to implement this

#

thank you sm

#

should i be running display in update?

rigid island
chilly surge
#

If you don't care about optimizing that tiny bit of allocation (presumably your chat isn't going to be like Twitch chat rolling all the time), Display can simply just be string.Join("\n", messages); and that's it.

leaden ice
#

you could even call Display() at the end of AddMessage

remote kelp
chilly surge
#

You probably don't need it, but oh well it doesn't hurt.

remote kelp
#

so i should call add message after i add a line of text?

leaden ice
#

AddMessage is how you add a line of text

remote kelp
#

ahh

#

ok

leaden ice
#

delete the first two lines in SendStreamMessage

remote kelp
#

Thats what enqueue is doing huh

leaden ice
#

that's what AddMessage and Display are doing

#

AddMessage is adding the message to the queue

#

Display renders everything to the Text object

remote kelp
#

okay

#

ill try it out

#

It is working

twilit scaffold
#

in VS, is there a way to cycle the suggestions of c# autocompletion? it wants to complete this bool to true, when i want false. i would like to do something like press the down arrow to go to false. i am not finding a way to do that and google and CGPT has been useless for some reason

somber nacelle
#

if you mean you are seeing something like = true; in grey to tab to complete, that's intellicode and you'd probably want to look up the settings for that

round violet
#

I remember someone here talking about his asset, a sort of better version of NaughtyAttributes.
does anyone has an idea of what I am talking about ?

dreamy meteor
#

I added a ui blur, and it dropped my fps from 200 to 100

twilit scaffold
somber nacelle
#

that is not intellisense. that is intellicode

twilit scaffold
#

same question, but with intellicode instead of intellisense then 🙂

somber nacelle
#

and you can look at the settings to see if that exists. now that you know what settings you would need to look at

twilit scaffold
#

ok, so you are not aware of one preconfigured. guess i need to hunt more

bright token
#

Whenever I use Debug.Log in my code, Visual Studio 2022 feels the impeccable need of adding System.Diagnostics to my libraries, which then causes an error. How can I stop it from adding System.Diagnostics?

rigid island
twilit scaffold
#

Intellisense settings matches the concept better than intellicode settings. mayber there are hidden intellicode settings? it is like they are symbiotic. completion list advancement, and showing a list with true and false, is basically what i am after

somber nacelle
#

intellicode is just an AI code prediction thing. it's not really meant for what you are trying to do

sacred sinew
#

how can I call an animation event with my script ?

twilit scaffold
somber nacelle
#

that is intellisense

sacred sinew
#

thx

twilit scaffold
#

Ok, i am hoping for that box, but with true/false option when typing a bool. then like, pressing a down arrow to switch between the two. This is all i am getting right now though: Image. No box with options, just the one incorrect suggestion

somber nacelle
#

that is intellicode

twilit scaffold
#

well, i am changing their names to stupicode and falsesense :/

#

seems like there should be a hotkey to toggle true/false there

somber nacelle
#

intellicode is just AI trying to predict what you were going to type. it's not going to be a replacement for you typing your code

leaden ice
#

Intellisense is not really intended to write your code for you. Imagine that was an int. Should there be a toggle for evey possible number? Just type t and it will fill in true for you

twilit scaffold
#

yes 🙂

cold egret
#

- Is there any way to create asset menu for a specific scriptable object type without putting an attribute on it manually but programatically? My last bet is reflecting the attribute to the type, but perhaps there is some api i'm missing or something

twilit scaffold
#

but seriously, what i am looking for is a combination of the two. When i enter a bool, the selection box should come up so i can down arrow to false or true. it is just an extension of what it is already doing. it is not writing code for me, it is assisting with data entry

#

usually i use VoiceAttack and just talk to type code. I have not taken the time to configure it for Unity C# yet though. in the end, it is just utter laziness on my part 🙂 (the desire for the bool toggle i mean)

hard viper
#

when you guys use git, do you do commits etc via VS, GitBash, or something else?

#

idk if the VS git features will only include the actual solution, or if it will include all the other files

lean sail
vagrant agate
#

Most all version control has a desktop gui.

hard viper
#

i see. I would like to set something up to avoid github, to keep everything local. is there a good gui-based program you would recommend?

vagrant agate
#

You just install GIT and push locally but if something happens to your harddrive you will lose it if you dont back it up. Thats the point behind local vs remote changes

hard viper
#

i would like to set that up later, to have a backup drive or something

vagrant agate
#

Most all IDE's will detect that you have GIT installed somewhere around your terminal window within the IDE

hard viper
#

so multiple computers can connect via local network

lean sail
#

Would be a lot easier if you just use github and a private repo. I dont remember if github desktop can work locally like that

hard viper
#

i assume github would be easier tbh

twilit scaffold
hard viper
#

maybe I’m just paranoid, but i’m just not sure how much I want to be transmitting information over internet. especially since my github account is more easily seen, and then compromised

lean sail
twilit scaffold
#

thanks for the info. would have taken me quite some time to determine what was what there

tawny elm
#

im trying to import a video file with transparency, issue is, im on linux.
for some reason unity on linux only supports the webm format, and only specific versions of it using specific codecs.
and no matter what method or programs i use, converting a video i rendered from blender with transparency into this format always gets rid of the transparency.
ive tried exporting from blender directly to the correct format but it doesnt support the right codecs.

#

ive simply got no idea how to do this

twilit scaffold
hard viper
#

I have an SO with a [SerializeField] private string myString field.
If I have the SO’s own method modify it in context menu, then the newly serialized value DOES get saved to file. If a different script calls that same method to modify it, then it does “change”, and looks different, but the file for the asset has not been changed!
Any idea why this might be?

#

Main relevant method in my SO looks like this:

/// <summary>Write whatever is in the class type references to the backup. </summary>
[ContextMenu("Backup Classtype references")]
public void BackupClassRefSave() {
    TryBackup(conductStrat, ref backupConductStratName);
    void TryBackup(TypeReference typeRef, ref string backupName) {
        backupName = typeRef.AssemblyQualifiedTypeName();
    }
}```
tepid plover
#

this is what happens currently and i want the plane to fall more when the angle gets too high and ive tried for about 10 mins now cant figure out does anybody know what i could do. Also this is my code: https://paste.ofcode.org/L2yGNu2M3QGNxS9HQMYmnv
It is extremely simple and the whole thing heavely relys on the unity physics system.

leaden ice
#

i want the plane to fall more when the angle gets too high
This is extremely vague

#

btw you are making some classic mistakes here in your code.
Physics belongs in FixedUpdate, not Update

#

and you shouldn't multiply the forces and torques by deltaTime once you move it there.

radiant elm
weak venture
#

Is there a best-practice pattern you would recommend for pausing logic triggered by invoke?
I have an event based pause setup rather than using time.timeScale=0 but im not sure what a good way would be to get invokes to hook into that system. In some cases, I've just replaced the invokes with a timer controlled by the component that can be pause/unpaused when it gets an event but I'm wondering if theres a better way I can set up delayed logic such that it could integrate into that system, like a way to pause all invoke timers on an object

hard viper
#

coroutine

weak venture
#

Can coroutines be paused? I see StopCoroutine functions but I assumed they would cancel them completely

hard viper
#

coroutines have WaitUntil

torn hazel
#

Hello, does someone knows if it is possible to have .csproj not in the unity project directory as if it was a third party library ?
I want to have a project outside of unity project directory because i'm using it for a .Net console app and some code will be used inside the unity project but i don't want to build a dll from it and move it to asset folder.

hard viper
#

and any time based WaitFor… do not advance if timescale is 0 iirc

weak venture
#

so if I have
yield return new WaitForSeconds(delay);
I'd just have to make calling that conditional against my pause bool?

hard viper
#

does your pause set timescale to 0?

#

it should

#

because if timescale is zero, WaitFor… any amount of time will not be ready for next call to advance

weak venture
#

nah because i want the ability to only pause certain things

#

theres like layers of pause

hard viper
#

you could do WaitUntil(!pauseBool)

#

but know that if not paused, that will probably make it yield to the next frame still

weak venture
#

right ok. thanks for the info.

hard viper
#

but that is the general premise anyway

earnest glacier
#

hey so I'm trying to simulate circular motion without using trig functions - I have a sphere with a RigidBody initially at (-5, 0, 0) and I add an initial velocity of (0, 0, 5). I add mv^2/r force every update method but it seems to just accelerate the objec tto infinity. any reason this is happening?

using System;
using UnityEngine;

public class CircularMotion : MonoBehaviour
{
    Vector3 center = new Vector3(0, 0, 0);
    public Rigidbody rb;
    int rad = 5;
    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = new Vector3(0, 0, 5);
    }

    // Update is called once per frame
    void Update() {
        Vector3 direction = center - rb.position;
        float v2 = (float) Math.Pow(rb.velocity.sqrMagnitude, 2);
        rb.AddForce(v2 / direction.sqrMagnitude * direction.normalized);
        // Debug.Log(rb.mass);
    }
}
somber nacelle
#

for starters, you really shouldn't be adding force inside of Update, higher framerates will end up adding more force than lower framerates as a result. physics should be performed inside of FixedUpdate
and for preventing it from just constantly speeding up you'd need to set up drag on the rigidbody and also possibly clamp the magnitude of the velocity

earnest glacier
#

oh i see

#

why would drag/clamping be needed though? is it because the addforce isn't exactly precise leading to speeding up? because theoretically the force shouldn't change the velocity of the object

cosmic rain
#

Force always changes the velocity of the object.

#

Otherwise there wouldn't be a point in it.

earnest glacier
#

huh iirc at least physics wise if the force is perpendicular to the velocity of the object it wouodn't do any work on the object, and so the kinetic energy/velocity stay the same

cosmic rain
#

Not sure where you heard that, but it doesn't matter what direction the force is applied at relative to the velocity, it would always affect it.

#

If it applies perpendicularly, it would just add sideways velocity.

earnest glacier
#

hmm so how does centripetal force work in unity then

#

or how would i simulate that?

cosmic rain
#

Actually. Wait a moment. I think my physics memory is getting rusty.🤔

somber nacelle
# earnest glacier hmm so how does centripetal force work in unity then

have you tried your current code inside of FixedUpdate to see how it behaves on the correct time step? because as it was before, you were adding extra force on non-FixedUpdate frames because update typically runs many more times per second than FixedUpdate does and FixedUpdate runs on the same time step as physics being updated

earnest glacier
#

yeah fixedupdate still seems to accelerate it to infinity, i'll try clamping the velocity

#

how would i do that?

#

just rb.velocity = rb.velocity.normalize() * constant?

cosmic rain
cosmic rain
#

Because it's not clear wether it just keeps on going in one direction or accelerating while orbiting.

earnest glacier
#

sure

cosmic rain
#

Also, just a correction about what we were talking before: applying a centripetal force to the object would make it's velocity change. It should keep the speed(velocity magnitude) constant. But when we talk about velocity, we imply it's a combination of direction + magnitude.

earnest glacier
#

its kinda hard to see since it happens so fast..

cosmic rain
#

As for the cause, it's probably because you got the formula in unity incorrectly.

#

The way you have it now is F = v^4/r^2.

earnest glacier
#

oh

cosmic rain
#

sqrMagnitude is squared magnitude after all.

earnest glacier
#

... okay i dont know what im doing

#

LOLOL

cosmic rain
#

Instead of squared magnitude use the regular magnitude

earnest glacier
#

it works tysm for the help!

#

should have read the documentation...

hard viper
#

just remember your units

#

dimensional analysis will immediately catch many mistakes

calm talon
#

If I have a shape defined by a set of vertices (Vector2 points) in an array (point 1 connects to point 2 and so on, with the last point in the array connecting back to 1) how would I check if an object is within the boundary of that shape?

terse quarry
#

Hey sorry to ping after a while lol. I've managed to get the screenshot working and saving it to a folder. But I can only get it to screenshot the entire screen. I don't really understand how the parameters for ReadPixels() relate to the region it captures.

sacred sinew
#

How can I use my animation events in a script

little meadow
sacred sinew
#

yep but i can't add the function

little meadow
#

why not? you just type public void MyFunc(params if you have any) { code goes here }

sacred sinew
#

yes but it's not gonna happen at the same moment than the event

#

it's just a function

little meadow
#

a function that the animator/animation component will call when it reaches the event

sacred sinew
#

this is where it doesn't work

little meadow
#

okay... show how you've set up one of the events

sacred sinew
#

i can't add the function

little meadow
#

you must have the function first, I guess

#

(I don't quite remember how it works)

#

you must have a component with the function, which should be attached to the object that you're animating... something like that

sacred sinew
#

it worked thanks

#

I just needed to add the function

little meadow
#

glad it worked, happy to help 🙂

scarlet kindle
#

hi. I ran into a funny situation. I am using
Int.Parse("+1")
in some code, which ran fine on my system. apparently this is because the default for NumberStyles is to allowe leading sign?

However, on someone else playing my game, this resulted in a exception and their game crashed lol

#

how would their system interpret this differently, we even checked their .NET version

#

and it was very similar, mine was 7.0.306 and theirs was 7.0.202

#

I guess to be safe, I should just use
Int32.Parse(num, NumberStyles.AllowLeadingSign) to be explicit?

little meadow
#

that's an option, buuut normally you'd pass CultureInfo.InvariantCulture

scarlet kindle
#

ah, yes I come from a very typed background

#

I see that as a solution too

#

but, I prefer to be very strict about typing if possible

little meadow
#

maybe passing NumberStyles is better, I haven't checked exactly how it works... just make sure it describes it well enough and doesn't depend on any user config

#

actually, is the string that you're parsing coming from user input?

scarlet kindle
#

I'm not even sure I totally get the InvariantCulture thing tbh... this is the first I've heard of it since you just mentioned it lol.

#

nah it's just from some prefab stuff i have

#

i can parse it however I want

#

its not really a big deal, i'm just super surprised that it would run fine on many systems, and then all of a sudden crash on someone else's

little meadow
#

InvariantCulture is just constant in how it handles things and doesn't depend on user settings

scarlet kindle
#

ah cool! maybe that's what I need indeed

little meadow
#

mm, parsing numbers is tricky... in some countries they use . as float point delimiter, and in others they use ,, and so on

#

there are spaces, no spaces, commas for thousand separators, etc.

scarlet kindle
#

fun stuff lol

little meadow
#

and that's based on device settings, lets say

#

InvariantCulture is not based on settings - it formats and parses things in the same way for everyone 😄

scarlet kindle
#

makes sense! I wonder if somehow Integer parsing is culture dependent, based on a user's system

#

that would explain the issue

little meadow
#

it is, yeah, that's why you can pass all these settings in 😛

scarlet kindle
#

oh interesting, so would that have to do with the native language they use on their system? or would it be based on where the OS was purchased from?

little meadow
#

language settings

scarlet kindle
#

ah i will have to ask him which language he's using

#

thanks a ton! good stuff 🙂

little meadow
#

(language and region on Windows... you can specify custom formats and stuff in the settings, I believe)

scarlet kindle
#

you're a hero, thank you thank you! ok i should probably go to sleep getting my schedule all messed up is not fun xD

#

have a good one!

little meadow
#

thanks, you too

earnest gazelle
#

Dudes, one question about architecture selection for data in a game. I love component based approach but it needs clear design for data beforehand.
It means it is so easy to have a separate definition class for each element/item type in the game.
For example in a simulation game with a bunch of different items, it is hard to pack their properties to different components unless the design is clear. What do you think?

little meadow
#

Clear design beforehand is not a thing, imo 😄
And the nice thing about component based approach is that you can make it piece by piece - one component only needs to know about X data and manages it itself. What other components may or may not exist - you don't care.
Of course, over time you'll see better ways to organize things, and every now and then you'll refactor. 🤷‍♂️ 🙂

earnest gazelle
#

I am afraid of reaching the point that it is hard to group data to modular components or at least some props are in components and some of them are not,
The problem is that I have separated data/definition (SO) from logic (components in prefabs)
The desire is to map the correct data to the correct component (mono)

#
 public class Repairable : MonoBehaviour, IRepairable
    {
        public event Action Repairing;
        public event Action Repaired;
        public int MaxUseCount { get; private set; }
        public int Count { get; private set; }
        public bool IsOutOfOrder { get; private set; }

        private void Init(ItemDefinition definition)
        {
            var repairableDefinition = definition.GetComponent<RepairableDefinition>(); // here, component based approach
            MaxUseCount = repairableDefinition.MaxUseCount;
            IsOutOfOrder = false;
            Count = 0;
        }
earnest gazelle
#

Hey, why doesn't it work?
I use unity 2022 LTS

public class Def:SerializedScriptableObject{
   public IDefinition Component;
}
 public interface IDefinition
 {
 }
  [Serializable]
  public class RepairableDefinition : IDefinition
  {
        public int MaxUseCount;
  }

I get an error below

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUILayoutEntry.ApplyStyleSettings (UnityEngine.GUIStyle style) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutEntry.set_style (UnityEngine.GUIStyle value) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutEntry..ctor (System.Single _minWidth, System.Single _maxWidth, System.Single _minHeight, System.Single _maxHeight, UnityEngine.GUIStyle _style, UnityEngine.GUILayoutOption[] options) (at <3787173144ff4a19b1a55d5938e19421>:0)
UnityEngine.GUILayoutUtility.DoGetRect (System.Single minWidth, System.Single maxWidth, System.Single minHeight, System.Single maxHeight, UnityEngine.GUIStyle style, UnityEditor.HostView.OldOnGUI () (at <5d5ebefe97114215928ac1d9cd096522>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <f67debe1efd242948106f1922bfac1c7>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
frosty basalt
#

i need some help with MediaPipeUnityPlugin anybody ever worked with it here? need to convert landmark positions to unity coordinate system or rect

thin hollow
#

Can somebody help me wrap my head around something?

  • I store my attack parameters (like, damage, animation, etc) in scriptable objects. In theory every NPC should be able to use any attack in the game.
  • I wanted to also store attack's effects logic in Scriptable Object (Like, how the attack is actually performed). But this didn't fly since the logic would require storing information about the target of the attack, but SO is shared between everybody who would use that attack so they will conflict overwriting the target-specific variables.
  • So I decided to handle out NPCs an AttackObject class object that the scriptable object can create with GetAttack() function, instead of the reference to the SO itself. This class would contain the logic for the attacks and data relevant to the attack.

Now I came to the problem of associating those attack classes to the scripted objects of the attack parameters, which attack should issue out which AttackObject subclass. Ideally I want the SO to have a variable exposed to the inspector, a dropdown list of the AttackObject class inheritors I can chose from, but how do I make something like this?
Naively making a serializable field didn't work, of course...
[SerializeField] public Type attackLogic;

little meadow
#

I'm actually working on releasing a package that does this +1-2 other things 😄

#

You need [SerializeReference] + a custom property drawer

#

I'll probably make the repo public sometime today, and can link you if you're interested in being the first user 😅 (though in the interest of fairness, other repos with such a feature do already exist)

thin hollow
little meadow
#

It would be more like [SerializeReference] [TypePicker] private BaseType fieldName; and the drawer of the TypePicker is gonna draw a type picker... you can get the classes using... TypeCache.GetTypesDerivedFrom(type) it's a Unity thing

thin hollow
#

Oh, thanks! I'll dig into that

subtle jungle
#

Can coroutines run in parallel? Like using multiple cores? Or do I need to use the job system for that?

little meadow
#

Coroutines run on the same thread as everything else. You can use .NET's task system or UniTask to do stuff on other threads, but keep in mind that everything that related to any Unity component requires running on the main thread.

subtle jungle
#

thanks, I just need to load beatmaps and mainly songs into memory, so that should be fine

little meadow
#

The job system, of course, is also an option... I'd say job system is more for doing heavy computations in parallel, whereas the task system is more about doing async stuff (like writing files, downloading stuff, which may take a while)

subtle jungle
#

oh, okay. thanks :)

sacred sinew
#

My bullets are fixed in the air even if my script tell them to move, do someone know why ?

round violet
#

is there a shortcut to create a vector 3 with same x y z ? like Vector3.one

#

using a float var

mellow sigil
#

Vector3.one * x

round violet
#

well im dumb

#

ty

chilly surge
sacred sinew
thin hollow
# little meadow It would be more like `[SerializeReference] [TypePicker] private BaseType fieldN...

I think I got the basic of it, but it seems I don't know how to assign the new variable. It gives me null exceptions...

    [CustomPropertyDrawer(typeof(TypePicker))]
    public class TypePickerPropertyDrawer: PropertyDrawer
    {
        private string _selectedType = "";
        public void TypeSelected(object type)
        {
            _selectedType = (string) type;
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            _selectedType = property.managedReferenceFieldTypename;
            if(property.managedReferenceValue?.GetType().FullName != null)
                _selectedType = property.managedReferenceValue.GetType().FullName;
            
            string clearName = _selectedType?.Split(".")[1];
            
            EditorGUI.BeginProperty(position, label, property);
            if (EditorGUI.DropdownButton
                (
                    new Rect(position.x+property.depth, position.y, position.width-property.depth, position.height),
                    new GUIContent(_selectedType),
                    FocusType.Passive
                ))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent(clearName), _selectedType==property.managedReferenceFieldTypename,TypeSelected,property.managedReferenceFieldTypename);
                TypeCache.TypeCollection types = TypeCache.GetTypesDerivedFrom(fieldInfo.FieldType);
                if(types.Count > 0)
                    foreach (Type t in types)
                    {
                        menu.AddItem(new GUIContent(t.Name), _selectedType==t.FullName,TypeSelected,t.FullName);
                    }
                
                menu.ShowAsContext();
            }

          //  property.managedReferenceValue = (UnityEngine.Object)Activator.CreateInstance(Type.GetType(_selectedType), new object[]{});
            EditorGUI.EndProperty();
        }
    }
little meadow
#

where does it give you a null ref?

thin hollow
#

In the commented out line

little meadow
#

so, see what's null on it and fix 😛

#

but why do you have a cast to UnityEngine.Object?

thin hollow
#

I couldn't figure out how to cast to the specific type I selected, everything I tried gives me syntax errors. T_T

little meadow
#

[SerializeReference] doesn't work with UnityEngine.Object... if you want those you just use a normal field with [SerializeField]

#

you shouldn't need a cast on that line

thin hollow
#

Hm, I can swear it was giving me "cannot convert..." error before without the cast, but now everything's fine... >_<
Anyho, I think I've located the error down to Type.GetType(_selectedType) not returning anything. X_x

swift falcon
#

!code

tawny elkBOT
eager steppe
#

is cableMaskLayer an actual layer in the Unity Inspector?

round violet
#

you can see it on the screenshots

hard viper
#

I have an issue in an SO:

[SerializeField] private string backupConductStratName;

/// <summary>Write whatever is in the class type references to the backup. </summary>
[ContextMenu("Backup Classtype references")]
public void BackupClassRefSave() {
    TryBackup(conductStrat, ref backupConductStratName);
    void TryBackup(TypeReference typeRef, ref string backupName) {
        backupName = typeRef.AssemblyQualifiedTypeName();
    }
}```
If I use the context menu to call this method in the inspector for the SO, the value of backupConductStratName DOES get updated and written to file.
If I call this method from a different SO’s method (also context menu in editor), it looks and behaves like the string is modified. But it doesn’t save it to the file!

Any idea why?
latent latch
#

So you're writting to an SO from another SO and the values aren't being serialized?

hard viper
#

it is like the SO is changed, but the changes did not get written to file. so when I close and reopen the project, it’s loke nothing was changed

hard viper
latent latch
#

Yeah, I think I've ran into this issue before, and it was when I've decided to try to write to my SOs instance when running the game.

#

I think I hypothesized that it created another instance that I was writing to, and it would only revert when restarting the editor.

hard viper
#

is there a way to just tell Unity to update and serialize the current contents?

hard viper
latent latch
#

right, because it probably made another instance (or perhaps it's just not serializing the values)

#

probably some fail safe to prevent you from blowing up your asset by mistake

latent latch
#

looks promising

#

could be something like a IsDirty flag you'd have to flip

#

but nothing I've really looked into since I realized pretty quickly that I shouldn't have been writing to them like that in the first place

hard viper
#

i just don’t see any methods/properties/fields in SO that I can access whichbare relevant

hard viper
latent latch
#

ah, yeah I was talking about my methods of writing to them

hard viper
#

well, i can only use ForceReserialize if i can get the path for an SO

#

so… how do I get the asset path for an SO given a ref to the instance lol

latent latch
#

assetpath

hard viper
#

is this going to work?

latent latch
#
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);

// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);```
#

oh scratch the ID

hard viper
#

ok, that is what I was about to ask.

latent latch
#

only works editor but seems like that's what you're doing anyway

hard viper
#

yeah, that is perfect

#

ty

#

i might make an extension method for SOs for this

#

damn. still trying to set up other IDE settings on windows, since I had to change computers

#

anyone know the name of the setting that makes VS automatically add using directives as you type?

little meadow
#

wait wait

hard viper
#

i disabled one for “add missing using directives on paste”, but that doesn’t count for my normal typing

little meadow
#

there's EditorUtility.SetDirty

hard viper
#

because with autocomplete, VS adds the stupidest shit

simple egret
#

"Show types from unimported namespaces"

hard viper
little meadow
#

It's the standard way to tell some Unity object that you changed it, so Unity would know to serialize it when you save next time, something like that

hard viper
simple egret
#

That setting enables it globally, but it can still be toggled from the completion list, using the green "+" icon bottom left.

hard viper
#

oh i see the buttons to operate the menus are just different

#

not sure I follow.

#

potential fixes highlights nnamespaces, but I don't think that is what I was seeing on my mac

#

because potential fixes is it trying to fix the whole problem for me

simple egret
#

Not on the tooltip, in the completion list

simple egret
#

With the feature enabled it will show the type name, and on the right in light gray the namespace it belongs in, if not imported

hard viper
#

sry, i feel like i’ve been driving just fine, and now I’m in a weird european car where all the buttons are in different places lol

latent latch
hard viper
#

I'm still a bit confused. This has show types from unimported namespaces on. This is the view I kind of want, but I don't want it to auto add namespaces.

#

because I end up with crazy namespaces in all my documents from random typos

simple egret
#

It's not possible, as far as I know

hard viper
#

ok. Off it goes then

simple egret
#

Either you have them listed, and it adds the directive as you complete, or they're not listed at all.
I guess you'll have to stick to the Quick Actions to add the correct using directive, or Ctrl+Z to cancel if you chose the wrong one

#

And Ctrl+Space to bring the list back up

hard viper
#

ty SPR

#

this is going to be a long and annoying process

#

anyway, since I finally have more tools, given windows VS is better, is ClassDesigner any good for coding?

#

i’m trying to see now that I have new toys what I have been missing out on

hard viper
little meadow
#

happy to help 🙂 👍

hard viper
#

i need to slowly get settled back in. ty for your patience

sacred sinew
#

I have to set the player off and I am using the "SetActive(false)" function but the Player is still active

heady iris
static matrix
#

can I make a UI button do a different thing depending on right or left click? I feel like that was something I could do

heady iris
#

The built-in Button class doesn't care about anything but left-clicking

#

Fortunately, it's very easy to extend existing components

static matrix
#

it is?

spring creek
heady iris
#

You can extend Button and override the OnPointerDown method

static matrix
#

yeah those wont work in this scenario

#

I dont think

#

maybe they would?

#

idk

heady iris
#

It receives a PointerEventData object

static matrix
#

but I can just make it first click sets state to 1, second to 2, third to 0
instead of rclick and lclick switching stuff seperately

heady iris
#

Actually, I bet you could just override that, along with OnPointerUp

#

and just rewrite the PointerEventData object so that it looks like a left click, even if it's a right click

#

and then just call the base method with the modified object

#

Otherwise, you'd just implement your own button logic for right clicks

spring creek
inner mist
#

If i follow an tutorial on 2d and the tutorial is 2d URP does it matter?

vivid heart
#

Please help, I can't seem to address the addressables to receive the list of keys; in the code snippet and image, everything seems to be configured correctly..

private async UniTask<List<string>> GetConfigKeys<TConfig>() => 
            await assetProvider.GetAssetsListByLabel<TConfig>(AssetLabels.Configs);

        private async UniTask<TConfig[]> GetConfigs<TConfig>() where TConfig : class
        {
            var keys = await GetConfigKeys<TConfig>();
            return await assetProvider.LoadAll<TConfig>(keys);
        }

Debug.Log(keys.Count) the result is 0

hushed dust
#

how do you profile the editor in 2022 LTS? the "profile editor" button is gone from the profiler

heady iris
#

it's in that dropdown

hushed dust
heady iris
#

ouch

#

I forget how much stuff appears in "Play Mode" and how much stuff appears in "Edit Mode" during startup

#

i haven't profiled that in a little while

#

my main menu was...uh, very Main, and very Menu

#

and was adding a half-second to my startup time

hushed dust
#

its happening in an empty scene, so it must be something in some asset i have in my project

proud fossil
#

how can I make my character move forward with new Unity Input System and Character Controlle

spring creek
proud fossil
#

oh ok, thanks

maiden sedge
#

hello quick question do coroutines still run if the object having the script is destroyed ?

#

like if I destroy a gameobject while a coroutine is running on an associated script

somber nacelle
#

if the destroyed object is what started the coroutine then the coroutine will stop

maiden sedge
#

oh okay thanks thats what I was looking for

golden garnet
#

Is “Apply Scene Offsets” a deprecated feature or no?

little meadow
#

I have to say, I prefer this channel... or the next one 😄

celest iron
#

I mean, obviously there is going to be more beginners

#

So the beginners channel is, by default, more chaotic

#

I don't see much wrong in that

little meadow
#

Oh, I don't see anything wrong in that as well 🙂 I just get more excited about some more challenging questions

half vigil
#

does anybody know how I can check if the player isnt on a slope anymore after sliding down one

#

!code

tawny elkBOT
half vigil
#

here code

#

slope calculations are at bottom

soft shard
# half vigil slope calculations are at bottom

Only thing I would suggest is using Mathf.Approximately(angle, 0f) instead of angle != 0 since a float is rarely ever going to be a perfect value - aside from that though, whats the issue with your current implementation? Your function should return false if the angle is greater than whatever you set maxSlopeAngle to be, if it is, you know your "not on a slope anymore"

half vigil
#

should I call the function on update and then check the angle?

#

if so, how?

soft shard
half vigil
soft shard
half vigil
#

should I check if angle is 0 (or < 10 more likely) and if so turn the speed down

soft shard
#

You could, if your goal is to slow the player down while moving on a slope

half vigil
#

if so

#

alr I changed the code a little and am using a coroutine to make the speed shift more smooth though tbh this isnt really related to the question

fleet flax
#

Anyone know how platformer/metroidvania games keep their camera from going "under ground"? In those games the camera only goes maybe a tile or 2 down like it's clamped or colliding with the terrain.

The effect works on walls and ceilings too I think.

rigid island
#

it's clamped

fleet flax
#

But how does it handle so many different heights and variations

rigid island
#

maybe it looks for specific object or tile?

fleet flax
#

Like each room and area is presumably at different heights and dimensions. You can't just set a floor and ceiling for every room

rigid island
#

hard to say wihtout seeing their implementation lol

fleet flax
#

Yea I'm wondering if there's like a standard approach or guide on it

rigid island
fleet flax
#

That's no bueno. Want a system that requires the least amount of setup I think

rigid island
#

least amount of setup? what do you mean by that?

#

if the floor is passed as some sort of "marker" then they can check specific height comparisons etc.

fleet flax
#

Like no markers or tile level implementation. It should just work everywhere.

If there isn't a normal way I think I'll just try it with colliders and see where it goes

rigid island
#

hows that extra work if it was say only the floor tiles etc.

fleet flax
#

Like 4 colliders for each direction and just check for wall collision before moving left and right

#

Ah I thought you meant setting specific markers. Yea wall/ground collision seems like an obvious first step I think

rigid island
#

do you have a video example / gif ?
its been a while since i've played a 2D sidecroller

half vigil
#

does anybody know how I can check the slope angle on update

half vigil
#

I have a slope function

#

Im just not sure how to use the angle in update

rigid island
#

wdym how to use the angle in update?

#

store it in a variable?

half vigil
#

lemme post code

waxen jasper
#

Anyone here familiar with DryWetMidi? I want to pick your brains

half vigil
waxen jasper
half vigil
#

no

waxen jasper
half vigil
#

🤬

spring creek
#

<@&502884371011731486>

half vigil
lean sail
#

they can still see deleted messages

spring creek
#

They see deleted messages

half vigil
#

ik

#

wasnt me tho

#
  • prank
quartz folio
#

!ban save 833202238948114443 no tolerance for this

tawny elkBOT
#

dynoSuccess hylianmango was banned.

spring creek
#

@swift falcon Move the hallway only

#

Not the player

#

Add sections far enough in front that you can't see it and far enough back for the same

hard viper
#

wow, that escalated quickly

#

and once again, peace is restored

rigid island
#

oh shit didnt even notice lol
well I suppose dont have to answer the code question anymore

sick wren
#

not sure what i did her but im trying to not have mouse POS value return to 0, more trying to have it return to its original possition after being used for the camera movement:



using UnityEngine;
using Cinemachine;

public class InputOnMouseDown : MonoBehaviour, AxisState.IInputAxisProvider
{
    public string HorizontalInput = "Mouse X";
    public string VerticalInput = "Mouse Y";

    private Vector3 mousePositionOnMouseDown;
    private bool isRightMouseButtonDown;

    private void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            mousePositionOnMouseDown = Input.mousePosition;
            isRightMouseButtonDown = true;
        }
        else if (Input.GetMouseButtonUp(1))
        {
            isRightMouseButtonDown = false;
        }

        if (isRightMouseButtonDown)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }
    }

    public float GetAxisValue(int axis)
    {
        // No input unless right mouse is down
        if (!isRightMouseButtonDown)
            return 0;

        switch (axis)
        {
            case 0: return Input.GetAxis("Mouse X");
            case 1: return Input.GetAxis("Mouse Y");
            default: return 0;
        }
    }
}

rigid island
#

btw you made the strings but arent using them HorizontalInput

#

you can make those const

sick wren
#

its a script for a camera movement thingie, being used along side cinemachine

rigid island
#

doesn't explain its purpose or what your end goal is

sick wren
#

it is supposed to move the camera relitive to the mouse movement once the right mouse button is pressed / held, the mouse meant to return to its original place when the right mouse button is clicked but instead it return to 0

rigid island
#

I dont see any code to tell it to return

sick wren
#

thats why im confused

#

i didnt include it thinking it would just stay in the same pos

rigid island
#

You wont be able to move the hardware mouse to that spot unless you're using the new input system anyway

#

unless you make a software cursor

heady grove
#

I'm working with UI toolkit
Is it possible to scale button image? can't find a way to do it

#

mmm ok, not sure if there is a better way but I just made image and text blank and added two child elemets: lable and visual element (for image)

broken trail
cosmic rain
broken trail
cosmic rain
#

3:10 or so

broken trail
mossy snow
#

Unity's serializer does support abstract types if they're derived from UnityEngine.Object. In his video, those things he's putting in the list are derived from Item, an abstract MonoBehaviour

#

the typical use case is serializing abstract MonoBehaviours or ScriptableObjects

broken trail
#

forgot I had to drag in an object instead of just the script

#

thnx tho

round violet
#

Is there a way to debug log in multiple console ?

Like having my logs of my player and ennemy in separate console

#

Maybe using a custom inspector window is the solution

fringe ridge
#

So if i get this right, using .SetActive for UI objects is very bad, but for other stuff like 3d objects in game it's not a problem?

west lotus
#

Why is SetActive for UI objects bad ?

little meadow
#

probably because canvas needs to recalculate things and reorder things

#

it's not like "too bad avoid at all costs", just not super optimal... which is something that may not matter at all, unless you do it quite a lot

west lotus
#

I have not noticed any perf problems from that specifically

knotty sun
round violet
#

ty ill try

fossil grail
#

guys when i animated by 321 go for a car game, the go letter never disappears and just stays there, can someone help

round violet
#

show code

round violet
#

such as

#

i didnt create any asmdef so i shouldn't have an issue with a missing asmdef

knotty sun
#

where did you see this?

round violet
#

the code ?

knotty sun
#

yes

knotty sun
#

the example code

round violet
#

corrected

#

had a < missing

knotty sun
#

I suspect the example is outdated, the Events section of the docs does not mention an onAdd or onRemove event

round violet
#

mh

#

well thats not cool, ill try to make it myself or find another example

#

ty for trying

knotty sun
#

makeitem and binditem are all you really need

round violet
#

ok ty

#

it quite dont understand how those methods works

leftPane.makeItem = () => new Label();
leftPane.bindItem = (item, index) => { (item as Label).text = allObjects[index].name; };
leftPane.itemsSource = allObjects;
#

the use of makeItem and bindItem looks mysterious to me

#

why am i making one item ?

lunar python
#

how to flip hitboxes correctly in Unity. I am setting localScale to (-1,1,1) but it is giving warning as the BoxCollider have negative scale can have wrong collision?

craggy veldt
round violet
#

oh yeah

#

so all items would be Label

craggy veldt
#

1 root and lotta children

lunar python
#

I tried flipping hitbox with rotation but the shader no longer shed light on the player because the vertices is on the flip side now

#

how to fix this?

round violet
#

now i got an issue with calling a method to add stuff in the list used in the ListView

#

since the class of my custom window is editor, I cant access it in regular code.
How could i make like the Debug class

#

calling anywhere, no compiling issue when building and stuff

knotty sun
round violet
#

okay

#

so, if i change the value of a index in the list, the Label in the ListView should update ?

knotty sun
round violet
#

sure

craggy veldt
#

that's the magic of listview

round violet
#

and if you dont mind i would love some directions for making a regular Mono class interact with the Custom WInodw at runtime

craggy veldt
knotty sun
round violet
#

its public for the class

#

but not static, so how do i get the ref to the window class ?

knotty sun
#

GetWindow

round violet
#

should the mono class be static ?

knotty sun
#

you an even make your Editor a singleton if you want, even easier

knotty sun
round violet
#

okay

#

there is 12 overload of GetWindow

#

looks im having issues because the window class is in a Editor folder

#

so i cant reference the class in other class that arent in the folder

knotty sun
#

should work

MyEditor window = (MyEditor)EditorWindow.GetWindow(typeof(MyEditor));
dense schooner
#

my code error?

#

with the game obj

round violet
#

because its Editor folder

round violet
dense schooner
#

thanks

round violet
# knotty sun no

if its not static, this means i have to create a debug log class reference ?
so its not like the Debug class

knotty sun
round violet
#

okay

hard viper
#

as a general rule of thumb,
use/make static methods when the function does not rely on or modify any information outside of its arguments.

Use a singleton when you need a class where there is a reference to a single one unique instance, which can modify its contents. But there will never be two of them.

round violet
#

well now is still miss the communication between this custom debug class and the custom window

hard viper
#

Debug classes should usually be static

#

because Debug classes should only contain methods that do not rely on or modify any information outside those debug methods

#

if you have a debug class that is not static, I need to question wtf you are doing

round violet
#

well, i am using a listview in the custom editor, so the custom debug class should add an item in a public list that is inside the custom edutor

#

the issue is that the custom window class is in an editor folder, so i cannot reference it in my custom debug class

hard viper
#

also keep in mind that modifying static fields is extremely dangerous, so you should extremely rarely even define them

round violet
#

i am not modifying a static field

hard viper
#

that is just general advice on this topic

#

so i don’t tell you to make something static, and then you go and make a bunch of static fields etc, and then make your life difficult

knotty sun
hard viper
#

i don’t think you are supposed to do that

stiff shore
#

CSharp

#

C#

hard viper
#

i made an asmdef in the root of my assets folder, which defines an assembly that functions equivalently to assembly-csharp

#

then add asmdefs etc in subfolders to break it up

round violet
#

i think its unity that makes all classes in Editor folders to a special editor only asmdef

knotty sun
#

not an asmdef then, it's a different .csproj

round violet
#

CustomDebug is my debug class
CustomConsoleDebug is the window

knotty sun
#

wait, let me see if I can put something together real quick

little meadow
#

@round violet you can perhaps make an event in CustomDebug that you fire whenever you log, and make the Debug Windows listen to that event?

#

could be a static event

round violet
#

good idea

#

but the compiler will still not know the event exist ?

little meadow
#

it will

round violet
#

because it doesnt know the class exists

little meadow
#

Editor stuff knows about non-Editor stuff

#

your Editor class will know about the other one

round violet
#

im trying rn

#

looks like it works

#

but the listview isnt refreshing

unkempt canyon
#

hello

little meadow
round violet
#

ill see if there is any method to do that

#

well now my window is super small so i cannot resize it

round violet
marble mauve
#

Hi guys. How can I delete or prevent gameobject under dontdestroyonload to don't be destroyed as I wanted in a specific stage of my game to destroy them and change to another scene

heady iris
#

I don't understand your question. Objects in the DontDestroyOnLoad aren't destroyed when you load a new scene in "single" mode (the default)

#

Are you asking how to move objects back out of the DontDestroyOnLoad scene, perhaps?

marble mauve
#

yeah

little meadow
#

My first suggestion would be to not use DDOL in the first place

heady iris
#

why not just destroy the objects manually?

little meadow
#

Do you want to move something out of DDOL scene, or do you want to destroy it? And do you have a reference to it or?

heady iris
#

otherwise, you can move objects from scene to scene

#

But I'm not sure why you'd want to do that here

#

If you want to destroy everything in the DontDestroyOnLoad scene, then I'd suggest changing your design so that:

  • You keep references to these objects, OR
  • You put these objects into a scene that you unload yourself
spring creek
#

You could look into Additive Scene loading, if the goal is to have things persist between some scene changes and get unloaded in other scene changes

heady iris
marble mauve
heady iris
#

Just destroy the object, then

#

All that DontDestroyOnLoad() does is move the object into a special scene that never unloads

#

it's not DontDestroyEver()

marble mauve
#

yeah that is what I was trying to destroy all the objects inside the ddol but I didn't success

little meadow
#

Does it have more than that websocket singleton? (I'm not sure why it needs to be a Mono in the first place, but I'll assume it does)

#

Generally you can do something like someDDOLobject.gameObject.scene.GetRootGameObject().ForEach(go => Destroy(go)); to kill them all

#

but that's... quite barbaric...

heady iris
heady iris
#

destroying everything in the DDOL scene seems like a terrible idea

spring creek
#

!collab

tawny elkBOT
heady iris
#

Stop spamming.

spring creek
#

Posting the same thing to more than one channel is spamming here

heady iris
#

especially when it belongs in none of the channels

spring creek
#

Also, that kind of post is not allowed, as you've been told
"We do not accept job or collab posts"

rigid wraith
#

I have a problem with circle position on object

        float rayDistance = 2.5f;
        Ray ray = new Ray(Camera.transform.position, Camera.transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * rayDistance);

        if (Physics.Raycast(ray, out hit, rayDistance))
        {
            if (hit.collider.gameObject.CompareTag("Tree"))
            {
                TargetPrefab.transform.rotation = hit.collider.transform.rotation;
                TargetPrefab.transform.position = new Vector3(hit.collider.transform.position.x, hit.point.y, hit.collider.transform.position.z);
                TargetPrefab.transform.localScale = new Vector3(hit.transform.localScale.x, TargetPrefab.transform.localScale.y, hit.transform.localScale.z);
                TargetPrefab.SetActive(true);

                if (Input.GetMouseButtonDown(0))
                {

                }
            }
            else
            {
                TargetPrefab.SetActive(false);
            }
        }
        else
        {
            TargetPrefab.SetActive(false);
        }```
little meadow
#

what is the problem?

rigid wraith
#

I have a problem with circle position on object

little meadow
#

and the problem is? 🙂

rigid wraith
#

the position is not aligned with the rotation, i.e. where I have it selected with the mouse, a circle should appear in the center of the object with a given y position and it should work with rotation

thin prism
#

Hi, so I have a problem with the spawning my menu, I want my menu to spawn at my cameras location plus an offset when I press escape, here is the code:
"escMenu" is my menu, and teh script is part of the main camera. My menu ends up spawning at teh coordinates the prefab is located. Why is this, and how can I change this, thank you for any help in advance!

round violet
#

i got a drop down but for some reason i cant select Cable

#
 int index = 0;
 index = EditorGUILayout.Popup(index, options);
 if (GUILayout.Button("Create"))
 {
     InitList(options[index]);
 }
little meadow
knotty sun
#

@round violet Got it kinda working but it's not perfect yet. I'll contine working on it then send you the code

little meadow
round violet
#

i @ you earlier to tell you that :(

#

no i feel bad because you worked on it

knotty sun
#

missed it, don't feel bad, I need this for myself anyway

round violet
#
public class CustomConsoleDebug : EditorWindow
{
    private Dictionary<string,List<string>> _data = new();
    private ListView _listView;
    private string ConsoleId = "";

    //private static Dictionary<string, EditorWindow> _windows = new();
    private string[] options = new string[] { "Player", "Cable"};


    [MenuItem("Custom/Custom Console Debug")]
    public static void ShowWindow()
    {
        EditorWindow window = CreateInstance<CustomConsoleDebug>();
        window.titleContent = new GUIContent("New console");
        window.Show();
    }

    void OnGUI()
    {
        if (ConsoleId.Length == 0)
        {
            int index = 0;
            index = EditorGUILayout.Popup(index, options);
            if (GUILayout.Button("Create"))
            {
                InitList(options[index]);
            }
        }  
    }

    public void InitList(string id)
    {
        titleContent = new GUIContent("Custom console: " + id);
        ConsoleId = id;

        _listView = new();
        _data.Clear();

        _data[ConsoleId] = new List<string>();


        _listView.makeItem = () => new Label();
        _listView.bindItem = (item, index) => { (item as Label).text = _data[ConsoleId][index]; };
        _listView.itemsSource = _data[ConsoleId];
        
        rootVisualElement.Add(_listView);

        CustomDebug.LogAction += AddData;
    }

    private void AddData(string key, string text)
    {
        _data[key].Add(text);
        _listView.RefreshItems();
    }
}
public class CustomDebug : MonoBehaviour
{
    public static event Action<string,string> LogAction;
    static public void AddDebugLog(string key, string text)
    {
        LogAction(key,text);
    }
}

use :

            CustomDebug.AddDebugLog("Player","moving");
#

prob not good because it has one dict for all data

#

but for know it works

knotty sun
#

that's cool, glad it's working for you

round violet
knotty sun
#

move this to class level

int index = 0;
round violet
#

worked ty

#

damin i forgot dicts doesnt serialize

#

have to add some init dict code

#

is there a GetWindow but for all windows ?

knotty sun
round violet
#

the event action is only bind on creation, so when reloading i have to bind it again

knotty sun
#

you could do it via reflection though

#

one problem I see, your system only works when the editor window is open

round violet
#

well yeah, since if there is no listener the action errors

little meadow
#

action shouldn't error! hey!

round violet
#

but i will always have my windows open, and if not, ignore the debug

round violet
little meadow
#

LogAction?.Invoke(key,text);

round violet
#

instead of LogAction(key,text); ?

little meadow
#

yes

knotty sun
#

try using a Queue

round violet
#

i still need my window to bind again after compiling

little meadow
#

you can make something on the editor side that stores the messages as they come and is always subscribed

knotty sun
#

Lot's of ways to do this, I'm gonna make a generic plugin coz Unity Console sucks

little meadow
#

Am curious to see! I've thought of doing that, but never got to it. I wanted to be able to ignore messages by some patterns and stuff like that 😄

knotty sun
#

exactly filters like the Android LogCat package

round violet
#

so actions arent serialized

languid hound
#

Anyone able to assist? This happened last time I tried this

        RaycastHit[] leftHit = Physics.SphereCastAll(leftHand.position, 0.05f, (leftHandTarget.position - leftHand.position).normalized, 5f, handInteractableLayers);

        if (leftHit.Length == 0)
        {
            leftHand.transform.position = leftHandTarget.position;
        }

        else
        {
            foreach (RaycastHit hit in leftHit)
            {
                Debug.Log(hit.collider.name);
            }
        }

For whatever reason this is finding objects half way across the map despite the fact the surrounding area is empty

#

It's aiming from an empty transform to an xr controller and hitting the floor? The only time it hits the controller is when the controller is higher than it

#

Keep in mind the controller is way above the floor and almost on the same y level as the controller

hard viper
#

My IDE shows Unity methods in blue, which is weird. Is this happenning due to some setting?

languid hound
#

That just randomly happens it happens with VSC too it's weird

little meadow
languid hound
#

It happens on a lot of methods like FixedUpdate

#

Oh wait I'm an idiot

hard viper
#

on mac, this never happened to me.

languid hound
#

Unity methods are highlighted in blue custom methods are yellow

hard viper
#

and it's super weird

languid hound
#

Always been like that for me since 2019 ¯_(ツ)_/¯

little meadow
#

yeah, I assumed it's the default and didn't care too much, but an option might exist - google ot chatgpt should know! 😄

little meadow
languid hound
#

Now my only issue is once the spherecast hits something it cant actually come off of it because it's constantly hitting it

languid hound
#

So the spherecast's origin is the leftHand position. If it doesn't hit anything it moves to the XR controller

#

But the issue is it can move to the controller and touch the ground

#

And when that happens it's stuck in a loop of touching the ground

#

Sorry if my explanations suck I don't really know how to explain it

round violet
#

can i make action listening to a specific arg

#

for example :

i have multiple instance of MyClass
each one have an id

when invoking the action with a param, if the given id matches an existing id in the instances of MyClass, then call the action of that instance

round violet
#

also, can you disable Auto using ?

#

VS keeps adding uncessary stuff

cyan hornet
#

Why is this happening?

#

I tried to add this component ladder on the FPScontroller

fervent furnace
#

i think you need to implement your own one
btw if the objects know which specific arg they should listen, then why not having an dictionary

Dictionary<value of the special arg,List<the objects>>
```then the publisher calls method of the objects in the list and passing other args, you dont even need event
#

or just early return

spring creek
cyan hornet
#

this file i the one i wanna add on FPSController

fervent furnace
#

no, not reply to you

spring creek
thin gale
#

ndk 21.4.7075529 detected. unity requires NDK r21d(64-bit) (21.3.6528147). how i can fix this error

cyan hornet
# spring creek The class, not the script Can you show the code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class Ladder : MonoBehaviour
{

    public Transform playerController;
    bool inside = false;
    public float speed = 3f;
    public FirstPersonController player;
    public AudioSource sound;





    void Start()
    {
        player = GetComponent<FirstPersonController>();
        inside = false;


    }



    void OnTriggerEnter(Collider col)
    {

        if (col.gameObject.tag == "Ladder")
        {
            Debug.Log("TouchingLadderTrue");
            player.enabled = false;
            inside = !inside;
        }


    }

    void OnTriggerExit(Collider col)
    {

        if (col.gameObject.tag == "Ladder")
        {
            Debug.Log("TouchingLadderFalse");
            player.enabled = true;
            inside = !inside;
        }


    }

    void Update()
    {
        if (inside == true && Input.GetKey("w"))
        {
            player.transform.position += Vector3.up /
            speed * Time.deltaTime;
        }

        if (inside == true && Input.GetKey("s"))
        {
            player.transform.position += Vector3.down /
            speed * Time.deltaTime;
        }

        if (inside == true && Input.GetKey("w"))
        {
            sound.enabled = true;
            sound.loop = true;
        }
        else
        {
            sound.enabled = false;
            sound.loop = false;
        }




    }


}

spring creek
cyan hornet
#

I think there was one yellow text error and I pressed ignore or something and it has now disapeared.
can i go back and see it? is there any way or should i just try to undo history and try to un-import and import these assets again to see if there's an error in them?

#

I can't undo the import though

vague hearth
#

How do different mechanics work at different levels in the like Pummel Party game? Does anyone have knowledge about this? Or can you help me with which keyword to research the subject?

spring creek
cyan hornet
spring creek
#

Just to make sure the errors aren't disabled

cyan hornet
#

oh, wait, you mean this?

spring creek
#

That is why the script can't be added most likely

hard viper
#

when I call playerInput.Gameplay.MousePosition.ReadValue<Vector2>();, this normally works to get the current mouse position. but if I click off of the gameplay area, and then click back into the gameplay area, it always returns Vector2.zero. Any idea why?

cyan hornet
#

oh wow, I actually got more with where that came from

#

Btw can I turn the ladder script into python? because I don't understand shit in C++. 😦

#

I was told you could use these scripting nodes similar to those they have on blender or unreal engine 4 where you connect the nodes and thats how you basically go on without any code. Or that you could code in any language but I dont know how to do that here.

spring creek
spring creek
cyan hornet
#

so does that mean it's already in FPScontroler?

#

imma try running it to see if he can actually climb ladders and stuff

spring creek
cyan hornet
spring creek
#

Ladder is most likely NOT on the fpscontroller

spring creek
# cyan hornet

Yes. The game cannot run until every red compiler error is removed

#

You have to go through the project window and remove all the duplicate files

cyan hornet
#

I searched "ladder" on the assets and I only got this one scripting file of C#, nothing else. The other 3 files seems to be something else..

#

sound and icon.

spring creek
#

It's the other assets

#

Sway, CameraUIZoom, Flashlight are the first three errors

#

It's all stuff in the PublicSeriesFolder folder

cyan hornet
#

ok you know what

#

imma delete this entire folder and only upload each file seperately whenever I need it cause this seems like it would never work otherwise

spring creek
#

Ladder has no errors

#

The other errors are just preventing that script (or ANY script) from being added

cyan hornet
#

maybe these scripts are stored inside of the FPS controler?

spring creek
#

Not any gameobject

cyan hornet
spring creek
#

In the project window only

#

It has to do with assets, not gameobjects

#

FPSController has nothing to do with this issue

cyan hornet
#

aight

#

so what can i do with it?

spring creek
#

I meant to circle the word project btw, not the search for ladder

cyan hornet
#

oh ok gotcha

#

do we have any idea how can you quickly find any duplicate files?

#

cause there's like a million files here

spring creek
cyan hornet
#

btw

#

i noticed something odd

#

very odd

#

for every C# file there's a META file?

spring creek
#

That is normal, and necessary

cyan hornet
#

ok hopefully i didnt delete standard ASSets

#

or imma restore them

tawdry jasper
#

Is there any good reason to ever use SendMesasge in a medium sized production project? I saw this in an asset I imported and had to research what it's for, and I can think of many other ways to accomplish the same thing? (I think I saw send messages in the new input module player input, so maybe I am using it anyway?)

cyan hornet
#

Ok so I deleted the 2nd asset package

#

I only kept these and i still get these errors

#

this is so confusing, i love it

little meadow
hard viper
#

in VS for mac, my TODO were always bright purple. Would anyone know where that option is for windows?

hard viper
#

yes

#

did that not normally become purple for you if you write TODO in a comment?

#

that just happened for me out of the box on mac

spring creek
hard viper
#

ty. I'll give it a shot

#

one of them would not install. went through extensions tab in VS to find something that might be promising

chilly surge
#

Isn't VS for Mac dead?

hard viper
#

no longer supported, but for the year I've been using it, it was good

chilly surge
#

Might want to switch to Rider or VS Code soon.

icy comet
#
{
    public class Attack : Action
    {
        public Transform killer;
        public KillerChase killerChase;
        private bool isAttacking = false;
        private bool isDead = false;
        public FogOfWarRevealer3D revealer;

        public override void OnStart()
        {
            killer = GetComponent<Transform>();
        }

        public override TaskStatus OnUpdate()
        {
            Character.Survivors.Survivor survivorComponent = killerChase._target.GetComponent<Character.Survivors.Survivor>();

            if (survivorComponent == null)
            {
                return TaskStatus.Failure;
            }

            PlayerStatus status = survivorComponent.playerStatus.Value;

            if (status == PlayerStatus.KnockedDown)
            {
                isAttacking = false;
                isDead = true;
                revealer.hidersSeen.Clear(); 
                return TaskStatus.Success;
            }

            RaycastHit hit;
            if (Physics.SphereCast(killer.position, 4f, killer.forward, out hit, LayerMask.GetMask("Survivor")) && !isAttacking && !isDead)
            {
                isAttacking = true;

                Debug.Log("Attacking");

               
                if (status == PlayerStatus.Injured)
                {
                    survivorComponent.playerStatus.Value = PlayerStatus.KnockedDown;
                }
                else
                {
                    survivorComponent.playerStatus.Value = PlayerStatus.Injured;
                }

                return TaskStatus.Running; 
            }
            else
            {
                isAttacking = false;
                return TaskStatus.Failure;
            }
        }
    }
}
#

can someone help pls? the action keeps running even after the survivor is knockedDown

#

I'm using behaviour tree

orchid abyss
#

animation override breaks the rolling animation for whatever reason

vagrant blade
#

Nobody is going to do free work for you, no.

cyan hornet
#

Sure.

thin gale
#

humanity is not alive

hard viper
#

is there a method to search for all components of a given type? Slow is fine, because this is for editor mode.

#

is public static T[] FindObjectsOfType(bool includeInactive); the recommended way?

cyan hornet
thin gale
surreal cobalt
#

Anyone having any problems with Unity Editor 2022.3.20f1 with EditorApplication.delayCall: UnityEditor.Sequences.SequenceIndexer.InitializeWithExistingData when recompiling?

Currently, it takes 1 min and 30 secs running that command after script compilation.

still badge
#

is it possible to do like a timer or something, i have a flashlight and want its battery variable to decrease every 3 seconds. I tried with Task.delay but not working it just ignores it

leaden ice
simple egret
#

If the battery level is a float, you can subtract Time.deltaTime * (1/3f) directly, to have a decrease of one third per second, or 1 for each 3 seconds.

still badge
vagrant blade
worn crystal
#

is there any way that i can play/preview animations in editor via script?

orchid swallow
#

Hey Everyone! Can someone explain me why I can't generate lightmaps? I made sure to create a light profile under the scene category so that won't be the issue. Thanks!

heady iris
#

Are you currently in play mode?

orchid swallow
#

omfg, I was

#

that's so silly, didn't even notice

#

Thanks mate

hard viper
#

these errors confuse me

#

customDrawLogic is a singleton that should be destroyed when I swap scenes. Everything works fine. But when I come back into the scene, objBase.customDrawLogic is null (unity null, it's a destroyed object)

#

but when I follow debugger, it just skips that whole if statement! even though it is null!

leaden ice
hard viper
#

I suspected it is interface-related

leaden ice
#

since the interface is not a derivative of UnityEngine.Object, it will not use Unity's overridden == comparison

#

so it will be checking against true null

heady iris
#

Correct.

hard viper
#

I see, which is why it skips

leaden ice
#

you could do:

if (objBase.customDrawLogic is UnityEngine.Object uo && uo == null)```
hard viper
#

that is smart. I'll give that a shot

#

yeah, throwing in "as Object" made it all work.

#

thanks

past kite
#

Is there a mechanism to throttle the rate of events? I need to use this in many places. Player smashes the keyboard but I only want to process X keystrokes per second. Same for object spawning. See it like a network bandwidth limiter on a firewall.

hard viper
#

you would need to add your own logic for that tbh

#

object spawning should just have a cooldown. that does not mean you should filter player input

chilly surge
hard viper
#

you should always envision the player inputting the worst possible combination of inputs, and the game logic should be able to detect everything, but still react properly

latent latch
#

gotta always put your game through the "cat on keyboard" tests

hard viper
#

pause buffering, a goddamn turbo controller, smashing your face into the whole keyboard at once… the game better still work

latent latch
#

I had a project to create a shell and one of the tests was the instructor basically smashing their hands onto the keyboard to check if it crashed

hard viper
#

good instructor lol

heady iris
#

one thing i need to do is write an input fuzzer that just fires a massive pile of random inputs at my game

#

random stick positions every frame, 0.5x A presses, the works

hard viper
#

one pattern I do is to put integer locks on things like pausing.

#
public void RequestPause() { pauseRequests++;
if (pauseRequests == 1) SetPause(true);}

public void RequestUnpause() { 
Debug.Assert(pauseRequests > 0, “Can’t have negative requests!”);
pauseRequests- -;
if (pauseRequests == 0) SetPause(false);}
#

you’re basically storing the number of things independently interested in (un)pausing, and only doing it once no individual service is requesting the game to be paused.

heady iris
#

oh yeah, this is a good idea

hard viper
#

the other is the timestamp method, which i’ve shown before, which is very good for buffered inputs

little meadow
#

I've done quite a lot of "reference counting" in my current project at work.... so many things that can be requested by several completely unrelated things at any time

#

At some point I started using RequestSomething(Object requester) and putting those in a hashset... to allow detecting of who wants access, who releases access, for when we have issues with something requesting a thing, and another one "releasing" it

#

or for when we wanna give more freedom to the requesters to be lazier 😄

proper pier
#

I'm refactoring all of my movement code and I'm trying to make it future-proof. What is the best way to implement a state machine? Should I have one class essentially dedicated to taking a bunch of variables from all over the place and outputting a state? I will have a state for movement based upon position (grounded, in air, etc) and a state based upon combat status (stunned, slowed), etc

latent latch
#

you can pretty much 1:1 the animation blend tree's statemachine or get an idea from that

hard viper
# proper pier I'm refactoring all of my movement code and I'm trying to make it future-proof. ...

I’ e done this several times. My advice is to make these separate classes:

  1. Player movment. This primarily uses an enum to represent player state (like idle, jumping, swimming)… It updates this enum based on player inputs and:
  2. Player contact state. This class gets read by playermovement for logic, but it gets filled by:
  3. Contact checker. This determines player grounding state, if you’re on ice, etc. And puts that info into ContactState.
  4. Player animation controller, which reads the enum in playermovement (and whatever flags) to know what to show.
  5. Player logic for reading contact state and other stuff to know life/death/HP etc
  6. A movement stat scriptable object to just hold values for things like run speed, jump force… just settings. It keeps playermovement much simpler.
#

one thing that makes player movement really bloated and overcomplicated is to try to do everything in it

latent latch
#

I've got a PlayerController -> Motor class to separate the input from the state logic a bit more instead of bloating it into a single script

hard viper
#

i’ve seen a lot of PlayerMovement scripts that handle player HP, animation state, ground check, and player movement…. it always ends as a trainwreck

#

player movement gets complex. stuffing all that shit into it is a terrible idea

#

also, more bools more problems

#

bools are like juggling. a few are ok. 20 is not ok

latent latch
#

can always do bidirectional references so you can always grab references from the top level

#

instead of deriving too deep

#

or bloating single scripts

#

otherwise events

hard viper
#

i try to make it more like one after the other.
contact generator fills out contact state.
playermovement reads contact state and updates player state enum.
animation script reads player state.

proper pier
#

I think I would want a class that determines position state, sends that output to movement state and combat state. The messy part is when movement states and combat states interact with each other both ways

hard viper
#

player movement needs all info before that

#

just map out the timeline

proper pier
#

yeah you're right, fighting state should already be pre-calced based on prior frames

#

and updates can be made on the current frame too ofc

#

then send that all to movement state

hard viper
#

yeah, just make sure to stage it

proper pier
#

what does that mean?

hard viper
#

do not have player movment updating player state before and after animation script reads it

#

stage 1) generate contact information
stage 2) determine player state
stage 3) determing output logic

#

do not be updating info from 1 in the middle of 3

#

1 feeds 2 feeds 3

proper pier
#

ah yeah, I plan on having all the states finish their calcs and then sending the info to executing player movment, animation updates, server updates, etc...

tribal coral
#

Hi! Do anyone know what is wrong with this script?? I want it to add 1 if there is a game object with the tag "Farm" in range but it starts adding up infinitivly as long as there is one in the range

proper pier
#

Thank you guys

cold parrot
cold parrot
#

You make a list of all farms and then count them all each update

tribal coral
#

So how should I do??

cold parrot
#

if a farm is in range you have to remove it from the list and add it to an already-in-range list

tribal coral
#

But how do I make so that the FindGameObjectsWithTag wont just place it back again?

cold parrot
#

then check that list if a farm goes out of range and move it to the first list again when that happens

tribal coral
#

Its supposed to be in the update function

cold parrot
#

It shouldn’t be

#

find is a terrible function to call in update

tribal coral
cold parrot
#

i have just explained how you do it with two lists

#

that is the correct way if you don't want to use physics checks

simple egret
#

When I read "in range", you probably want to use some sort of SphereCast to limit the result set to what's close enough

#

It's less expensive than using Find, at least

cold parrot
#

the find is not the problem here

#

its an issue of converting a state into an event

simple egret
#

It would be an improvement, but yes they need to cache what farms they've already seen in some list

cold parrot
#

you make two lists, inRange and outOfRange fill them by iterating with whatever your find or overlap returns and range check yields. then iterate them each frame and move them between the lists whenver their respective condition for being in the list changes, whenever you detect such a change, fire your event (your count + 1)

#

thats how you manually create a TriggerEnter and TriggerExit event.

#

there is opportunity for optimization but thats the principle you've been missing in your code

tribal coral
#

@cold parrot Okay i think I got a solution. All I need to do now is to remove i from the array.... which I dont know how to do 😂

cold parrot
#

you cant remove items from an array, only set them to null, which makes no sense in your case

cold parrot
#

as i said above, fill LISTs with your farms from the ARRAY in start

#

then iterate the LISTs in update and move items between the lists

#

(you can use HASHSETs for better performance)

tribal coral
#

How do I move items between lists then?

cold parrot
#

remove from one, add to the other

tribal coral
#

but you said that I couldnt remove an item from a list

cold parrot
#

you cant remove items from ARRAYs

tribal coral
#

arent lists and arrays the same thing??

cold parrot
#

no

tribal coral
#

Can I use lists in the same way as i use Arrays in my case??

cold parrot
#

no

#

internally a list automatically maintains a gapless array of variable size

#

but that is irrelevant here

#

array is fixed size and has no add/remove

#

list is variable size and has add/remove

tribal coral
#

But I dont really understand how lists are going to help me if I cant use them in the way that im using arrays. Can I make so that the for loop skipps items from the list??

cold parrot
#

yes

tribal coral
spring creek
#

You can place a value at an index

#

Which is not the same as adding, and it is the key difference here

cold parrot
spring creek
tribal coral
spring creek
tribal coral
#

And I want to know how

spring creek
tribal coral
spring creek
#

Changing from an array to a list is not that big of a change

tribal coral
#

Okay. I will look into it

tribal coral
#

But I will look into it

#

Thank you

cold parrot
#

@tribal coral


List<GameObject> _inRange = new();
List<GameObject> _outOfRange = new();
void Start()
{
  GameObject[] farms = FindObjectWithTag("Farm");
  _inRange = farms.Where(it => Vector3.Distance(transform.position, it.transform.position) <= maxDistance).ToList();
  _outOfRange = farms.Where(it => Vector3.Distance(transform.position, it.transform.position) > maxDistance).ToList();
}

void Update() {
  for(int i = _inRange.Count -1 ; i >= 0; i--) {
    if (Vector3.Distance(_inRange[i].transform.position, transform.position) > maxDistance) {
      _outOfRange.Add(_inRange[i]);
      _inRange.RemoveAt[i];
    }
  }
  for(int i = _outOfRange.Count -1 ; i >= 0; i--) {
    if (Vector3.Distance(_outOfRange[i].transform.position, transform.position) < maxDistance) {
      _inRange.Add(_outOfRange[i]);
      _outOfRange.RemoveAt[i];
    }
  }

  // your count is just _inRange.Count
}
agile saffron
#

Hello! I have animations for a walk cycle for a character right now in unity (haven't messed with the controller yet I'm nervous of messing it up) but I'm not sure how to apply these animations to the player movement script I already currently have. I can send the script if needed but I'm not really sure where to start looking bc just trying to look it up on forums is confusing to me (I am,, really not good at coding)

agile saffron
#

oh! ok sorry I thought I was in that chat

past kite
#

Ok, so I wrote my own rate controller. Since I was worried about key clashes, I used LINE + FILENAME as unique keys. Is there a better way to get unique keys in C#?

#

Basically something better for GetKey()

past kite
cold parrot
past kite
cold parrot
#

its just a handle

#

so the caller can pass it back on subsequent checks, identifying the timer it has claimed

#

you internally associate the handle with the call & timer

past kite
# cold parrot its just a handle

That's unfortunately beyond my C# knowledge. As you might gues from LINE, I did mostly C. So I unfortunately don't fully understand what you mean.

cold parrot
#

well if you know C, handles should be your bread and butter 😄

past kite
cold parrot
#

anyway, in C# you'd likely make an instance of a rate limiter for each resouce you want to limit access to and just have the user check that instance

past kite
#

So less code. Less space for bugs.

cold parrot
#

think of it as a sync primitive