#archived-code-general

1 messages Β· Page 191 of 1

normal stump
#

yup

heady iris
#

It looks like this makes the main thread run that method whenever it gets a chance to

#

which would be roughly equivalent to having a job produce a list of things you want the main thread to run

normal stump
#

yeah that was my point

#

except the code never leaves the task

heady iris
#

although, does Invoke also block the thread until the action is finished running?

normal stump
#

yes it does

#

but it would be the same as running any other code

#

what I generally do in WPF is do all the network IO in the task, then invoke the main thread and update some UI state there, which takes no time

heady iris
#

I see. I'm not aware of a way to do that, but there's a good chance I'm just not familiar enough with writing async code (in the context of Unity) to know

#

right

quartz folio
#

I've already posted the way to do it, twice

normal stump
#

I'm reading it πŸ™‚

errant shore
#

A script that makes as soon as you click the button it moves your object to another scene

#

please

quartz folio
#

Demands are not how you get answers here

#

ask an actual question about a problem you are having

normal stump
#

also the demand is unclear

heady iris
quartz folio
normal stump
#

yes it does

#

sorry about that πŸ˜›

#

I was just trying to understand the flow of it, it's all clear now

#

basically calling one of the methods will decide where/when the task will run

heady iris
#

Speaking of doing things in the background, I have an annoying problem.

I want to do a huge number of raycasts against level geometry. RaycastCommand has been very helpful for this, but there is one issue: many things force all pending physics batches to finish before they can proceed. This includes stuff like moving character controllers or recalculating bounding boxes after LateUpdate is finished.

I just care about the level geometry, so there should be no need for this. These colliders aren't changing at all.

I tried creating a separate scene (with its own physics scene), but it looks like batches in physics scene B still have to complete before anything that happens in physics scene A can proceed.

Is there anything I can do about this?

#

It's possible that I just botched setting up a separate physics scene. I'll check that I actually did that properly.

shy notch
#

What do these errors mean after fixing merge conflicts on github?

hexed coral
#

Corrupted assets, you likely did something wrong on the merge

shy notch
#

I hate git so so much

lean sail
#

what merge conflicts, did you manually try to fix a scene file or something?

lean sail
#

well good thing now is you can revert your changes

#

since you're using git πŸŽ‰

spark yew
#

i have been trying and failing to implement an inventory system to my battle system for weeks now

my end goal is to make it like the mario & luigi system; i've tried a bunch of tutorials however can't find one that particularly suits my needs

how would i be able to make an inventory system similar to it?

any help linking me to the proper resources n such would be appreciated

wintry crescent
hexed coral
wintry crescent
#

And when item is used, just spawn the gameobject that's referenced, with the player for example as parent, and let it do what it needs from there

spark yew
#

hmmm alr

wintry crescent
#

You can use an external merge tool in most gui git clients

#

You can use that

wintry crescent
hexed coral
#

You can, but shouldn't. That's how you lose progress

wintry crescent
#

Just add the tool, right click the conflict, merge using external tool and it'll solve... Most things. Then edit the rest by hand in notepad++. That's my usual approach

hexed coral
#

Keep your scenes modular, don't let two people edit the same one in different branches

wintry crescent
gaunt wren
#

Anyone here use Sebastian Lague's BΓ©zier Path Creator tool? I'm using Unity 2021 and some Spline paths drift from their position slowly over time. It's really annoying having to move the splines back into place every time I have the spline object selected.
I'm using the github version as it is the most recent version.
Has anyone found a solution to the path drifting?

leaden ice
gaunt wren
#

for clarity, apparently it happens if the spline object is a child of another object while having a rotation applied to it

errant shore
gaunt wren
vagrant blade
normal tide
#

I am building on meta quest 2 and I am getting this error

rigid island
#

is not code

normal tide
#

U told me to do so

rigid island
#

You mean my reply to someone else ?

spiral ibex
rigid island
#

what shape overlap do you need that you can't do with primitives?

spiral ibex
#

I would like it to not be tied into any shape is my problem.

#

I wanted to serialize a collider, drag and drop any collider on it and be done with my day

#

I was hoping for a cone shape in the future for example, this puts a dent in my plans :p

rigid island
#

hmmm you can make it Trigger and use OnTrigger I suppose

#

if you're doing a vision cone use something like a Dot product for FOV

#

then fire raycasts to make sure you're not blocked or something

spiral ibex
#

Honestly if it means keeping a list of objects within the area using triggerenter and triggerleave I may just scrap it, it is a very weird omission to have in physics module

fringe ridge
#

Any ideas why parallax background might be flickering?

rigid island
#

🀷 layer order fighting each other maybe ?
depends what "flickering" looks like and when its happening exactly

#

are you sure its code related?

fringe ridge
#

I mean the whole parts just disappear and appear, not just the sides

#

im not sure

#

it happens really fast, but is really annoying

spiral ibex
#

some kind of culling perhaps?

placid ivy
#

Hello, anyone know if it's possible to set the IP where the client must connect in NetCode for Entities ? (I've pack in ded server, and want to connect to ded deploy in remote server, but i didn't find anyway to set IP)

fringe ridge
#
    {
        float temp = cam.transform.position.x * (1 - parallaxEffect);
        float dist = cam.transform.position.x * parallaxEffect;

        transform.position = new Vector3(startpos + dist, transform.position.y, transform.position.z);
        if (temp > startpos + length) {
            startpos += length;
            
            if(textureIndex >= 0) {
                textureIndex++;
                if (textureIndex >= spriteArray.Count)
                    textureIndex = 0;

                int tempIndex = textureIndex - 1;
                if (tempIndex < 0)
                    tempIndex = spriteArray.Count - 1;

                GetComponent<SpriteRenderer>().sprite = spriteArray[tempIndex];
                transform.GetChild(1).GetComponent<SpriteRenderer>().sprite = spriteArray[textureIndex];
            }
        }
    }``` if this helps
#

maybe you see my mistake

spring creek
fringe ridge
#

this is the hiearchy

#

they're all sprite rendereres, so order doesnt matter I think?

spring creek
#

Nothing to do with the hierarchy

#

If you don't know what the sorting layers are, then they are probably all Default, and order 0, so it's layer fighting causing the flickers

#

Oh, here

rigid island
short wing
#

SpriteRenderers arent supposed to zfight

#

are all gameobjects using sprite renderers ? are you using 2D Renderer URP ?

mystic ferry
#

huge

shell scarab
#

I think you're being sarcastic but they're most likely used in two different ways internally.

similar difference to between can be turned on/off and is on/off probably.

spring creek
# short wing SpriteRenderers arent supposed to zfight

Oh wow. Ok. I always carefully lay out the sorting layers to avoid it. I know it's still important for having the order correct, but that is hilarious that I thought so for so long.

Thanks for the correction!

Edit: sorry for that heroshrine haha.

shell scarab
#

nah u good lol

#

i need to code but i got starfield and just want to play that sadblob

short wing
spring creek
short wing
spring creek
gray mural
#

why isn't OnEnable called in the script that is attached to DDOL GameObject? do I have to call it manually in SceneManager.sceneLoaded += _ ?

rigid island
gray mural
#

is there a method that is called in ddol when scene changes too?

#

except of my previous variant with action

rigid island
#

the one you posted but no built in call

gray mural
lean sigil
#

I'm using this function to simulate fish swimming in a pond, and have them go toward a pellet if one is present.

void SearchSwimPoint()
    {
        //return a random point within range
        RaycastHit info;
        float travelRange = Physics.SphereCast(koiTransform.position, pellet && waterVol.bounds.Contains(pelletPos) ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange, Vector3.zero, out info, 0f) ? info.distance : pellet ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange;
        swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + new Vector3(Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange));
        while (!waterVol.bounds.Contains(swimPoint) && !(pellet ? Vector3.Distance(swimPoint, pelletPos) < Vector3.Distance(koiTransform.position, pelletPos) : false))
        {
            swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + new Vector3(Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange));
        }
        swimPointSet = true;
    }
#

However, for some reason, these fish are swimming to the point (0, 0, 0) when the pellet is located at (0, -0.1, 0).

rigid island
#

jesus how can you even read this function

#

ternary can be ok for a 1 liner but this is just....

gray mural
lean sigil
#

Also, once the pellet is destroyed, it shows up as "missing". Does that mean the object is not "null"?

lean sigil
somber nacelle
gray mural
#
float range => Random.Range(-travelRange, travelRange);

float travelRange = Physics.SphereCast(koiTransform.position, pellet && waterVol.bounds.Contains(pelletPos) ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange, Vector3.zero, out RaycastHit info, 0f) ? info.distance : pellet ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange;

do
{
    Vector3 offset = new Vector3(range, range, range);
    swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + offset;
}
while (!waterVol.bounds.Contains(swimPoint) && !(pellet ? Vector3.Distance(swimPoint, pelletPos) < Vector3.Distance(koiTransform.position, pelletPos) : false));

swimPointSet = true;
lean sail
# lean sigil I'd be glad for any suggestions.

nested ternaries are quite unreadable. id just split this up and cache some of the values then use them when needed. You have 1 line that contains a spherecast, .contains, .distance, another .distance and just other stuff I odnt even know what is for

gray mural
#

cuz I cannot see the purpose of your code so well

gray mural
lean sigil
# rigid island jesus how can you even read this function

The way this function is supposed to work is it has the fish choose random positions within a specific range.

If no pellet is present, the SphereCast's radius for its travel range is set to its SwimPointRange. If there is a pellet present and is contained within the water collider, the SphereCast's radius is set to the distance between the fish and the pellet.

Next it acquires a point toward which it will swim. If no pellet is present, one is selected randomly from any point within the specified radius. If there is no pellet and the destination point is outside of the water, or there is a pellet and the distance from the fish to the pellet is greater than or equal to the distance from the destination point and the pellet and the destination point is outside of the water, then it selects a new point until those conditions are rendered false. This way the fish stays in the water and only goes toward the pellet.

lean sigil
#

It seems they just continue swimming toward that point even after the pellet is destroyed.

gray mural
#

oh, actually you use distance there

#

somehow

lean sigil
#

And they seem to not be swimming in the right direction.

gray mural
#
pellet && waterVol.bounds.Contains(pelletPos)

actually I guess that the issue is that this is false

#

because the distance should be ok

Vector3.Distance(pelletPos, koiTransform.position)
#

try to make your code human readable and put some prints I guess ?

lean sigil
swift falcon
#
  "Data": [
    {
      "Day": 1,
      "Month": 1,
      "Year": 2023,
      "Money": 0,
      "Loan": 0,
      "Emi": 0,
      "CutDay": 0,
      "RawMaterial": 0,
      "NumberE": 0,
      "MacLock": [ false, true, true ],
      "MacP": [ false, false, false ],
      "MacE": [ 0, 0, 0 ],
      "Product": 0
    }
  ]
}```
#

this is my json file

#
 {
     public int Day;
     public int Month;
     public int Year;
     public int Money;
     public int Loan;
     public int Emi;
     public int CutDay;
     public int RawMaterial;
     public int NumberE;
     public bool[] MacLock;
     public bool[] MacP;
     public int[] MacE;
     public int Product;
 }```
#

this is my c# file

#

not complete but the important snippet

#

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <347e3e2bef8c4deb82c9790c6e198135>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0)

#

I am getting this error

#

i think the issue is

#

the incorrect data type i used for maclock,macp,mace in my c# file

dusk apex
swift falcon
#

i don't know what stack trace is

dusk apex
#

Show the complete error

swift falcon
#

this is the console log

dusk apex
#

Show the complete error uncut

lean sigil
#

OK, somehow it's working now.

somber nacelle
swift falcon
lean sigil
somber nacelle
gray mural
swift falcon
#

idts

lean sigil
#

But progress is still progress. πŸ˜„

somber nacelle
lean sigil
#

This doesn't fix them not swimming toward the pellet.

#

As in, when it's not at (0, 0, 0).

swift falcon
lean sigil
#

I'll post code related to that later.

gray mural
lean sigil
#

I had, tho, but I will detail this in a bit.

#

Also I forgot to mention that for whatever reason, when the fish are swimming toward a pellet, they move rather slow.

#

Now for code.

#

Here's where the pellet's position gets assigned and stored:

    void Update()
    {
        Seek();
        if (pellet)
        {
            pelletPos = pellet.transform.position;
        }
    }

And here's the movement code for the fish:

    void Seek()
    {
        if (swimPointSet && !pellet && pelletPos == swimPoint)
        {
            swimPointSet = false;
        }
        if (!swimPointSet)
        {
            SearchSwimPoint();
        }
        else
        {
            Vector3 swimPointDist = transform.position - swimPoint;
            float travelMag = swimPointDist.magnitude;
            RotateToTarget(swimPoint);
            ApproachTarget(swimPoint);
            if (travelMag < stopDistance)
            {
                swimPointSet = false;
            }
        }
    }

    void RotateToTarget(Vector3 targetPos)
    {
        // get vector from us to the target
        Vector3 targetDir = targetPos - koiTransform.position;

        // get a vector that is somewhere between us and the target direction
        Vector3 newDir = Vector3.RotateTowards(koiTransform.forward, targetDir, followSpeed * Time.deltaTime, 0.0f);

        // build new rotation based on new_direction
        koiTransform.rotation = Quaternion.LookRotation(newDir);
    }

    void ApproachTarget(Vector3 targetPos)
    {
        // if distance between us and the object is small enough, stop moving towards it
        if (Vector3.Distance(koiTransform.position, targetPos) < stopDistance)
        {
            return;
        }

        // adjust our transform so we get closer every frame if applicable
        rb.velocity = koiTransform.forward * Time.deltaTime * followSpeed;
    }
}
swift falcon
gray mural
tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

somber nacelle
lean sigil
#

sorry

swift falcon
swift falcon
#

and how to find it

dusk apex
#

Clear the logs

gray mural
swift falcon
#

thnx πŸ™‚

gray mural
lean sigil
#

Yeah.

#

So I really don't know what's going on there at all.

bold pawn
#

Anyone have ideas on how they are doing this camera move (starts at 0:33 ish) from FPS to focused on keypad? https://youtu.be/LFkBCmwZtYk?si=46e_DpBMy2yOW-6t&t=33

Deus Ex Mankind Divided - A Heated Combination Trophy / Achievement Guide - Enter a classic numerical code in the game's first keypad. [Bronze / 10G]

Mission 1: Black Market Buy
At the very first keypad you find (which is story related and unmissable) you must enter the code "0451". This will open the door and unlock the trophy / achievement.

...

β–Ά Play video
rain crater
#

Am I crazy already, or is Unity broken?

for (int i = 0; i < carMeshRenderers.Length; i++)
        {
            carMeshRenderers[i].materials[carMeshRendererMaterialSlot[i]] = carMaterial;
            Debug.Log($"carMat: {carMaterial.name}      setMat: {carMeshRenderers[i].materials[carMeshRendererMaterialSlot[i]].name}");
        }

I have this in script. As you can see, it should set the specific material for the i-th mesh renderer to carMaterial. Simple stuff.
Although it does not! To exclude the possibility of something else messing it up, I've added the Debug.Log. And what does it show? That carMat and setMat are different materials!
I really doubt there can be anything else changing the material, especially since no other script has access to these mesh renderers, nor the materials used here. What can be wrong here?

leaden ice
#

.materials returns a copy of the materials array

#

modifying that copy will not do anything to the renderer

#

this is noted in the documentation

#

you would need to do this:

Material[] mats = carMeshRenderers[i].materials;
mats[carMeshRendererMaterialSlot[i]] = carMaterial;
carMeshRenderers[i].materials = mats;```
rain crater
#

it worked just fine before I updated my script. I simply had .material before, and it worked. Unless those two are actually different

leaden ice
#

they are different

heady iris
leaden ice
#

yes

heady iris
#

I was under the impression it duplicated the materials if this was the first time you accessed it, so that the renderer now has unique materials

leaden ice
#

you only used the getter, which returns a copy

leaden ice
#

but the array it returns is a copy regardless

heady iris
#

Oh, I misunderstood.

#

setting into the returned array does nothing, because you're setting into the copy

#

I was mixing that up with modifying the array elements, which does work exactly as expected

rain crater
#

Oh, it does work. But it's kinda weird that .material returns the material, and .materials[i] returns a copy.
Anyways, thanks a lot for the help!

rain crater
leaden ice
#

There are many things in the Unity API that return arrays and most of them return copies. Mostly this is done because the real collections are in native code, not C#

#

so it wouldn't be possible to directly return these collections

heady iris
#

in fact, most things that look like fields are actually properties

#

hence why transform.position.x += 1; doesn't work

rain crater
rain crater
heady iris
#
renderer.materials[0].color = Color.red;
dusk apex
#

General pattern for properties of value type or collections:cs var things = ... //things.x = ... //things[...] = ... ... = things

heady iris
#

This is completely fine. It makes a new array that has all of the materials in it. You access a material and set one of its members.

#

It's when you try to assign into that array that it doesn't work

#

because you just change what the array is holding

rain crater
#

yeah, that's what I was thinking. Modifying materials inside the array works, because it's one material in 2 arrays (copied and original).
But if I assign new material to copied array, it doesn't get set to the original one because those are different arrays

spark yew
fringe ridge
short wing
#

@fringe ridge are you moving them ?

fringe ridge
#

yeah

#

but its not consistent with the movement

#

like i move the last panel to the front, but it doesnt happen then, it just happens randomly

short wing
#

did you remove the movement and tested ?

#

try to isolate

fringe ridge
#

oh no, wait, it does corelate with something

#

when the last panel is moved to the front it flickers

#

its not because of speed or anything, because of the transition

#

the way this works is i move the background to the front when it has passed the defined length

short wing
#

try to isolate the part you believe the bug is, and let us see the code

jaunty needle
#

How do I stop a new animation starting until the current one finished using code on animator?

fringe ridge
#

causing some kind of weird glitch where for a fraction of a second it got stuck inbetween

short wing
#

Kinda of hard to debug without seeing what are you really doing.
Are you swaping sprites between parent and child 1 (the second child) ?
Is this supposed to happen only once after a certain limit ?
Is this limit being resetted after you swap ? Or its constantly checking and swaping every late update.

rigid island
#

Why does result of a task cause Inifite Loop / Freezing in Unity?

leaden ice
#

presumably because it needs to block to wait for whatever the async task is

#

you should NEVER block the main thread in an interactive application

#

otherwise the user experiences "freezing"

rigid island
#
 public async Task<string> LoadSomeData()
    {
        Dictionary<string, string> savedData = await CloudSaveService.Instance.Data.LoadAsync(new HashSet<string> { "PlayerSave" });
        Debug.Log("Done: " + savedData["PlayerSave"]);

        return savedData["PlayerSave"];
    }```
//Another script

```cs
    [ContextMenu("Load")]
    public void LoadData()
    {
        var jsonData = cloudService.LoadSomeData();
        var data = JsonUtility.FromJson<PlayerSaveData>(jsonData.Result);

    }```
#

LoadData for some reason is freezing

leaden ice
#

so that's what it's doing

#

unfortunately for you the main thread is the thing that renders the game every frame

#

if it's blocked, it can't do anything else

swift falcon
#

I'm trying to make a snap function for props in my builder to snap to the side of another object, I do that by using the position of the object we hit + 50% of it's width in the right direction

buildPosition = 
hit.transform.position + hit.transform.right * 
(buildOrders.item.width * (hit.transform.localScale.x > 0 ? 0.5f : -0.5f));

buildOrders.desiredRotation = hit.transform.eulerAngles;```
This works perfectly for objects that are 0, 90, 180, 270 degrees but other it seems to be incorrect? I tested a 45 degree object and I needed to offset it by 0.0000182 to remove it detecting a collider overlap.

Any suggestions on how I can do this better? I assume there is some floating point accuracy issue here?
rigid island
leaden ice
#

the await is implied here

#

and it's the problem

rigid island
#

Ahh okk is this why they made an Awaitable class I suppose.

leaden ice
rigid island
#
 public async void LoadData()
    {
        var jsonData = await cloudService.LoadSomeData();
        var data = JsonUtility.FromJson<PlayerSaveData>(jsonData);


    }``` this worked
#

unity UGS really forces you to use async with things like async void. cringe

swift falcon
rigid island
#

I havent done anything with LoadedData yet cause the .result from Task was fucking me up lol
Im just making a video on Cloud Saving UGS , not really using this in a production product

#

thought it was neat unity finally added Email/Pass login to authentication package , it actually made it useful now

swift falcon
swift falcon
#

no i mean ur CloudSaveService singleton, if thats what it is, where does it take data from

#

like do you have database for that or what?

swift falcon
swift falcon
#

yeah i figured but wasn't sure, thanks

swift falcon
#

is it connected to steam or database or what?

rigid island
#

Unity Authentication service is built in the UGS, you can choose whatever platform you want.

#

it has Anonymous login by default, they finally added Email/Password login though , it was something missing I wanted first before trying this

#

everything is stored on UGS Dashboard

swift falcon
rigid island
#

yeah you can use SteamID

swift falcon
#

yeah nice , cool

swift falcon
#

im curious cuz im soon off to create the login system for my game aswell so just figuring out all the options

rigid island
#

OpenID was the only Option for custom logins but its difficult, I'm glad they built their own email/pass . I was missing that from many services like Lootlocker or MongoDB

#

Oauth comes with too many hells to deal with, so yeah this is easy solution without worrying about security since they take care of it

swift falcon
rigid island
#

cause its a 100$ for steamID

#

lol

wind palm
rigid island
#

sorry my bad wording πŸ˜›

#

not native

swift falcon
wind palm
#

You can use the Steam default game to develop too, so you don't need to front the $100

rigid island
wind palm
#

Not sure how that works with Unity's system though, I'm using someone else's

rigid island
#

gotta look into this

wind palm
#

Just google Steam Spacewar (app id 480)

solemn glade
#

I'm using unity's input system and would like to return the players GameObject when they join, I have been googling for about half an hour and cannot find anything lol

rigid island
runic cave
#

Is there a way detect when an object is deleted from the scene in edit mode and find out what that object was?

swift falcon
#
{
    GameObject[] gb = GameObject.FindGameObjectsWithTag(tagName);
    GameObject gb2 = GameObject.FindGameObjectWithTag(tagName + "Input");
        foreach (GameObject g in gb)
        {
            g.SetActive(isEnable);
        if (isActive & g.GetComponent<Button>()!=null)
        {
            g.SetActive(false);
        }
        }
    gb2.SetActive(isActive);
}```
NullReferenceException: Object reference not set to an instance of an object
Play.EnableDisable (System.String tagName, System.Boolean isEnable, System.Boolean isActive) (at Assets/Scripts/Play.cs:112)
Play.BuyMachine (System.Int32 mid) (at Assets/Scripts/Play.cs:273)
Play.Mac1Button () (at Assets/Scripts/Play.cs:234)
lean sail
rigid island
lean sail
#

so idk specifically about steamworks api

rigid island
rigid island
#

use site !code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

swift falcon
worthy fable
#

Even though it's a GameObject, I can't reference the Player Goal to a prefab that is not in the scene. When I put the prefab into the hierarchy, I can reference it, but in that case, I can't override the prefab, and the "Apply" option remains greyed out.

rigid island
worthy fable
#

I don't get it

#

Should I make Player Goal a prefab?

rigid island
#

you cant reference scene objects from prefab

worthy fable
#

So should I use .find in Start()?

bold pawn
#

I was mistaken

rigid island
#

avoid Find methods

worthy fable
#

No its already in the scene

#

I'm not spawning the goals

rigid island
#

EnemyX

#

thats the prefab

#

Goals are part of the scene already yes?

worthy fable
#

Yes

rigid island
#

right so when you spawn the EnemyX prefab, pass that on Instantiation

worthy fable
#

uhh

#

how EnemyX is a prefab

#

isnt it just a script

rigid island
#

idk what u called the prefab

#

screenshot is cutoff

worthy fable
#

mb

rigid island
#

Enemy. lol no big deal.. same concept applies

#

what is spawning Enemy

#

make that thing hold reference to the Goal in the scene

#

then pass it when you instantiate , look at the example link I've sent

worthy fable
#

Okay let me process these

#

I'll let you know

#

Thank you already

#

U gained a sub HYPERSL

rigid island
worthy fable
#

I'm not sure if i'm being dumb but that didn't work

#

What i'm trying to do is, I want enemy balls to aim to my goal post and go for that direction.

#

@rigid island

public class SpawnManagerX : MonoBehaviour
{
    public GameObject enemyPrefab;
    public GameObject powerupPrefab;
    **public GameObject playerGoal; **
    public GameObject player;
    private float spawnRangeX = 10;
    private float spawnZMin = 15; // set min spawn Z
    private float spawnZMax = 25; // set max spawn Z
    public int enemyCount;
    public int waveCount = 1;
#

and there's this.

#
public class EnemyX : MonoBehaviour
{
    public float speed;
    private Rigidbody enemyRb;
    private SpawnManagerX smx;

    // Start is called before the first frame update
    void Start()
    {
        enemyRb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        // Set enemy direction towards player goal and move there
        Vector3 lookDirection = (transform.position - smx.playerGoal.transform.position).normalized;
        enemyRb.AddForce(lookDirection * speed * Time.deltaTime);

    }```
leaden ice
worthy fable
#

Im just doing what unity's junior programmer course said πŸ˜”

leaden ice
#

typical of unity to do stupid things in their tutorials lol

worthy fable
#

I mean I watched sht ton of tutorials about unity

#

and this is the best one so far

leaden ice
#

unfortunately it seems to be espousing some things that are not best practices

worthy fable
#

they even give you a bugged game and get it fixed

bold pawn
#

Anything physics related should be called in FixedUpdate()

worthy fable
#

Wish that was the problem

#

Ty though

#

It's solved now, thank you everyone.

heady iris
#

it will be correctly summed up and applied in the next physics update

#

it will be slightly less consistent then doing it in FixedUpdate

#

throwing deltaTime in there is just goofy though

leaden ice
#

at 300 fps you will get twice as much force added per physics update as you would at 150 fps

heady iris
#

the docs say that AddForce will change velocity by force * DT / mass

leaden ice
heady iris
#

I'm trying to figure out which way that asumption goes

leaden ice
#

and always uses that

heady iris
#

i'm gonna test this. i'm curious now.

#

you're right!

#

πŸ’₯

#

that's very annoying

#

well, now it's nice and clear-cut

#

it's mega-wrong to apply continuous forces in Update

#

rather than just sort-of-wrong

leaden ice
#

it does become sort-of-wrong if you multiply deltaTime in

heady iris
#

then it's just as wrong as putting it in FixedUpdate, I guess

leaden ice
#

but still a lot less right than doing it in FixedUpdate

heady iris
#

less wrong (tm)

#

i love how fast unity compiles in this mostly-blank project

runic cave
#

Does unity fire any events or actions when an object is deleted while not in play mode?

leaden solstice
runic cave
#

ah, thank you!

mystic ferry
#

okay so I'm really just asking this for my own general knowledge, but certain interfaces are clearly event based. An example is ISerializationCallbackReceiver which has a member OnBeforeSerialize(). When you implement the interface it's clear that under the hood the engine adds all of the classes that implement that interface into a list and invokes the event handler at runtime, but I'm not quite sure syntactically how you'd add them to the delegate

#
public class SerializationCallbackHost
{
  private List<ISerializationCallbackReceiver> _receiverObjects = new();
  public delegate void CallbackReceiver();
  CallbackReceiver _receiever = new CallbackReceiver();
  foreach(ISerializationCallbackReceiver _rec in _receiverObjects)
  {
    _receiever += _rec.OnBeforeSerialize;
  }
}

public interface ISerializationCallbackReceiver
{
  public void OnBeforeSerialize();
}

apologies in advance for the horrific code, this is 99% guesswork and I know a lot of this is probably very wrong

#

that's my best guess at the idea, where am I wrong?

leaden solstice
#

You don’t call the method when you turn it into delegate

mystic ferry
#

oops, just a typo

#

how much of that do you suppose is accurate if any? also, how would the engine collect the implementers of the interface at runtime?

leaden solstice
#

What is the issue you are encountering?

#

Just performance concern?

mystic ferry
#

no issue, just conceptually trying to understand

#

I know collecting interface implementers is simple enough on our end because the hierarchy is a graph, but I don't think that's globally true

#

well nevermind that might be stupid. It would only make sense that they're all part of the graph

leaden solstice
#

I mean I doubt Unity would need delegate there

mystic ferry
#

wym?

#

you mean like replace it with an event or something instead?

leaden ice
mystic ferry
#

thanks, that explains a lot actually

proper pulsar
#

Good evening,
I'm current writing a voxel game in unity and have been working to get UV's properly affixed to the generated voxels.

After hours of work, I've finally gotten it to a point where it looks decent, but the texture stretching is undesired. I believe it's caused by a misaligned vertex, but I have yet to find where in my code that causes the misalignment.

https://pastebin.com/RkcC23Su

Do you have any ideas?

My apologies; I've found the solution. The answer was that the order I had assigned the UV's needed to be adjusted.

hoary monolith
#

is there a way to change the size of a game object in runtime? if possible, not by scaling but something like setting the radius to be 50

shell scarab
#

Like its mesh or collider or…?

hoary monolith
#

uhh it's basically a prefab with a circle collider2d

red flax
quaint escarp
#

so, I have a localPosition and a localRotation stored; I want to position my gameObject as if it was the child of another object without SetParent; like if I did the SetParent(transform,false)

I tried:

transform.rotation=parent.rotation*localRotation;
transform.position=parent.TransformPoint(localPosition);

but the values result in a small offset from the actual position if I copy-paste the transform component

mental oriole
#

My visual studio (2022) does not show errors in the Error list and I dont know why

red flax
red flax
shadow fern
#

hi, i work on my this project. when I jump, the animation works as I want, but when I want to jump again after hitting the ground, sometimes it gets stuck in the jump animation trigger. at the same time, I want the animation to work when falling from a high place. how can I achieve this?

`private bool _isJumpPressed = false;
private bool _isJumping = false;
[Header("Jump Settings")]
[SerializeField] private float speedY;
[SerializeField] private float _gravity = -9.81f;
[SerializeField] private float _jumpForce = 15;

void PlayerMove()
{
if (_isJumpPressed && !_isJumping)
{
_isJumping = true;
_playerAnimator.SetTrigger("Jump");
speedY += _jumpForce;
}

    if (!_characterController.isGrounded)
    {
        speedY += _gravity * Time.deltaTime;
    }
    else if (speedY < 0 && !_characterController.isGrounded)
    {
        speedY = 0;
    }
    
    _playerAnimator.SetFloat("SpeedY", speedY / _jumpForce);
    
    if (_isJumping && speedY < 0)
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.down, out hit, .1f, LayerMask.GetMask("Default")))
        {
            _isJumping = false;
            _playerAnimator.SetTrigger("Land");
        }
    }
    
    Vector3 movement = new Vector3(_currentMovement.x, 0, _currentMovement.z).normalized;
    Vector3 rotatedMovement = Quaternion.Euler(0,_camera.transform.rotation.eulerAngles.y, 0) * movement;
    Vector3 verticalMovement = Vector3.up * speedY;
}`
red flax
#

you need to have this component on the object you want to have updated but aside from that it shouldn't be too bad

quaint escarp
#

but Parent Constraints should be a great alternative for what I was doing; I was creating a complicated Serialized array of values to be applied, so I'll replace it with your suggestion.

red flax
#

hmm for just generally setting position + rotation, what I found to work is

objectToUpdate.transform.position = originalTransform.transform.position;
objectToUpdate.transform.eulerAngles = originalTransform.transform.eulerAngles;

Something like that should work, was looking through my code but I use a slightly different setup since I generally have an offset, but something like this should work fine

#

Yeah that parent constraint stuff is awesome because another alternative would be during an update/late update method you would typically update the position/rotation but this seems to just take everything needed and update it accordingly I use it for a barrier type setup for a player and it works great!

#

a little on the learning to know how to set it up but once you get over that hurdle it's great

quaint escarp
#

thank you!

red flax
#

So I guess I'll add this:

You need to add a constraint source like so

GetComponent<ParentConstraint>().AddSource(new ConstraintSource()
                {
                    sourceTransform = playerDataReference.m_PlayerProtectionParent.transform,
                    weight = 1
                });

and I have this on the actual component, the freeze position bit kinda confused me at first but the freeze position basically means it will take whatever position is given from the source (so it's essentially freezing it's own position) so you would do that + rotation if you want it to follow the position/rotation of an object (in this case the source)

#

oh right and last bit would be to remove the source, I use an object pool so that's where I typically clean up my objects

if (objectToDespawn.TryGetComponent(out ParentConstraint parentConstraintReference))
                {
                    parentConstraintReference.RemoveSource(0);
                }

So if that isn't the case for you, I would say something like OnDisable/OnDestroy is where you'd put the clean portion

quaint escarp
#

thanks for the great explanation and examples! I'm already reimplementing the "carrying inventory items" system using your approach :)

red flax
#

Hey no problem! it's a great alternative so I'm happy to share the knowledge I have on it πŸ˜„

red flax
#

wouldn't that be for for a build? if you want to see errors, it'd be better to look at what is shown in the unity console

#

hmm actually that might not be the case, I can see errors in visual studio, maybe restart visual studio? I know it can be iffy at times

gray mural
tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

quaint escarp
# mental oriole does somone know?

sometimes I fix this problem by going to Edit>Preferences...>External Tools and setting the External Script Editor to Visual Studio and then pressing Regenerate project files

#

but I'm not sure if that's the case with your project

gray mural
gray mural
#

the second case can appear when changing scripts name in unity, but it is not changed in vs yet

#

or vise versa ?

mental oriole
#

wrong tag lol

mental oriole
winged hull
#

For a online rpg, its obvious that player data such as level, skills, currency, achievements etc are stored in the database. But what is the best practice for storing static data such as, weapon and equipment base stats, monster stats, monster drop tables, quest dialogues, etc? Do I also stored them in the database, as JSON files, or like just hard coded in the scripts?

red flax
#

For the game I worked on, we used an sql database, each table stored various amounts of data basically like you suggested. It definitely worked but you have to create essentially an API that connects the sql database to your game, it's a bit of work but it's definitely doable.

winged hull
#

So just store both dynamic and static data in the database

hidden parrot
red flax
#

would the static data be the exp table(as an example) , and dynamic anything specific to the player that updates?

winged hull
#

dynamic as in data that changes over time such as player exp
static as in ones that doesn't change like weapon base attack

hidden parrot
red flax
#

static wouldn't have to be in the sql table, you can just essentially bake that into the client itself, but the dynamic would be what you use the sql table for (at least that's how we did it, you can do both in sql but still requires a bit of effort)

#

sorta depends on the circumstances, though, because having it stored in an sql database off the machine means that it's harder to alter locally, and doesn't exactly work for an online rpg

hidden parrot
#

I'm not a network guy but I imagine by making requests to a server you're opening yourself up to attacks like impersonating the server

#

Then again every system has vulnerabilities so yeah, pick whatever

red flax
#

the way we set it up, was in order to get or send info, you had to essentially get a token from the server itself, the token expires every I think 5-10 mins so it refreshes

#

there were probably ways to get around it but nothing is perfect

winged hull
#

yeah i mean both way works i just wanna know whats like the industry standard before i start implementing it

red flax
#

hmm I didn't setup the sql portion just the bits that connected to the sql server to get and send info, though tbh I wouldn't know how to exactly describe what I did lol it's kinda a lot to put into words

#

I think a general idea is that for the setup at least on the client end, since there is a lot of deserializing/serializing is to generalize that portion, and also setup data class types that are similar in design to what the data tables are like. Having those two things helped quite a bit when setting up everything needed for sending and reading data.

winged hull
#

yeah im not worried about the setup, just wanted to know where is the best place to put data that's never going to change.

red flax
#

Oh for static data I just have it stored in the client, since it never really changes we never had to really change it aside from fixing whatever bugs we found. We essentially had local databases, but more in a sense of a dictionaries of scriptable objects for particular info on things like equipment/item data

#

It's actually what I do for the game I'm working on now, we have close to 200 attacks for the player, that are stored in a database (but again it's just a dictionary really), I guess the better alternative is to have something be able to parse in an excel/google spreadsheet to update all the different values which I might end up doing in the future if it's necessary (I've read this is a good idea, but I have yet to try it out) so that is something you could look into if you want.

winged hull
#

hmm yeah makes sense. only time ill ever change the data is for like balancing.

red flax
#

Scriptable objects are great, we use them to store the animation clip for the attacks, the prefabs that we want to spawn in, along with any transform offsets, and also things like the damage values and such, which if they were split up (the damage portion that is) we could probably just have it use the spread parsing stuff. The great thing though is we can do all the changes to the scriptable object live and we can see the results straight away, which definitely help for things like balancing, and also just prefab positioning

valid cosmos
#

can someone help me? I have a problem that I'm unable to make my player move when I'm trying to call a public class from other script which is the player controller. What I did is I called the play controller into another script and use it for if else game state. I used HandleUpdate on public void to make the function work

#

I used public enum GameEstate to make sure that the character won't be able to move when the player interacts with NPC

red flax
#

are you able to show your code, so we can see what maybe wrong with it?

leaden ice
vale bridge
#

Is it wise(advised) to store data that will be used across scenes by some gameManager in a scriptableObject

gray mural
#

Is it impossible to do within 1 condition?

if ((ItemController item = hitTransform.GetComponent<ItemController>()) != null)
red flax
#

if(hitTransform.TryGetComponent(out ItemController itemController))

#

TryGetComponent returns a bool

gray mural
red flax
#

Yep no prob!

stable osprey
gray mural
stable osprey
#

you're welcome πŸ™‚

#

it'll come handy in other comparisons -- but for Components TryGetComponent is recommended

gray mural
#

actually I've just realised that I don't need'em, cuz I just have to compare getcomponents

#

but now I know how to get them

stable osprey
#

using GetComponent isn't good practice in general -- except when in collisions/physics

gray mural
#

it's a pity that normal transform is ItemController item doesn't work

red flax
#

is using is better than say .Equals?

gray mural
#

I actually don't have another option

gray mural
#

you can override Equals

#

so its kinda different for every class and struct

stable osprey
gray mural
#

is is another

stable osprey
#

architecturally speaking

lavish ridge
#

Is there a way I can sync a game object's movement to a bone on my model during an animation?

gray mural
#
if (component is Behaviour behaviour and not Collider2D)
{
    behaviour.enabled = value;
}
red flax
#

huh okay, I've never actually used is before

gray mural
red flax
stable osprey
#

almost always, but yeah

gray mural
stable osprey
#

hmm in proper OOP you'd have InventoryController that references each of those

gray mural
lavish ridge
#

Wouldn't that move my character about the screen?

red flax
#

I have something similar to that, my inventory controller would hold references to each inventory slot, and what is in each inventory slot

red flax
#

because that I guess would be different

lavish ridge
#

I'm trying to have my character do a pickup animation and tween an items size from a bone moving with the character

#

As if the animation and bones were gameobjects and the item is just a child of one of the game objects (a bone)

#

If that makes any sense

red flax
#

hmm, I feel like I could probably figure out what you mean but it might be better if I saw a vid of it or something lol

#

is there some sort of example from another game you could show?

stable osprey
lavish ridge
red flax
#

Hmm nothing comes to mind, I could try think of a solution in the morning though, might be able to think up a way to do it (would still be better with an example or vid though)

deft kindle
#

Hi i am wanting to make my car game multiplayer and i want to use PUN 2 but idk how

leaden ice
worn badger
#

Im trying to upload a build to Meta Developer portal, and its telling me that since june 30th, api must now be minimum of 32, but I dont know how to get this on the editor? in the settings i can try select it but it doesnt have a name like the others, just "API Level 32".... ??? I have never had this problem when working with it before.

Am i missing an update to the Android SDK? I searched the editor modules and it only says that theyre installed. so is there anyway to force an update?

leaden ice
#

but I would recommend against PUN2

#

it's quite old / outdated at this point

#

and missing capabilities

deft kindle
red flax
#

Photon Fusion is where it's at, so much better imo

leaden ice
#

Photon Fusion or Unity's NCFGO is newer/better

worn badger
red flax
#

I have the exact same budget lol

deft kindle
worn badger
#

you dont need to spend anything :p

red flax
#
worn badger
red flax
#

money is only needed if you want to make it into a bigger multiplayer game anyways, can just use the basic setup if you just need to make something like a game for studies or even for a game jam

fervent furnace
#

i remember api level of android is somewhere in project settings->player->other setting with target platform is android
jsut search for api in project settings

deft kindle
lost walrus
#

Hey so, I am trying to make a random contient generate, I am kinda new to procedural generation

Basically what I have now is perlin noise combined with fallof map.

What should I do if I wanted to have more organic shape?
(ping if you respond) (my code knowledge is medium) (my unity knowledge is somewhere between beginner and medium)

hexed pecan
#

Like throwing in a layer that is ~4x the current noise scale would help already

#

Play around with min/max, multiplication and other ways to blend the noises

lost walrus
#

thanks for the tip

real kestrel
#

Hi, I am working on a rhythm game and I want to procedurally find the beat ( Drum or Bass) according to the melody of the music, but I couldn't do that. I can now find bpm, beat interval also the peak of the music using spectrum data. can someone help me ?

devout solstice
#

is there a method that doesn’t need to be called on that will still you know do stuff, i want to have a separate method with all my if statements that run if a key is pressed so i don’t have update all junked up

leaden ice
#

call the method in Update

devout solstice
#

ig that would work

somber nacelle
#

Or use the input system and events since that's what it sounds like you want

dense edge
#

hello, im trying to make a turnbased combat system but i got int osome questions. Im making a turn manager that setup all the turns and initatives, but i want to make events happens if the characters have different skills or effects

#

for example

#

i have a character that always at the start of the its turn he receives 50% of his hp as a shield

#

other character receives 100% crit cahcne if its hp is full

#

this 2 triggers happens on the turn manager "turn start"

#

there is a way to make a method "subscribe" to this evetns?

heady iris
#

For that kind of things, you could use C# events.

#

Each skill would subscribe to the relevant events when turned on (and unsubscribe when turned off)

#

alternatively, you could add methods to your skills like "OnTurnStart"

then just loop over all of your skills and run the methods when appropriate

dense edge
#

hmm bit im going to need to grab all the skills and check if hte onturnstart exist in all of them

#
  • the other effects
#

i will check the event thing

#

thx a a lot

quick elbow
#

Has anyone seen this error:
β€œSaving has no effect. Your class β€˜UnityEditor.XR.Simulation.XREnvironmentViewManager’ is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.
Only call Save() and use this attribute if you want your state to survive between sessions of Unity.
UnityEditor.XR.Simulation.XREnvironmentViewManager:OnDisable () (at ./Library/PackageCache/com.unity.xr.arfoundation@5.0.7/Editor/Simulation/XREnvironmentViewManager.cs:169)"

Any suggestions on how to resolve, or possibly how to suppress it?

#

It's coming from the ARFoundation package 5.0.7. I tried 5.0.5 as well but same thing. It's just an editor script that throws this at runtime

whole portal
#

Hi everyone. I'm working on a marching cubes voxel terrain in Unity and I'm running into issues trying to "dig" into it. My setup includes a MeshGenerator class and a DensityGenerator class that uses noise for the terrain. I'm trying to modify the density values to dig holes into the terrain but it's not working as expected.

  • I've tried to use a Dig method to change the density at a specific point and regenerate the mesh.
  • I'm using raycasting and I've also added debug spheres just to check if the raycast hits the terrain, and it does hit but no digging happens. The digging is supposed to happen where the raycasting hits.

I've added a few debug logs which you can see them in the screenshot. I have no idea where the issue lies. I'm also using a few compute shaders but haven't modified anything in there, the digging related code is in my scripts.

gray mural
#

Are those the same?

Input.GetKeyDown(KeyCode.LeftAlt | KeyCode.RightAlt)

Input.GetKeyDown(KeyCode.LeftAlt) || Input.GetKeyDown(KeyCode.RightAlt)
wind kestrel
#

hey, I'm new to the discord. Is there anywhere i can ask for help with C# scripts?

wind kestrel
#

ok, its just i cant find any guides for a swipe movement system

gray mural
wind kestrel
#

its a golf game, but i want the touch input to be when touching the golf ball

#

yes, ive googled it, but only found guides for 3d fps

simple egret
gray mural
simple egret
#

Nope, that's as compact as you can get

gray mural
heady iris
#

this is not one of those cases

#

I dunno if there's an easy way to check if that's true.

simple egret
#

(KeyCode.A | KeyCode.B).ToString() - if it returns "A, B" then it's flags. If it returns a number or a completely unrelated key, it's not flags

heady iris
#

oh yeah, that'll indicate it

simple egret
#

Haha, doing the "short" but invalid way will poll inputs for the LeftWindows key, which is deprecated

heady iris
#

secret achievement unlocked

gray mural
#

I can also make a custom method for this stuff though

#
public static bool GetKey(KeyCode key1, KeyCode key2) =>
    Input.GetKey(key1) || Input.GetKey(key2);
heady iris
#

indeed. i was about to say "you could use a params argument", but that makes garbage every time you call the method

somber nacelle
#
public static bool GetKeys(params KeyCode[] keys)
{
  foreach(var key in keys)
    if(!Input.GetKey(key))
      return false;

  return true;
}

supports unlimited number of keys, but yeah creates garbage like fen said

heady iris
#

I guess I'd just implement a few of them

#

actually, how does overloading work if there's a params version of the method?

#

okay, it takes the non-params one

simple egret
#

I believe it attempts to resolve the exact signature first

#

If all else fails, params

gray mural
#

performance?

heady iris
#

it makes an array

somber nacelle
heady iris
#

i discovered this when using LayerMask.GetMask in a very hot part of my code

simple egret
#

(Did you know you can pass an array directly to the params argument and it won't complain?)

heady iris
#

it's all syntactic sugar, isn't it

gray mural
somber nacelle
#

a lot of garbage collection can cause hangs/frame rate issues

gray mural
#

I see

heady iris
#

yeah, you get hitches as the garbage collector runs

gray mural
#

how should I name these different methods?

public static bool GetKey(KeyCode key1, KeyCode key2) =>
    Input.GetKey(key1) || Input.GetKey(key2);
public static bool GetKey(KeyCode key1, KeyCode key2) =>
    Input.GetKey(key1) && Input.GetKey(key2);
simple egret
#

AnyKey, AllKeys

#

Probably

gray mural
simple egret
#

Yup to be consistent with the names Input already provides

gray mural
peak trellis
#

Apologies if this is the wrong chat but I tried putting my project GitHub and when I cloned it back to make sure it works I got a lot of errors. I used gitignore but added an extra line to ignore zip files. Is there something I'm missing? Thanks in advance

lean sail
peak trellis
heady iris
#

hm, one of those errors where a package can't see a name.

#

so the Library folder is not included in the repository, correct?

peak trellis
#

Yeah no library

dense edge
#

for soem reason i cannot acess evetns, anyone know why?

somber nacelle
#

what do you mean you cannot access events?

dense edge
somber nacelle
#

those events are static, you access them directly through the class rather than through an instance of the class

dense edge
#

im trying to make a messa appear on hte on tuurn start on oteh exterior gameobject

somber nacelle
#

so it's just turnbasedUnit.onTurnStart += <whatever>

heady iris
#

(do you actually want static events?)

dense edge
#

yeah but it dont appear as a event on my fiel for soem reason

somber nacelle
#

also you should consider naming your classes with PascalCase rather than camelCase to align with standard naming conventions for c#

dense edge
#

im not sure

#

i got a guide

#

and made it static

somber nacelle
heady iris
#

perhaps the guide is talking about a situation where it makes sense to be static

simple egret
#

See the dots here? That means your class isn't named correctly, it should be TurnBasedUnit so you know it's a class at a glance.
Same for the two events there, they need to be renamed

dense edge
#

i see

#

i will solve that

#

and yeah the static stuff was teh rpoblem

#

yap worked fine

peak trellis
tribal gust
#

Is there a way I can record the best performance of my agent during the training process? (Unity ml.agents)

dense estuary
#

Im making a script that generates different objects with different values. so I made a struct that holds the values for the different objects. but I dont know how to make a for loop that loops and increments for each index of the struct. I thought maybe i could do this for (int resource = 0; resource < Resources.length; resource++) but that doesnt work.

#

here is the struct

leaden ice
dense estuary
leaden ice
#

this is an element in an array containing this struct

#

an array or a list

dense estuary
#

oh, sorry.

leaden ice
#

you have either:

Resources[] myResources;
// or
List<Resources> myResources;``` right?
#

that's very important information

dense estuary
#

yeah

leaden ice
#

ok perfect

#

so if you want to iterate over those you can do either of these:

for (int i = 0; i < resources.Length; i++) {
  Resources r = resources[i];
  Debug.Log(r.name); // for example
}```
```cs
foreach (Resources r in resources) {
  Debug.Log(r.name); // for example
}```
leaden ice
# dense estuary yeah

so to be clear on the terminology here:
You've defined a struct called "Resources". And you have an array of Resources structs. The array of structs is called "resources".

dense estuary
#

or are they pretty much the same?

leaden ice
#

the for one is useful mostly when your code needs to know the index i for some logic inside the loop

dense estuary
#

Alright, thank you so much.

dense estuary
#

I have a new problem, I cant figure out how to get these trees not to spawn so close to eachother. right now im shooting a raycast from a random point in the sky towards the ground and spawning the prefab at the hit.point. but the trees are spawning to close together. how can i fix this?

lean sail
dense estuary
spring creek
lean sail
# dense estuary How could I apply a minimum spacing?

there'd be a few ways, one would be storing all the locations previously placed then making sure none are too close to any in the list. If you're doing this on like 1000s of objects, you might have noticeable lag.
Another way I could think of would be define some grid where you will check to possibly place a tree at each location in this grid. For each position randomly decide if it should place a tree
Theres probably better ways online but this is the first thing I thought of πŸ€·β€β™‚οΈ

uncut mural
#

I have a question for IAP.
I succeed init product to fakestore and be able to buy it , but all product is in 1 tab(their are many product type: gold packs, diamond packs, misc).
And how can i classify them by type(gold, diamond, misc) so i can separate them into many tabs.

rigid island
uncut mural
uncut mural
#

I could classify by using
product.metadata.localizedTitle.Contains(string type)
But i wonder if there is better way.

#

@rigid island

rigid island
#

hmm yea I'm not sure I haven't really used IAP

uncut mural
#

Ok thank you.

ionic path
#

Hey, just wanted a second opinion on this, for a loot drop system, should I make all the items part of an object pool, or just instantiate them? Large amounts of ammo, money and health are expected to spawn throughout the game, so I figured an object pool would be best, but I'm not 100% sure

also, is there a way for multiple objects to share the same pool?

heady iris
#

there's at least one nice C# implementation I've acquired before

limpid owl
#

Hello everyone, I'm working on a hyper-casual tycoon park game and I'm looking for advice on how to structure my code efficiently to keep it clean and maintainable. Are there any design patterns or best practices that you recommend for organizing code in tycoon park games

#

except from solid principles

#

there is a platform that responsible of spawning attractions based on player balance and can be used to upgrade the attraction also a platform can be used to spawn a worker
platform is the blue square in the picture can have many commands let's say List<ICommand>

dense estuary
# spring creek You might be looking for something more like poisson disk sampling?

I'm following this thing to do that, and I've gotten an error.

PoissonDiscSampling.GeneratePoints (System.Single radius, UnityEngine.Vector2 sampleRegionSize, System.Int32 numSamplesBeforeRejection) (at Assets/Scripts/ProceduralObjectPlacement/PoissonDiscSampling.cs:31)
Test.OnValidate () (at Assets/Scripts/ProceduralObjectPlacement/Test.cs:16)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)```
#

here is line 32

#

here is line 16 of test

heady iris
#

you will need to share the code you are using

#

I think I recognize it, but I'm not sure

dense estuary
autumn gorge
#

Hello I am using Unity Gaming Services Economy and more specifically the inventory system. I am trying to get custom data from the inventory items but it doesn't work it just returns null.(code:
[code=CSharp]var inventoryResult = EconomyService.Instance.Configuration.GetInventoryItems();
foreach (var item in inventoryResult)
{
var data = JsonConvert.DeserializeObject(item.CustomDataDeserializable.GetAsString());
Debug.Log(data);

    }[/code])

I have checked if it was getting the object and it was. I didn't seem to find how to get custom data on the docs and had to rely on just description in the ide and some forums with limited info. Personally I find it baffling that unity doesn't document a important part of their service. Any help would be greatly appreciated.

quartz folio
# dense estuary here is line 32

Surely it should be / (cellSize - 1) if cellSize is the size of the grid.
Either way, seems like an issue with this implementation, or perhaps you've passed in parameters this implementation doesn't like that it doesn't filter against

dense estuary
night harness
#

Think I might be misunderstanding structs,

I have a EventInfo struct which contains a UnityEngine.Object variable,

I have an Array of EventInfo's that I'm looping through where I'm trying to get that UnityEngine.Object

When I debug log this object, it's totally what im expecting it to be, But when I try and add it to my list or direct variable it's just not happening, Like it's somehow only a reference that is dying at the end of my function?

I'm running this code in editor

        foreach (EventInfo eventInfo in interactionSuccessEvent.EventInfos)
        {
            Debug.Log(eventInfo.parameterObject is ItemData);
            if (eventInfo.parameterObject is ItemData)
            {
                ItemData Item = (ItemData)eventInfo.parameterObject;
                Debug.Log(Item);
                trackingItems.Add(Item);
                myItem = Item;
                myLoot = (LootData)eventInfo.parameterObject;
            }
        }

Item is Debug.logging completely fine but trackingItems, myItem and myLoot are just not retaining the value

There's a few moving parts in this so please let me know if I need to provide additional context

#
[System.Serializable]
public struct EventInfo
{
    [SerializeField] public enum Mode { Defined, Void, Object, Int, Float, String, Bool }
    [SerializeField] public Mode parameterType;
    [SerializeField] public string className;
    [SerializeField] public string functionName;
    public UnityEngine.Object parameterObject;

snippet of my struct

heady iris
#

i.e. where are they declared?

#

you should share the entire script

night harness
#

Theres like 4 scripts going on here haha

EnhancedEvent : UnityEvent
contains the EventInfo struct and the stored array of EventInfo's

Interaction : MonoBehaviour
contains a EnhancedEvent and that is running the foreach code (interactionSuccessEvent is the EnhancedEvent)

somber nacelle
#

my first question is why public List<EventInfo> EventInfos => new List<EventInfo>(eventInfo);
you're allocating a new List every time you access that property

night harness
#

I knew someone was gonna hit me with that haha, Was just playing with shit my bad. Can confirm directly referencing the array does not resolve the problem

somber nacelle
#

okay, are you going to share the class that fen asked you to?

night harness
somber nacelle
#

might wanna double check that link

night harness
#

my public variables are declared up top, I use AddEnhancedEventListeners button to run RefreshEventInfo. everything else in the script is unrelated

somber nacelle
#

are you getting any exceptions? or is it just not behaving the way you expect it to?

night harness
#

No exceptions, The publicly exposed variables just aren't being set. Or atleast visably, Ill debug log them directly just incase it's a serialization issue

dense estuary
#

How can i pick a random value in a list?

heady iris
somber nacelle
heady iris
#

Verify by doing Debug.Log("whatever", gameObject)

#

clicking the log entry will take you to gameObject in the hierarchy

sudden peak
#

I was wondering if I could get a hand on static functions, I have a static class called calculator with has a bunch of different math functions in it for a custom data type. These functions have inputs which i used through the function but I always thought these function inputs were in variables but are they pointers?

night harness
night harness
somber nacelle
#

btw what version of unity are you using?

dense estuary
night harness
#

2021.3.6f1

#

That's why I was wondering if somehow I'm only getting a reference and not a real value or something odd

heady iris
somber nacelle
heady iris
#

it gives you the element at that index

#

you now have a Vector2

#

are you asking about modifying the x and y values?

night harness
#

For additional context the data inside EventInfo is being set via a custom property drawer but in theory that shouldn't matter?

somber nacelle
# night harness 2021.3.6f1

okay so this isn't going to fix your issue, but it will clean your code up a bit: you can actually perform your cast in the same line you do the type check.
so instead of every if statement where you do if(eventInfo.parameterObject is ItemData) then immediately perform a cast into a local variable on the next line you can just do if(eventInfo.parametersObject is ItemData item) and it will not only do the type check but then it will also cast to the ItemData type and store the result of that cast in the item local variable

night harness
#

oh ok cool

dense estuary
heady iris
#

or is that for custom editors

somber nacelle
heady iris
#

pick a random number. index the list with the random number.

somber nacelle
#

you know how to access a list at a given index, right?

dense estuary
#

..no

heady iris
heady iris
night harness
dense estuary
#

I'm new to lists and arrays. sorry

somber nacelle
night harness
#
        foreach (EventInfo eventInfo in interactionSuccessEvent.eventInfo)
        {
            if (eventInfo.parameterObject is ItemData newItemData)
            {
                Debug.Log(newItemData);
                trackingItems.Add(newItemData);
                Debug.Log(trackingItems.Count);
                Debug.Log(trackingItems[0]);
                myItem = newItemData;
                myLoot = (LootData)newItemData;
            }
        }

running this gives me this

dense estuary
night harness
#

and then running this right after gives me this

    public void DebugLogValues()
    {
        Debug.Log(trackingItems.Count);
        Debug.Log(myItem);
        Debug.Log(myLoot);
    }
somber nacelle
#

how did you confirm that you are actually looking at the correct object?

#

Debug.Log($"State of {name} ({GetInstanceID()}): list count {trackingItems.Count}, item: {myItem}, loot {myLoot}");
replace both sets of your Debug.Log calls with this line and show what it prints

night harness
#

The data that is being debug logged as well as the buttons I need to press in order to run the functions

will do

somber nacelle
#

there's two whole seconds between those logs. are you certain nothing else is changing those values in that time?

#

also it looks like the myItem and myLoot variables were null at the time you logged the first one. did you make sure to call that after assigning them rather than before?

night harness
#

I run the DebugLogValues() after my other function and still retains the values, should I test the exact frame after?

night harness
#

trackingItems, MyItems, MyLoot etc. were written like within the hour and it's not being touched by any other code

somber nacelle
#

gonna be honest, i have no idea what might be causing your issue at this point. i'm certainly not going to try and read through 400+ lines to figure out what might be overwriting those values. and if you have a custom inspector involved, there's also a decent chance that something you've done in that is causing the issue

night harness
#

That's totally fair homie. It is kinda weird though right?

bold pawn
#

Trying to recreate this mechanic... https://youtu.be/LFkBCmwZtYk?si=46e_DpBMy2yOW-6t&t=33 starts about 0:33, not getting any errors, but also not getting the camera to move either... https://pastebin.com/EVGWK5Ex

Deus Ex Mankind Divided - A Heated Combination Trophy / Achievement Guide - Enter a classic numerical code in the game's first keypad. [Bronze / 10G]

Mission 1: Black Market Buy
At the very first keypad you find (which is story related and unmissable) you must enter the code "0451". This will open the door and unlock the trophy / achievement.

...

β–Ά Play video
dense estuary
#

how can I move this square to follow my gameObject, the square is using values from a grid array. The grid always starts at 0 even when i move my gameobject.

rigid island
#

you don't need any of this, just 2 cameras nd ur done it blends them nicely for you

bold pawn
#

seriously?

rigid island
#

fr

rigid island
bold pawn
#

Damn man

#

i asked on 3 different servers how they thought the best way to make that camera move and no body said a word so I figured I'd just build it my way

#

To be fair, I was half way there ;P

rigid island
#

saves soo much code and headaches

woeful slate
somber nacelle
#

show !code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

woeful slate
bold pawn
somber nacelle
woeful slate
somber nacelle
#

i don't see anything in here that would cause the sprite to change. at least not anything obvious that would. have you checked your animator to make sure that isn't somehow causing it?

#

also this Entity class you have doesn't derive from MonoBehaviour, does it? πŸ€”
because if it does, you shouldn't be using a constructor on it

night harness
#

@somber nacelle It's something to do with where I'm calling the event. When RefreshEventInfo() is called from that context it seems like it's only getting a reference to that data but if i can it on a button or ondrawgizmos etc. it works fine

#

I'm guessing I'm misunderstanding an aspect of serialization

woeful slate
#

need to go back and refactor, but in regards to constructors what should I avoid? just not use them at all?

somber nacelle
#

then you definitely shouldn't be instantiating it with a parameterized constructor. best not to use them at all with MonoBehaviours

woeful slate
#

i don't think I'm instantiating any

#

tbh i don't know why i have the constructor, I originally thought unity called that

#

but i learned unity doesn't do that

somber nacelle
#

by instantiating i am referring to creating an instance, not just using Object.Instantiate

woeful slate
#

oh i'm never calling new Character anywhere

#

if that's what u mean?

somber nacelle
woeful slate
#

oh i think i know my issue

#

you're gonna hate it

#

i have every single animation for the hair in a single animator that i switch between by calling my PlayAnimation function

somber nacelle
#

lol yeah that'll do it then

woeful slate
#

my guess is that when it re-enables it goes back to the default, and since it's already in idle it doesn't switch to the correct hair type

#

need to refactor that at some point

#

i just am not sure how to handle animating different parts of a character that need to swap out for example

#

so like the base and tool animations will be the same so they have their own clean animator

#

but the hair will all swap

dense estuary
#

This is math stuff. This square is always offset to where the gameobject is in the corner of it, how can I make this square always centered on the gameobject? This is what i tried, size = regionSize + new Vector2(transform.position.x, transform.position.z);I cant use negative numbers because it throws me an error. cause you cant have negative numbers for arrays for some reason. So what can I do?

broken nest
#

Does anyone know how I can Determine the selected "Lightmap Encoding" for the current build target. I've dug through all the docs on the PlayerSettings class (which seems like it ought to be the right place). I've also looked through the LightingSettings class which has a lightmapCompression property, but that doesn't seem to correspond to the Player Settings field.

somber nacelle
broken nest
broken nest
somber nacelle
quick elbow
#

How can I secure my game server by only accepting connections for authenticated clients? I need help with the authentication part, not the connection approval part. I'm using Azure Active Directory to manage client identities and my game servers have sensitive customer data, so I only want to allow clients from the Azure AD tenant as able to connect to the game server

#

I was reading about access tokens, but how do I prevent man in the middle attacks? It doesn't seem recommended to send access tokens over the connection to the game server

broken nest
broken nest
cosmic rain
astral oriole
#

I am trying to set it up so that where if a building's x coordinate is right next to another building, it sets active to true, but this isnt working

#

do i need to for loop somehow?

rigid island
#

or is it int?

astral oriole
#

its an int

#

im just trying to compare these 2 building's and set it to true when they are next to each other on the x axis

#

just cant seem to figure out the for loop for it i believe

rigid island
quick elbow
cosmic rain
astral oriole
#

they arent matching, because both building.data.x's are being set to the same value

#

idk how to not have that happen

quick elbow
#

Just wondering how else I could have the server authenticate the pending client connection for either approval or denial

rigid island
cosmic rain
cosmic rain
#

Either way, I'm not knowledgeable enough in that area to provide proper guidance. At the very least, try asking in #archived-networking

cosmic rain
olive shore
#

I was going to ask this is code begginner but some ppl are talking in there and i didnt wanna interupt, Could someone please explain what this might mean please?

#

for context, i built the game and installed onto my phone, and was using android studio to read the logcat, where a intistitial ad is supposed to appear the game freezes and the logcats displays this message

stuck gust
#

registers it as something invisible or that is not yet supposed to be rendered maybe

olive shore
#

it would be reffering to my adsmanager prefab?

also do you mean the layer in the inspector?

somber nacelle
languid crane
#

I'm trying to implement an interface

{
    public void Strike() { }
    public void Destroy() { }
}

I havent implemented its methods in my class but theres no errors, why?

public class Tree : MonoBehaviour, IDestroyable
{
    private void Start()
    {
        
    }
}
broken nest
languid crane
rigid island
somber nacelle
#

you've given the methods on the interface bodies which makes them default interface methods

languid crane
#

They're default methods yeah

#

just realised

broken nest
languid crane
#

had to remove the braces, fixed it πŸ‘

rigid island
broken nest
somber nacelle
#

lol at this point it's barely even new. it's a c# 8 feature which is like 4 years old now

rigid island
somber nacelle
#

ah yeah, fair enough lol

languid crane
#

interfaces cant have private methods can they

rigid island
somber nacelle
languid crane
#

hmm

somber nacelle
#

ah looks like it was added at the same time default interface methods were so should be supported

broken nest
languid crane
#

so i have IStrikable, i'd like to use it on tree and rock for now. I thought id have Strike() and Destroy() in it, but now that i think about it, destroy can just be a private method in the tree (for eg) directly beacuse its just goint to be called from strike anyways

dusk apex
languid crane
#

because it doesnt let me to make it private directly, needs me to give it a body

somber nacelle
#

if it should not be called by outside objects then yeah remove it from the interface. unless your interface includes any properties the method may access, then you can just add the default implementation

languid crane
#

its just going to be called internally, so i guess ill get rid of it

#

Is using interfaces with only one method in them normal?

broken nest
somber nacelle
languid crane
#

Thank you πŸ‘

rigid island
# broken nest I see. I can look this up in my own time (it seems I'm a little behind the curv...

You mean like this ?

public class Player : MonoBehaviour, IBeans, IPotatoes
{
    private void Start()
    {
        SayHello("nav");
    }
    public void SayHello(string name)
    {
        Debug.Log("Which One Am I?" + name);
    }
}

public interface IBeans
{
    public void SayHello(string name) { Debug.Log("HelloFrom Beans" + name); }
}

public interface IPotatoes
{
    public void SayHello(string name) { Debug.Log("Hello from Potatoes" + name); }
}```
rigid island
somber nacelle
#

it will log the Which One Am I one

rigid island
#

yup

somber nacelle
#

with default implementations you can only call those methods on objects specifically of the interface type. so you'd have to cast your class to the interface to use the default methods on the interface.

#

that's my biggest gripe with them tbh, kind of annoying to use the methods within the object that implements the interface

broken nest
rigid island
somber nacelle
#

so you would have to do something like (this as IBeans).SayHello("whatever");

spring creek
#

Wow. I did not either

rigid island
#

wait that does nothing

spring creek
#

Oh lol

somber nacelle
#

you can also explicitly implement the methods on the class using public void IBeans.SayHello(string name) { //different implementation here }

rigid island
#

you can't use public tho right?

somber nacelle
#

ah, right yeah gotta omit the access modifier

rigid island
#

niice. I pesonally may not use this ever but kinda nice to have

leaden solstice
#

You’ll have to use it when you are implementing own IEnumerable<T> for example

rigid island
#

so basically soon lol IEnumerable is kewl

#

think when i was using entity framework i ran into this but was so long ago i forget

green radish
#

how might someone assign a tile via code in this context?

#

I need to be able to call the tiles I have in the project by name in some way

#

without making a public variable for it since that will become increasingly tedious over time

#

for clarity I just want to call the tile type, not a specific tile in a tilemap

livid stag
#

Does anyone have a suggestion for how to build an infinite scrolling menu? Meaning if i scroll past an item it appears on the other end

latent latch
#

Unity has an alright scrolling tool for the UI, which you can normalize a set of elements from 0 to 1, but depending on your design you may just want to craft it yourself.

cinder raft
#

can any tell me the syntax to access the animation track of timeline asset so that when the game starts i can have the animator changed for that animation track

somber maple
#

can someone help me, i have got a problem. Unity has detected errors in my scripts but there are no errors in my console?

somber maple
#

There are none tho

rigid island
#

Unity has detected errors in my scripts

somber maple
#

but there are no errors in the console

rigid island
#

so where do you see this?

somber maple
#

This happened when i was Trying to download unity input system

rigid island
somber maple
#

still no errors, and when i try and play, it says all errors have to be fixed

rigid island
somber maple
#

recently i put my projects into an External Disk is that safe?

#

Thanks so much

#

it works thank you

thin aurora
#

You need to cast the type instance to that interface, and then call the method. You can't call it when the type represents an implementing class

main shuttle
#

Also heres a guide on how to post !code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

autumn gorge
autumn gorge
main shuttle
tulip temple
#

having some issues with editor GUI code,,
https://pastebin.com/UWqCbx8y (< EventTriggerEditor)
there is the editor script, this code is for this script (this code is not the issue but it might help with context) https://pastebin.com/njcifNnR (< EventTrigger)

this code is meant to let me setup in a neat GUI a list of commands that will be executed in order of listing. that all works fine with this script here https://pastebin.com/USuejKMc. (< EventHandler, once again for context)
one of the commands is called sendEvent() and it lets a eventTrigger command chain send a list of commands to another EventHandler other than the one it currently is giving commands to, so letting me affect a player to say,, make them speak then also make the follower speak with one eventTrigger

the issue is the GUI code as said in the start. im trying to make the sendEvent GUI a nested ReorderableList just like the main list is, so i can make command chains for the sendEvent and assign them to nestedCommands in this script https://pastebin.com/snit1gBH (< Command) to well,,, send. but with the current GUI code im getting a strange result and dont know how to fix it everything else works fine other than the sendEvent. the issue is its showing a expandable arrow instead of the select dropdown, i also JUST as writing this saw that in editor it says Teleport when the sendEvent command is the selected command, and i havent checked for that yet so dunno if its a dumb mistake for that one issue. i have not tried to fix the spacing just yet so i know thats broken

#

if you wonder why i dont just make a normal hard coded system, i just want something extremely modular for game dev like an extention to unity

#

and something a friend of mine can understand to make things happen in game

#

clicking the arrow labeled target (idk why it says that) does nothing at all other than rotate the arrow

loud wharf
#

Ngl, i found ReorderableList to be too much of a pain. UnityChanThink
Not a lot of extensive tutorial either, nor is it even documented well. UnityChanPanicWork

tulip temple
#

yea,,, thats why this has been taking all night lol

#

i just want a nice gui πŸ˜”

somber nacelle
#

what version of the editor are you using

loud wharf
#

I just avoided ReorderableArray entirely tbh.

tulip temple
#

2021.3.23f1

somber nacelle
#

okay. the reason i asked was because reorderable lists were a bit broken in very early versions of 2021.3 and caused a display issue similar to the one in your screenshot but it was fixed in like patch 7

loud wharf
#

Possible to make something fairly decent without ReorderableArray.

#

Just using structs and property drawers. UnityChanPanicWork

#

Granted, the only thing u can't edit is the array itself, stuff like the format or the add/remove element.

tulip temple
#

if i cant figure out ReorderableLists in this broken context then ill try other ways

#

just with the nature of the commands being executed in order of how i set them, its not fun when i cant quick drag them around

latent latch
#

I kinda confused. Aren't all lists now reorderable by default or is it how you've got it encapsulated remove the attribute from it?

tulip temple
#

im not sure, im not good with editor code,, i just copied what worked overall inside of case sendEvent with small changes based on what phind said

latent latch
#

Well, you can continue developing out your script, but if you find yourself stuck on this, why not just make a list of structs for this part?

#

and just use the normal list unity has to offer for the gui

tulip temple
#

hmm,, i guess if only the one command has no reorderable stuff that wouldent be bad

#

its the main block that matters and that works fine

tulip temple
#

well ive stayed up 5+ hours too long on this issue, imma pass out.
if anyone has ideas on fixes that would fix the current code with ReorderableLists please @ me!

static prairie
#

Can anyone explain why this is happening when trying to input a quaternion value on a script?

No custom editor scripts are set up to modify this

somber nacelle
#
  1. are you sure that's a quaternion not a vector3? i only see 3 values there not 4
  2. if it is a quaternion, why are you entering in values manually?
  3. adding on to 2, if it's a quaternion why are you entering any numbers above 1? quaternions are normalized and do not contain euler angles like that
static prairie
leaden ice
#

Quaternions show in the inspector as euler angles by default

loud wharf
leaden ice
#

the three angles are not independent of each other

vague tundra
#

How could I set the pivot of a gameobject without a parent object? The goal is to specify an offset from the gameobject's natural center that will be the pivot point for rotations

leaden ice
#

if it's a sprite you can change the pivot in the sprite editor

vague tundra
#

Ooh interesting... it's 2D, but its more of just a game-object that could potentially have any sprite.
Mmm I hadn't thought about how the sprite would effect the pivot tho...
Thanks!:D

#

You always have the answer @leaden ice
What are you working on at the moment?(:

loud wharf
#

Hmmm i love custom editor, u think u did well but nope, it broke. UnityChanPanicWork

heady iris
#

I am working on a debug system. Each debuggable object implements IDebug, and either directly registers itself with the debug system or gets registered by a parent object.

I'm concerned about memory leaks. My naΓ―ve implementation looked something like this;

private Dictionary<IDebug, bool> debugShown = new();

...

if (debugShown[debuggable]) {
  debuggable.ShowDebug();
}

This means that every debuggable object will wind up referenced in that dictionary. Thus, they will never be GC'd.

This sounds like a decent place for "weak references". I see two ways to do this:

Is this a reasonable plan? Have people had this kind of thing work well in the past?

late lion
#

I haven't used WeakReference directly before.

heady iris
#

well, I'm not even able to make an IL2CPP build on my macbook, so...

#

🫠

leaden ice
heady iris
#

it just falls over and explodes due to a code signing error

heady iris
leaden ice
heady iris
late lion
#

I ended up just using IDisposable.

heady iris
#

I was also considering this.

#

I don't want to have to explicitly dispose these objects, though. There's going to be quite a variety of them -- some will be MonoBehaviours, some will be plain old classes

#

I also need to store a hierarchy. Normally, non-root debuggables only get drawn if their parent is getting drawn. It looks like this:

            foreach (var child in debug.ShowDebug())
            {
                if (!debugShown.TryGetValue(child, out var shown))
                {
                    debugShown[child] = false;
                }

                if (debugShown[child] = WantsDebug(child))
                {
                    ShowDebug(child, depth + 1);
                }
            }
#

I want to be able to "pin" a debuggable so that it is always drawn. But if an object is pinned and its parent is active, it shouldn't get drawn twice

#

i guess i could make a list sorted by the depth the child is found at (this is a tree, so the object can't be at multiple depths), store all of the rendered objects in a hash set, and then scan the list for objects that are 1) not in the hash set 2) marked as pinned

#

i'll play with that. i'm more interested in the weak references right now

#

also, what a nuisance: WeakReference and WeakReference<T> have completely different sets of methods and properties!

#

ah, there's an issue: two weak references made from the same reference aren't going to count as the same dictionary key

#

I presume that's why ConditionalWeakTable exists in the first place.

#

I already use System.Runtime.CompilerServices elsewhere in my code -- I remember having to go find a DLL so that I could use Unsafe.As for some cursed enum stuff. So I guess it couldn't hurt to use it again...

#

argh this is cursed

#

there is a third option: just don't worry about leaking at all

#

all of this data will die when the scene unloads anyway

#

and I could really just do a "manual prune" by dumping out the state dictionary into a list of weak references and asking for a garbage collection

#

if it absolutely mattered

gray vessel
#

I have a custom spotlight texture that extends the vertices automatically to get the right size. But, it gets frustrum culled when the original sprite (shown by the box size) is offscreen. Is there any way to fix this without reworking the shader?

heady iris
#

There's no "update when offscreen" equivalent, is there?

#

like you have for SkinnedMeshRenderer

leaden ice
#

You can override the default bounding box by setting your own world space bounding box. This is mostly useful when the renderer uses a shader that does custom vertex deformations, and the default bounding box is not accurate.

heady iris
#

Ah, there it is. I forgot you could just set it!

gray vessel
noble surge
#

Is there any major difference between vscode and visual studio for Unity?

rigid island
leaden ice
#

Navarone summed it up well

#

I recommend Rider if you can afford it or if you're a student and can get it free

scarlet viper
#

I want to premake rotations and pick them with a dictionary but im not sure how to do it

var rotation = dictionaryWithRotations[localpos.y]

something like this. but the issue is position Y could be eg. 0.923426. Theres too many possibilities to account for all of them (to make dict keys for all of them)

#

maybe i could use math inverse lerp or lerp idk

#

but a number from LERP could also be something long and bizarre like 0.912321
i could round them up to 0.01 but then I would have only 100 (lerp goes from 0 to 1) entries in my dictionary but i need more/a better control over the amount of dict keys

#

I feel like this is a simple math problem but i cant wrap my head around it

heady iris
#

what is the goal here?

#

what gameplay feature is this needed for?

scarlet viper
#

just an animation made by rotating things based on position

heady iris
#

is there no formula to turn a position into a rotation?

#

You could use InverseLerp to turn a range into a value from 0 to 1, then convert that into an integer between 0 and n (exclusive) to index an array

heady iris