#archived-code-general

1 messages · Page 219 of 1

pure scarab
#

it freezes on this

sonic bone
#

Multiplayer coding help

pure scarab
cosmic rain
pure scarab
#

but the unity editor completely freezes, it doen't respond to input, not anything

cosmic rain
#

The debugger is in your ide.

pure scarab
#

you mean the profiler right?

fervent furnace
#

Debugger is not profiler….

pure scarab
#

or this??

fervent furnace
#

It is a function provided by your ide

cosmic rain
pure scarab
#

you mean the debugger in visual studio?

fervent furnace
#

Yes

cosmic rain
#

Yes.

finite swift
#

Currently having a bug in where when the player dies when walking to the left when he respawns it will spawn the player sprite facing to the right, however the actual player think it is facing to the left, and so when walking to the left it does not switch the sprite from right facing, to left facing, and vice versa
(You can feel free to ignore the IEnumerator Respawn, as that simply resets the level after an amount of time, the IEnymerator Life seems to be where the problem resides)
https://paste.ofcode.org/wfFMLfb2fknjExqcwE6xrj

#

Sorry if my explanation of the bug is bad, I can send a few screen shots if need be

knotty sun
finite swift
#

I thought the issue might have been coming from there, but after awhile of bug testing it seemed like it wasn't the source of the issue

#

I could easily be wrong though

knotty sun
#

ok, so in Life you are setting localScale to 1,1,1 after the Wait.
you need to save the current localScale before you set it to 0,0,0 and then restore that after the wait

finite swift
#

Awesome thank you! Works like a charm

knotty sun
#

where do you set LS ?

finite swift
#

Ill paste the whole coe as well in case anyones interested

knotty sun
#

why? why not just set it before you set the localScale to 0,0,0 ?

finite swift
#

True actually

#

ty

quartz folio
#

Your IDE looks underhighlighted, if you're not getting autocomplete and code completion you need to configure it !ide

tawny elkBOT
quartz folio
#

@finite swift 👆

swift falcon
#
if (PrefabStageUtility.GetCurrentPrefabStage() != null)
{
    StageUtility.GoToMainStage();
}```For some reason sometimes I get "ArgumentNullException: Value cannot be null." from "StageUtility.GoToMainStage();"?

But I'm not sure how I can possibly be getting that error?
rocky helm
#

Is GoToMainStage supposed to take in any arguments?

swift falcon
#

No, and it only errors sometimes

rocky helm
#

Show me the function

swift falcon
#

All the code leading up to it?

rocky helm
#

No, just the function

swift falcon
#

Not sure which function you want but

    public static void EditItemSO(UnityEngine.Object selectedObject, bool adjustCamera = false)
    {
        // Don't do anything if we try to edit with no object selected
        if (selectedObject == null)
        {
            Debug.LogError("Can't edit prefab, there is no selected item to edit.");
            return;
        }

        currentItemBeingEdited = selectedObject;
        if (selectedObject is ItemSO item)
        {
            GameObject prefab = item.prefabs[^1].gameObject;
        
            // Check if the selected object is the prefab
            if (PrefabUtility.IsPartOfPrefabAsset(prefab))
            {
                // If we are already editing, clear it
                if (PrefabStageUtility.GetCurrentPrefabStage() != null)
                {
                    StageUtility.GoToMainStage();
                }```
rocky helm
#

No I meant the GoToMainStage function

#

Should have specified

knotty sun
swift falcon
#

I don't have access to that? It's a Unity internal one

rocky helm
#

Oh its a literal thing

#

Mb

swift falcon
#

Which leads me to not understanding why it's giving me that error

knotty sun
#

can you screenshot the error and post your complete code to a paste site

pliant mulch
#

someone knows why if I create a script to use mouse on border screen to move camera horizontally, my camera move in Y axis too if i go backwards?

swift falcon
#

The whole massive console error?

#

Well.. might as well I guess

#

More is better than less

knotty sun
#

And you've cut out the most important bit

swift falcon
#

Also the 3 scripts involved, the entire thing?

#

Cut out? That's the entire thing?

#

There isn't more?

knotty sun
#

my bad

swift falcon
#

So do I paste the entire script of all 3 scripts?

knotty sun
#

PrefabOptions script

swift falcon
knotty sun
#

I would say, without a doubt that that is a Unity Editor bug

#

only thing you can do is wrap your code in a try/catch

swift falcon
#

Yeh because weirdly enough it only breaks sometimes, if I run the "Reset" button instead of "Save" it'll run that line fine

#

It seems to only occur if I am editing GameObjects that are not the main prefab

#

So all those in "Stages" are other prefabs I loaded in

knotty sun
#

certainly nothing you can do about it, there's nothing wrong with your code

swift falcon
#

Okay I was worried maybe I was doing something to break the editor

#

Which I mean, I might still be doing somewhere

knotty sun
#

you could try to put a call to GetMainStage before the GoTo and see what it returns

swift falcon
#

Don't fully know what you mean, call it in the other script? I'll see

knotty sun
#
              if (PrefabStageUtility.GetCurrentPrefabStage() != null)
                {
                    SceneManagement.MainStage mainStage = StageUtility.GetMainStage();
                    if (mainStage == null) Debug.Log("main stage is null");
                    StageUtility.GoToMainStage();
                }
#

should never debug but you never know

swift falcon
#

SceneManager in UnityEngine namespace? if so, there isn't a MainStage in it

knotty sun
#

UnityEditor

swift falcon
#

Yeh that'd make more sense 😅 sorry

#

mainStage isn't null

#

It went through and gave an error

knotty sun
#

then it is a bug

swift falcon
knotty sun
#

so wrap it in try/catch to mitigate it

swift falcon
#

Could it be because of how I am editing prefabs?

#

I've noticed it only seems to happen if I am editing a prefab which isn't the main one

knotty sun
#

no, MainStage should never throw an exception unless something very silly has happened in the Unity C++ code

swift falcon
#

Okay because if I rename the green one, never errors
If I edit red one, always errors

#

I'll put it in a try 🙂 Thanks for the help

knotty sun
#

maybe raise a bug report

swift falcon
#

It's been really difficult getting the hang of Unity editor stuff, especially UI stuff but hopefully now I can move forward

austere cape
#

hello guys I am doing my own custom editor and I want to create a slider like this in this image I am asking how to do it or is there any resources I can learn from I search and I didn't find it

lime patrol
#

Hi guys we made it with @knotty sun . Devs want to get info with JS. I made it it's working but they are keep telling me "we can't see data, it's not sending". How they will catch that info? They are iframing game on application.

#

And they are C# codes ;

    [DllImport("__Internal")]
    private static extern void trackEventEndGame(string id);

    [DllImport("__Internal")]
    private static extern void trackEventBack();

    [DllImport("__Internal")]
    private static extern void trackEventActiveState();

    public void CallTrackEventEndGame(string id)
    {
        trackEventEndGame(id);
    }

    public void CallTrackEventBack()
    {
        trackEventBack();
    }

    public void CallTrackEventActiveState()
    {
        trackEventActiveState();
    }
swift falcon
#

Btw Steve, I use the "EditorApplication.delayCall" to get my script to call itself again 1 frame later and 1 frame throws a few errors but at least it recovers now

#

Thanks again for the help

knotty sun
swift falcon
#

Oh I just double checked and it actually fails for 2 frames and then the 3rd frame goes through

knotty sun
swift falcon
#

Yeh maybe.

knotty sun
#

you could drop the code into an EditorCoroutine with a while loop

swift falcon
#

I just do this currently

lime patrol
#

I didn't add it too code. That's why?

knotty sun
#

that is not the way the system works

lime patrol
#

They are saying it's not redicting

#

How can i test it? From console to proof them it's working

knotty sun
#

does not surprise me, that doesn't look like a valid URL to me

knotty sun
lime patrol
#

console.log(trackEventBack);

#

just that?

knotty sun
#

no, console.log("in trackEventBack");

lime patrol
#

Btw i added ActiveState method in when it's not focusing game call it etc. It's calling right?

#

Yes not found because it's not a URL

knotty sun
static matrix
#

Cannot modify members of 'room' because it is a 'foreach iteration variable'
im confused about this error,

 foreach (RoomNames room in cameraManager.roomNames)
     {
        if(room.Num == cameraManager.CurCam){
            return room;
        }
        if(room.TimeRemainingTillDebug >= 0 ){
            room.TimeRemainingTillDebug -= Time.deltaTime;
        }
     }

i've done code like this before, without any errors,

foreach (StatusEffect effect in statuses)
            {
                effect.TimeLeft -= 1;
                effect.TickActivation();
                if(effect.TimeLeft <= 0)
                {
                    effect.OnRemove();
                    RemStat.Add(effect);
                }
            }

so idk why its giving me one now
the only difference is that statuseffect is a class derived from scriptable object and RoomNames is a struct, but I didn't think that would mess with how you could access the variables contained within

static matrix
#

wdym
that is the error

fervent furnace
#

i believe the error should be renamed
since it is a just that means the variable returned from Next() will be the copy and you are modifying the copy, not the struct in the collection

static matrix
#

so it does matter that its a struct?

cosmic rain
#

Yes.

#

Use a regular for loop. Modify it and assign the modified struct back to the array

#

Or make it a class.

static matrix
#

agh
thats annoying
ok

spring creek
proper plank
#

I'm guessing there is a simple answer but I couldn't seem to find it for my student.

I'm curious why this might happen. The student has a pause menu created however it doesn't visibly show in all of their scenes. It is in the hierarchy, the game pauses, they have their event system, however the menu just doesn't get set active even though it's using the same code as other scenes. They get no errors or warnings. They used print statements & break points to track things down, the timeScale gets set and bools get updated but pauseMenu never gets set active in this particular scene.

Their script looks something like below, and uses the event system to activate it.

void Pause()
{
  if (!isPaused)
  {
    isPaused = True;
    Time.timeScale = 0;
    pauseMenu.SetActive(True);
  }
  else
  {
    ...
  }
}```
static matrix
#

is the menu in DontDestroyOnLoad?

#

oh wait when you set timescale to 0 does the script stop totally
bcause if thats the case it will be pausing before the menu is set active

pliant mulch
static matrix
#

you can use pastebin

spring creek
pliant mulch
#

how to embed code?

spring creek
tawny elkBOT
static matrix
#

```cs
code here
```

pliant mulch
#

I don't have this character in my keyboard, i mush copy from web every time?

#

Italian keyboard

proper plank
pliant mulch
#

no pc

spring creek
pliant mulch
#

I have this only "'"

#

| this is my left of one xD

hard viper
#

yeah, it’s a very weird charcacter

pliant mulch
#

the pipe

static matrix
spring creek
#

Then just use a paste site 🤷‍♂️
Oh, or you can copy paste it from above!

fervent furnace
#

time scale will not affect setactive since it is not time based operation (i think)
DDOL is needed for the pause if the scene will be unloaded

hard viper
#

i see, so yeah you don’t have that key

#

here. to copy paste:
``

pliant mulch
#

cannot paste too much characters

spring creek
hard viper
#

that’s the best I can do for you, fam

pliant mulch
proper plank
#

They fixed it but don't know why. They just deleted the player prefab on that scene and re-added it and it started working.

ember ridge
#

Does anyone know how to lay items in a wave shape like Revita? I’ve tried a couple of times and can’t seem to make it work.

fervent furnace
#

the placement in bottom left?

ember ridge
#

yes

hard viper
hexed pecan
hard viper
#

this code lets you make a variable that you can: 1) publicly read from anywhere, 2) edit in inspector, and 3) block other classes from editting it

hexed pecan
#

@ember ridge Does this need to be done from code though? You could just place the slots there by hand

ember ridge
#

nah, I want to place them by hand, but couldn't make it work

hexed pecan
pliant mulch
fervent furnace
#

you keep a pivot line eg y=k then for function (x,y) = (x,k+Asin(Bx)) you can do sampling on this vector function by given x outputs y, A is amplitude,
or place it manually
put the item (image of other cmponent) in other gameobject and the other gamobject is ordered by layout group)

#

A layout group
L B
| L Item
L B
| L Item

ember ridge
hexed pecan
#

The above answer is also for you, if im not mistaken

#

I would just do a for loop and something like cs bool isOdd = i % 2 == 1; Vector2 pos = new Vector2(i * spacingX, isOdd ? offsetY : 0);

#

Constant spacing on the X axis and every other element gets offset in the Y axis

ember ridge
fervent furnace
#

just an empty gameobject

#

which is the parent of the item gameobject

#

then you can freely control the y position of the item gameobject (ofc dont control the x)

ember ridge
#

oh, gotcha

#

I will make an empty object that has a horizontal layout component first, then add several items to it. Under Items, I will add my actual UI related item objects and adjust their height based on the above code.

edgy sierra
#

greetings, has anyone here used unity3D with kafka?

sonic bone
sly ivy
#

Hey, Im needing help with displaying values through string. I need 1250 to be displayed as 1.25K but currently it only shows as: 1.00K
How the code works atm is:

#
  {
    valueTMP.text = "$" + (value / 1000).ToString("F2") + "K";
  }```
fervent furnace
#

integer division

somber nacelle
#

divide by 1000f instead

sly ivy
#

me smol brain

somber nacelle
#

int divided by int returns int

sly ivy
#

ah

#

even if its forced to display by two decimal points with F2?

#

cus it does show decimal, just replaces the actual value by 0s

somber nacelle
#

yes, just because you display an int with decimal places doesn't make the actual value have them

spring creek
sly ivy
#

so simply making it into 1000f fixes it then?

somber nacelle
#

yes because any operation involving an int and a float will return a float

sly ivy
#

damn

#

that was simple, thanks

#

yeah fixed it, thank you so much for the help

obtuse canyon
#

How should i make a custom editor component which would clone my object into a grid?

rain blade
#

Hey guys, recently I upgraded my project from 2020.3.26f1 to 2020.3.48f1, and after doing so I received 2 errors both saying the same message, and I have no clue on how to fix it.

Copyright (C) Microsoft Corporation. All rights reserved.

warning CS2029: Invalid name for a preprocessing symbol; '(7)' is not a valid identifier
warning CS2029: Invalid name for a preprocessing symbol; '>-' is not a valid identifier
error CS2001: Source file 'C:\Users\brxwn\OneDrive\Desktop\Old Desktop\Desktop\AppleClimbersNEW\Cube' could not be found.```
Is there anyone here who has also received this error? If so please tell me how you fixed it. Thanks! ![UnityChanSalute](https://cdn.discordapp.com/emojis/885169594808033280.webp?size=128 "UnityChanSalute")
hard estuary
rain blade
#

I'll try it!

knotty sun
spring creek
hybrid turtle
#

ok ive been putting this off and debugging for a while literally put it off and did other things but here is a link it continues to not work on pc but only my mac

#

it has genuinely alluded me to what can be wrong with this because even the logs show all the correct data but the actual program is not behaving as intended

fiery path
#

Mind is kind of rotting learning state machines
Watched three videos and still kind of in the same place
Any tips?

wide mural
#

Trying to use vscode with Unity, just fresh installed but dont have the documentation in vscode and i get this error, any fixes?

rain blade
tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

somber nacelle
#

double kill

rigid island
#

🦥

wide mural
somber nacelle
#

restart your computer if you have actually followed all of those steps correctly

somber nacelle
#

have you followed all of the instructions in that guide and also restarted your computer?

wide mural
#

i didnt install vs2022 with unity would that affect it

somber nacelle
#

no

wide mural
#

yes i have

somber nacelle
#

then consider switching to a real IDE like vs2022 instead of a fancy text editor

wide mural
#

bro? XD

craggy oyster
#

im having a problem with figuring out shooting bullets in 2d

#

i cast raycasts for deducting health and then instantiate a bullet prefab for show

wide mural
#

why cant ppl just say they dont know instead of being angry

craggy oyster
#

i then check the distance between the bullet and hit object for determining when to destroy the bullet

spring creek
# wide mural bro? XD

Vscode is not supported by unity. Many people have issues with it. If you followed that guide and restarted your computer, you may want to consider just using visual studio which IS supported directly by Unity

craggy oyster
#

but this method seems to be a little inconsistent

spring creek
wide mural
spring creek
somber nacelle
spring creek
#

Show the package manager

wide mural
#

I was typing it then this person says to just switch

spring creek
wide mural
#

alright well

#

w/e

#

Xd

spring creek
wide mural
#

its a fresh install

rigid island
#

you're gonna have to debug why dotnet is missing.
show us all the plugins in VScode

wide mural
somber nacelle
spring creek
# wide mural

Remove the Visual Studio Code Editor package. Both use the Visual Studio Editor package

spring creek
wide mural
#

done, still there

rigid island
wide mural
spring creek
# wide mural

You probably don't want all those project files, but that isn't relevant.

The biggest question that was unclear from your responses:
Did you restart your computer?

rigid island
#

hmm it might need a proper restart or something if the whole dotnet is somehow missing

wide mural
#

And I just tried to regenerate everything to see if thatd help

#

Ill try restarting again

spring creek
rigid island
#

yea if its still an issue install .net sdk manually or sum

wide mural
#

then ill restart

wide mural
#

thx bro it works now 👍🏻

brittle sparrow
#

If I wanted to make an inventory, but I had to display as many item icons as there are slots, would I really have to make 81 gameobjects for that.. including item count display... I wonder if there's a better way to draw the icons and item count.. any ideas? Not sure how to look this one up, thanks!

#

my current prototype using tiled sprites, and a single collider gameobject that moves around based on the cursor's position, a really smart little tile

leaden ice
#

I'd stick with that unless there's a compelling reason not to, as it will be the simplest to implement

brittle sparrow
#

oh, GridLayoutGroup.. I'll look that one up, thanks!

hard estuary
brittle sparrow
#

oh, so it preprocesses positions and stuff? so i'll have to make 81 objects after all..

#

i mean yeah it's not that bad i guess

#

but still..

brittle sparrow
#

what's sort of the limit of spriterenderers you can throw into a project before it really goes wrong?

wide mural
#

i think ull be fine

brittle sparrow
#

was curious for some time

#

for the average pc*

swift falcon
#

my old laptap can handle 10k without problem

brittle sparrow
#

oh wait

rain blade
brittle sparrow
#

i had to make 81 text objects too...

wide mural
swift falcon
#

just make one object properly, and duplicate it when you sure it's fine

brittle sparrow
#

if theoretically a gameobject had a spriterenderer and a text object at the same tiem, would it be the same ashaving two separate gameobjects for each?

#

yeah, im probably gonna put a single icon/tile, and duplicate it in runtime

#

easiest way

swift falcon
#

instantiate is costly btw

brittle sparrow
#

ill put it in a loading screen yeah

swift falcon
#

just have them permanently ecisting

#

then just change their vlaues when needed

brittle sparrow
#

yeah!

#

thanks everyone!

#

now i feel more confident about using manyobjects

heady iris
#

i had someone a week ago who had the extension installed, restarted their computer, and still had an acute case of No-SDK-itis

#

a manual install worked in that case, fortunately. very weird.

vague plank
#

I had to manually install the SDK myself for some reason.

hard estuary
heady iris
#

I haven't recently had a problem with it refusing to download the SDK

#

it has decided it needs a new version while I'm on an airplane twice, though..

#

and I have been completely unable to make it respect the setting to use an existing SDK install

vague plank
#

Btw anyone here making use of ComputeShaders for Data processing? I am trying to figure out the best way to handle a stupid scenario, but I am coming empty. x)

heady iris
#

explain the problem you're trying to solve

#

not "how to use compute shaders to do X", but "how to do X"

brittle sparrow
hard viper
#

is there a simple way for me to call Sort on a fraction of a list?

#

I have a list that is bigger than it needs because it's for non-alloc physics. but as a result, only the first N entries are real.

hard viper
#

awesome. thanks

#

uh, how do I make an IComparer quickly?

#

I have this:

raycastResults.Sort(0, totalHits, sorter);```
Which doesn't work, since Comparison doesn't implement IComparer
#

I could make a class for it, but is there a simpler way that just uses a lambda?

simple egret
#

Yeah you can do a Comparer<RaycastHit2D>.Create(your lambda here), and cache it somewhere

hard viper
#

uh... what?

hybrid turtle
#

his guys is there a way to save addiitvely loaded scenes in not at runtime in unity

hard viper
#

huh. interesting

spring creek
hard viper
#

so Comparer has a .Create constructor, that makes a comparer with a lambda?

spring creek
hybrid turtle
#

like i just opened it additively but when i go to push git doesn't save VideoCont scene as additively loaded

spring creek
hybrid turtle
#

yup

#

is there a work around or something? possibly a saver script

simple egret
hard viper
#

wow, that's slick, SPR. ty. I wish I could do it without caching anything, but this is ok too.

fringe raven
#

anyone have a basic camera controll script that mimicks the scene camera behavior (wsadeq and shift?)

lean sail
hard viper
#

I now have

raycastResults.Sort(0, totalHits, sorter);```
spring creek
hybrid turtle
hard viper
#

use imagination. imagine a world where the indentation looks good

simple egret
lean sail
hard viper
spring creek
hard viper
#

bonus question: Could I define an extension method to... make RaycastHit2D just have the IComparer? or implement IComparable?

#

I imagine no, but I have to ask

hybrid turtle
#

for anyone that may need it as well

heady iris
#

and it's not saved

#

but yeah, I can imagine you could write a script to remember that

gray mural
hybrid turtle
gray mural
#

Does any one know why WaitUntil doesn't work in a static coroutine?

heady iris
#

i don't know what a static coroutine would be

#

a coroutine runs on a specific MonoBehaviour

gray mural
heady iris
#

show your code

gray mural
# heady iris show your code

In the following example coroutine stops working after yield, so that levelData isn't assigned

public static IEnumerator LoadSceneAndPlay(string sceneName, string levelId, bool value)
{
    SceneManager.LoadScene(sceneName);

    yield return new WaitUntil(() => SceneManager.GetActiveScene().name == sceneName);

    LevelData levelData = GetLevelData(levelId);
    GameUtility.currLevel = levelData;
    GameManager.PlayGame(value);
}
heady iris
#

and how do you start the coroutine?

gray mural
spring creek
heady iris
#

and which object is this running on?

lean sail
#

I imagine you're destroying the object that is starting this coroutine, since this is related to scenes?

heady iris
gray mural
spring creek
heady iris
hard viper
#

anyway, tyvm @simple egret. The clean code now makes me happy. UnityChanThumbsUp

gray mural
#

I've changed some methods to static when refactoring my code

heady iris
#

I would not expect it to matter. A non-static method will have access to this, but there should be no other differences.

#

And you don't use any members here.

#

(well, it'd be impossible to use them in a static method!)

heady iris
#

I said I see no reason for it to fail.

#

Something else is causing this.

#

unless you're asking why a static method wouldn't have this?

gray mural
#

ok, let me test it out quickly

gray mural
heady iris
#

this is the object the method is running on

gray mural
#

I see

heady iris
#

a static method isn't associated with a specific instance, so there is no this

gray mural
#

anyway, I don't call this there

heady iris
#

yeah, that'd be a compile error

gray mural
#

So, apperently, this issue isn't associated with a WaitUntil being called in a static coroutine

public static IEnumerator LoadSceneAndPlay(string sceneName, string levelId, bool value)
{
    print("started");

    yield return new WaitUntil(() => 1 == 1);

    print("ended");

    SceneManager.LoadScene(sceneName);

    yield return new WaitUntil(() => SceneManager.GetActiveScene().name == sceneName);

    print("waited until");

    LevelData levelData = GetLevelData(levelId);
    GameUtility.currLevel = levelData;
    GameManager.PlayGame(value);
}
#

here started and ended are printed, but waited until isn't

heady iris
#

oh

#

the scene name might not be what you expect

#

try logging it

#

I remember having an issue like this -- I think the scene name wound up being the entire path?

#

i.e. it was Scenes/Fooscene, not Fooscene

gray mural
#

the thing is that it all worked before I've changed some methods to static...

#

I've just changed it back to non-static, but it still doesn't work..

heady iris
#

that'll log the name of the active scene each time it checks

gray mural
#

thank you, just tried to do it before waituntil

#

didn't work, as expected

heady iris
#

that would be too early

gray mural
#

yes.

heady iris
#

since the scene will load one frame after you call the LoadScene method

simple egret
#

I just arrived, but coroutines run on the game object that started it. If you switch scenes and the object on which the coroutine runs isn't persisted, it will stop as soon as the object is destroyed

gray mural
#

You're right. I receive a single print

yield return new WaitUntil(() =>
{
    print($"sceneName: {sceneName}; active scene: {SceneManager.GetActiveScene().name}");
    return SceneManager.GetActiveScene().name == sceneName;
});
#

the most confusing about it is that it worked before...

simple egret
#

It will work if you load additively, or called DontDestroyOnLoad() on this object

heady iris
#

well, you might have changed more than one thing at a time

#
git status | wc -l
      53
#

😬

#

ask me how I know about that

gray mural
#

that's why...

heady iris
#

well, it's not that you can't "call" a coroutine in a static method

#

it's that StartCoroutine is an instance method of MonoBehaviour

#

so if your method isn't a member of a MonoBehaviour, or your method is static, then StartCoroutine won't be available to you

#

and you'd have to have a reference to a MonoBehaviour to call the method on instead

#

Perhaps you were previously running the coroutine on an object that didn't get destroyed by the scene change

#

and now you are running it on one

gray mural
#

so do you have any suggestions then?

#

do I change it back to a non-static

#

isn't it the best variant here?

heady iris
#

no. the problem is that you're running the coroutine on an object that is getting destroyed

#

don't do that

#

Although, if you have no reason to make the method static, then I guess you could, indeed, just make it an instance method again

gray mural
# heady iris no. the problem is that you're running the coroutine on an object that is gettin...

No, you haven't understood. It looked like this in the previous commit

public void LoadSceneAndPlay(string sceneName, string levelId, bool value)
{
    StartCoroutine(LoadLevelCoroutine());

    IEnumerator LoadLevelCoroutine()
    {
        SceneManager.LoadScene(sceneName);

        yield return new WaitUntil(() => SceneManager.GetActiveScene().name == sceneName);

        LevelData levelData = GetLevelData(levelId);
        GameUtility.currLevel = levelData;
        GameManager.PlayGame(value);
    }
}
heady iris
#

yes, because this is an instance method on a MonoBehaviour

heady iris
gray mural
#

I've just called the method before

#

now I'm gonna do this again I guess?

heady iris
#

Oh, I thought the method that was starting the coroutine was also static. Is that not the case?

#

Just show the code. I can't see your screen.

gray mural
#

I was assuming you could

#
private void ModifyLevel() =>
    LevelManager.instance.LoadSceneAndPlay("LevelCreator", 
        levelsSelectionField.currOption.GetComponent<LevelInfo>().levelData.id, false);
#

that's the previous commit

#

that did work

#

it used to call a method that had an embed coroutine

simple egret
#

LevelManager.instance
Singleton. High chance this has a DDOL call in Awake

heady iris
#

There's no reason you can't have a local function in a static method

#

I presume the problem was that StartCoroutine no longer existed.

gray mural
gray mural
#

that's the problem

heady iris
#

okay, so your old code started a coroutine on the LevelManager instance

gray mural
#

So by starting a coroutine in another class, we make sure it won't disappear

heady iris
#

Your new code starts a coroutine...somewhere. You still haven't shown us that.

#

Whatever object you're starting it on must be getting destroyed.

gray mural
#

the script is destroyed once a scene is changed

heady iris
#

LevelManager.instance.StartCoroutine(...) will start a coroutine on the level manager instance

gray mural
#

and it isn't destroyed

#

so the stuff after WaitUntil is successfully called

heady iris
#

then just do that, and it'll work fine

gray mural
heady iris
#

That is unrelated.

heady iris
#

If you are inside an instance method of a MonoBehaviour, you have access to all of the other instance methods of MonoBehaviour

#

One such instance method is StartCoroutine

#

When you write this...

gray mural
hard viper
#

is 1E-5f ok syntax for a float? want to make sure I don't summon some eldrich binary demon

heady iris
#
public void Foo() {
  StartCoroutine(Bar());
}
#

this is equivalent to writing:

#
public void Foo() {
  this.StartCoroutine(Bar());
}
#

In a static method, you don't have this, so you can't just write this

#
public static void Foo() {
  StartCoroutine(Bar());
}
hard viper
#

oooh, we teaching the man about static

heady iris
#

You got around this by changing your code to look more like this

#
public static IEnumerator Foo() {
  return Bar();
}
hard viper
#

the easy explanation that stuck with me, and made life very easy:
"static" means something is owned by the class definition, and not by any one instance

simple egret
#

Wait till they hear how their local function can access variables outside of it lmao

heady iris
#

And that someone else, in your case, was an object that got destroyed during the scene load

gray mural
heady iris
#

You made LoadSceneAndPlay return an IEnumerator, rather than starting a coroutine

gray mural
hard viper
#

example:

private static pi = 3.14159f;
public float radius;
public Circle(float radius) {this.radius = radius;}
}```
heady iris
#

I was explaining how you could do LevelManager.instance.StartCoroutine to run a coroutine on the level manager object.

gray mural
hard viper
#

Circle.pi is owned by the definition of a Circle, but radius is owned by individual instances. individual circles have their own individual radii.

heady iris
#

LevelManager.instance.StartCoroutine(LevelManager.instance.LoadSceneAndPlay(...)), for example

hard viper
#

you can't run a coroutine static. it needs to run on an instance

heady iris
#

Are you trying to get rid of the LevelManager instance entirely?

gray mural
gray mural
heady iris
#

Ah. I see.

gray mural
hard viper
#

you can make a static reference to a coroutine. You can make a static method that creates a Coroutine or IEnumerator for one. but you can't StartCoroutine as static

gray mural
#

I have got rid of it. Almost. But the coroutine...

heady iris
#

There will need to be an object somewhere to run the coroutine on, yeah.

gray mural
#

it's just annoying that not everything is static..

#

thank y'all for your help 😄

wispy wolf
#

Say I have a transform and a gameobject. From the perspective of this transform the gameobject is offset by <x,y,z> units and rotated by <x,y,z> degrees.

But I have another transform in a different arbitrary location and rotation. I want to move and rotate the gameobject so that, from the point of view of this new transform, it is in the same position it was relative to the old transform.

Its hard to describe. How do I do this?

leaden ice
#

but sounds like you jsut want to get the local position and rotation of an object

#

and then apply that local position and rotation to another object

#

Is this for a portal system?

brittle oyster
wispy wolf
# leaden ice but sounds like you jsut want to get the local position and rotation of an objec...

A transform can exist without a gameobject, its just a struct. What I'm attempting to do would take a long time to explain.

Imagine you are a transform. You have a location and a rotation. You see an cube in front of you. Relative to you, this cube is at <x,y,z> and is rotated relative to you by <a,b,c>.

Now you move. Anywhere, I don't care. You look in a different direction. Your transform is now completely different.

Now I want to move that cube to a new location and rotation so that from your perspective it hasn't moved at all.

leaden ice
#

so I assumed that's what you meant

leaden ice
heady iris
#

sounds like you just want to reparent something and keep its old local transform

wispy wolf
#

I don't want to change parents tho

#

In a way yes, but without the actual parent changing

heady iris
#

You can also just calculate a world-space position and rotation

#

perhaps something like this

#
Transform movingObject;
Transform oldViewer;
Transform newViewer;

Vector3 oldLocal = oldViewer.InverseTransformPoint(movingObject.position);
Vector3 newWorld = newViewer.TransformPoint(oldLocal);

movingObject.position = newWorld;
#

This will find the local position of movingObject from the POV of oldViewer

#

It will then figure out where that same local position is for newViewer

#

I am less confident about rotation

brittle sparrow
#

this is okay to have.. right?

leaden ice
wispy wolf
#

Rotation is kind of the hard part because it would need to be rotated as if the new transform were the world axis.

heady iris
brittle sparrow
#

they're basically inventory slots consisting of an icon and item count each

heady iris
#

I'd expect something more like

brittle sparrow
#

nothing that would cause major performance issues basically

heady iris
#
  • slot
    • icon
    • label
  • slot
    • icon
    • label
  • slot
    • icon
    • label
brittle sparrow
#

oh

#

yeah, they're all done in runtime so it's fine!

leaden ice
heady iris
heady iris
brittle sparrow
#

oh right, unity has that sort of stuff built into it

heady iris
#

It takes a little while to learn how to use it correctly

#

The UI docs do a good job of explaining it

wispy wolf
heady iris
#

I do not follow.

leaden ice
heady iris
#

try it and see!

#

this stuff can be surprisingly easy when you let Unity do all of the math for you

#

i wonder if this is for a perspective-manipulation puzzle game

wispy wolf
#

T1 and T2 exist at the same location. The only change is the rotation on the Z axis. But the purple dot doesn't just rotate, it has to be moved and rotated

heady iris
#

yeah, my code handles that part

wispy wolf
#

cool I'll combine them then and see what happens

heady iris
#

The purple dot's world position is updated so that its local position, in the eyes of T2, is the same as its local position was in the eyes of T1

#

Scale is going to be a trainwreck if it's non-uniform, so don't do that

#

but uniform scaling ~should~ be okay

wispy wolf
#

I'm not doing anything with scale (yet, hopefully ever)

leaden ice
#

of course the cute/cheeky way to do this is:

Transform originalParent = movingObject.parent;

movingObject.SetParent(oldViewer, true);
Quaternion localRotation = movingObject.localRotation;
Vector3 localPosition = movingObject.localPosition;

movingObject.SetParent(newViewer);
movingObject.localRotation = localRotation;
movingObject.localPosition = localPosition;

movingObject.SetParent(originalParent, true);```
heady iris
#

yeah, just shuffling objects around

leaden ice
#

and the code we already shared should do it

heady iris
#

I might just do that

#

I've done similar things in the past to avoid having to think too hard

main coral
#

Hello, what is a good option with Unity Gaming Services that allows players to log in only with the current game version?

modern creek
#

Somehow my project (using Unity.UI) got the default material set to some other material (that doesn't have the _Stencil property). How do I .. set this back?

#

like my "none" material is using that AllIn1SpriteShader material:

delicate flax
heady iris
#

i don't think they want to make it impossible to connect with an old version

#

just to prevent honest players from doing so

forest ravine
#

About Physics.CheckBox, if using theoverload that takes a rotation, how is the final "box" checked?

#

Do I end up checking against a box that is rotated? Or against that one sufficiently large to accommodate the rotated one?

heady iris
#

The former.

#

It's not an axis-aligned bounding box!

#

just a box

forest ravine
#

Really? I'm using it to ensure I can place a new room contiguously to another and it's failing quite more often than I'd like to

leaden ice
#

probably a bug in your code.

#

wdym by "failing"?

heady iris
#

If you're using a new enough version of unity, you can turn on the physics debugger to see the queries

#

This is very useful.

forest ravine
#

Where would that be?

forest ravine
#

Thank you

void basalt
forest ravine
#

Turns out my version has Physics Debugger but not the one that shows queries

somber nacelle
#

then you'll need to show code or something if you want help

forest ravine
#

This is what I use to obtain the bounds:

    public Bounds GetBounds()
    {
        if (colliders.Length == 0)
            return new Bounds();

        Bounds bounds = colliders[0].bounds;
        foreach (var collider in colliders)
            bounds.Encapsulate(collider.bounds);

        bounds.Expand(_boundsExpandBias);
        Vector3 offset = transform.TransformDirection(_boundsCenterDisplacementBias);
        bounds.SetMinMax(bounds.min + offset, bounds.max + offset);

        return bounds;
    }
#

And then:

leaden ice
#

why are you using bounds?

#

collider bounds ARE axis aligned bounding boxes

forest ravine
#

I thought it was a quick way of knowing if I could place a new room adjacent to another

leaden ice
#

well if your rooms are rotated it won't be accurate

#

or if they're any shape other than a box

#

I thought you were using OverlapBox?

forest ravine
# forest ravine And then:
            Bounds bounds = moduleData.GetBounds();            
            if (!Physics.CheckBox(bounds.center, bounds.extents, instanceRoot.transform.rotation, _modulesPhysicsOverlapCheckLayers))
forest ravine
leaden ice
#

Yeah this isn't going to be accurate because the bounds are not going to actually match the collider shapes unless they happen to be unrotated box colliders

forest ravine
#

But aren't I getting the "tightest" box to a room with this method?

leaden ice
#

the tightest axis aligned box

#

what do your rooms look like

forest ravine
leaden ice
#

collider.bounds is axis aligned

heady iris
#

I described how CheckBox works

leaden ice
#

CheckBox uses whatever you give it

heady iris
#

If your room's overall shape is not an axis-aligned box, then you will get an excessively sized box

#

consider a room that's on the XY diagonal

#

you'll wind up with a square-shaped bounds

#

even if the room is extremely narrow

forest ravine
#

Debugging with this I get:

    private void OnDrawGizmosSelected()
    {
        if (BoundsProvider == null) return;

        Gizmos.color = Color.green;
        var debugBounds = GetBounds();

        //Vector3 cubeLocalCenter = debugBounds.center - transform.position;
        //Vector3 cubeLocalSize = debugBounds.size;
        //Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);

        Gizmos.DrawWireCube(debugBounds.center, debugBounds.size);
    }
heady iris
#

I was about to suggest using Gizmos, so that's good

forest ravine
#

Do you know an equivalent gizmos debugging that rotates the bounds as Physics.CheckBox would do?

heady iris
#

Drawing a rotated box requires you to modify the gizmos matrix

leaden ice
#

CheckBox doesn't rotate anything it uses whatever rotation you give it
You would use Gizmos.matrix if you want to rotate the wire cube

heady iris
#

It's a bit annoying.

forest ravine
#

Doing the debugging after the generation, this is one the failed cases I found. I enabled the room manually, it did not spawn

#

With what you have told me rn the debugging is what is incorrect (I'm not yet rotating the box)

#

Bc that one is one of the few odd-degree exits of a room I have

heady iris
#

notice how the box is larger than it needs to be, because it's axis-aligned

#

If you rotate that box to match the room's rotation, it'll stick out pretty darn far

#

I'd suggest calculating the bounds in local space, so that you can ignore the room's rotation.

forest ravine
#

Sorry for the possible miscommunication but which thing is axis-aigned? My debugging or the physics call which takes a quaternion?

heady iris
#

That big box is axis-aligned.

#

Your code then rotates it to do the physics query.

forest ravine
#

That's just my debugging

heady iris
#

is that not what you're using to run the box query?

forest ravine
#

Yes

#

Yes, but that GetBounds()of mine, seems pretty local

forest ravine
somber nacelle
#

yes and it's getting the bounds from the collider which is an axis aligned box. so that big box you see is what you are using (just rotated) for the CheckBox call

forest ravine
#

Ok, I did a "dirty trick", when calculation my bounds I store the transformation, set it back to identity, calculate bounds and finally restory transformation

#

I don't like manipulaton transforms to obtain data instead of doing the math but it is what it is

spare island
#
        [Button]
        /// <summary>
        /// Creates a new tutorial note.
        /// </summary>
        public TutorialNote CreateNote(string message = "No message provided.")
        {
            var note = Instantiate(notePrefab, tutorialCanvasTransform);

            // Ghetto constructor
            var noteScript = note.GetComponent<TutorialNote>();
            noteScript.SetMessage(message);
            latestNote = noteScript;

            return noteScript;
        }

What is a way that I can implement a 3 second delay before instantiating this object without making it into a coroutine and still being able to return noteScript?

latent latch
#

general timer loop?

spare island
latent latch
#

Eh, well I think coroutine or member variable timer flags are probably the best two choices you got

#

You got invoke as well, but usually people suggest to just use coroutines

lean sail
leaden ice
spare island
#
        public async Task<TutorialNote> CreateNote(string message = "No message provided.")
        {
            await Task.Delay(NoteCreationDelay * 100); // Delay for 3 seconds

            var note = Instantiate(notePrefab, tutorialCanvasTransform);

            // Ghetto constructor
            var noteScript = note.GetComponent<TutorialNote>();
            noteScript.SetMessage(message);
            latestNote = noteScript;

            return noteScript;
        }
            Task<TutorialNote> createNoteTask = TutorialManager.Instance.CreateNote("Look around a bit. Press and hold W, A, S, or D to look around your office.");
            yield return new WaitUntil(() => createNoteTask.IsCompleted);
            var note = createNoteTask.Result;
leaden ice
#

right so... you used a coroutine and async

spare island
#

i forgot tasks exist

somber nacelle
#

why did you need to wait inside the method that instantiates it anyway? you're calling that method from within a coroutine. just wait inside that coroutine before you call the method . . .

spare island
somber nacelle
#

why? the caller has to wait anyway if you're delaying inside the call, no? because otherwise the return won't work

spare island
#

i like overthinking things

#

i was trying to avoid that boilerplate code

#

i realize i ended up making boilerplate code anyway

#

it gets really annoying when i need to start coroutines from other coroutines inside of something that isnt a monobehavior

cosmic rain
#

Async await can be less boilerplate code

somber nacelle
#

if you're doing it inside of a coroutine you don't actually need the StartCoroutine call, just yield return YourOtherCoroutine(); (assuming you want to yield until it has finished)

cosmic rain
#

Or more...
Depending on the use case

spare island
somber nacelle
#

it will wait for that new coroutine to complete before proceeding with the coroutine that started it

spare island
#

if not, how do i make it wait

somber nacelle
#

that's the whole point of the yield

spare island
#

just makin sure

somber nacelle
#

if you didn't want to wait, then you would have to use StartCoroutine otherwise it wouldn't have been started correctly

spare island
ivory pasture
#

tried to create new project on a new device on a 2019 lts version, got this error everytime i start it

leaden ice
ivory pasture
#

okay, thank you

latent latch
#

So I've been putting this off for a bit, but I'm not sure the best way to go about a tooltip problem I've been having. Seems silly, but I'm not exactly sure how to update the current object that is under my mouse cursor when using IPointerHandler in addition to IDragHandler. OnPointerEnter and OnPointerExit work fine, but if I were to drag an item that has a tooltip onto another slot in my inventory, the eventsystem will not call OnPointerEnter on this updated item slot.

#

OnEndDrag does not work since that would only call the previous slot's method and not the new current updated slot where the item had been dropped.

#

Seems like this would be a common problem if anyone has any suggestions from their implementation.

dusk apex
latent latch
#

So OnPointerEnter enables the tooltip, and OnPointerExit disables it. But the problem here is that OnPointerEnter does not call on the next slot when a drag event is being called.

#

So technically what's happening is when drag event is over, the OnPointerEnter will not be called on the new slot unless I move the pointer out and then back in.

dusk apex
#

Assuming it's either a Minecraft/Terraria hot bar or Diablo inventory system

latent latch
#

Yeah, exactly that. After you drop an item, the tooltip should renable because your cursor should still be over it.

dusk apex
# latent latch So OnPointerEnter enables the tooltip, and OnPointerExit disables it. But the pr...

I'm assuming this is the process:
Say for instance you've got four slots. When the mouse enters slot one, you'd show the tooltips and likely register a target etc. When dragging, you'd disable the tooltips for the current item and reference the held item (dragged). Moving over a different item should show that item's tooltips still, ideally. Releasing would swap items and update tooltips etc.

latent latch
#

Right, I think it may just be some execution ordering problem I'm having. I got a lot of the item slot logic on a different script as my tooltip, but both have the interface.

dusk apex
#

So is the problem that it's showing the tooltips for the previous item?

latent latch
#

Right, it's not updating to the new item

#

I disable all tooltips when dragging, so only when I drop the item should I see a new tooltip

dusk apex
#

Maybe log to see if order is an issue or if pointer enter thereafter simply isn't occurring.

#

If the second, just do a force update when items are swapped

latent latch
#

I think it may just be an execution ordering problem, such that my tooltip is calling the event first before the slot Pointer events swap the data*

dusk apex
#

If the first, maybe disable the entry script, swap items and re-enable.

dusk apex
high crow
#

Hello does anyone know how computers/calculators get from basic operators to roots/powers. I’m trying to write a math library in raw C++

spring creek
fervent furnace
#

you can just google it

pure scarab
#

tried to make a jump for my 2d player that can move around a sphere like planet, though for some reason it's treating transform.up like Vector2.up. the second image is a demonstration of what i'm talking about, for example it the player is on the "side" of the planet, from their perspective the player jumps left

#

i am using MoveRotation to rotate the player towards the planet

cosmic rain
pure scarab
#

the player's

cosmic rain
#

If it's truly rotated, the direction should change.

#

Share the code of where you draw that ray

#

Wait, was it drawn in paint or something?😅

crude mortar
#

yes haha

#

but drawing a ray would be a good start to figuring out whats going on

pure scarab
#

the ray IS being drawn up... hmm...

#

just did a Debug.DrawRay(transform.position, transform.up, Color.red);

cosmic rain
# pure scarab yes.

Yep. Then the issue must be somewhere else. Maybe share details on what exactly goes wrong first.

pure scarab
cosmic rain
#

Start from describing the issue. Maybe demonstrating with a video?

mellow sigil
#

This line causes it:

rb.velocity = new Vector2(transform.right.x * horizontalSmooth, rb.velocity.y);
#

velocity is in world coordinates so that won't work for movement on anything other than a normal horizontal plane

vague tundra
#

Any math kings out there?
What kind of function do you think might fit the following desired graph? A combinaton function is fine

lean sail
vague tundra
#

Welp, you almost answered like a good bloke! Thanks:D I'll look into cubics - that sounds excellent

lean sail
#

there are curve fitting equations, and calculators online

vague tundra
#

All good, you helped plenty with the cubic suggestion. I couldn't remember what graph I was after, but that's it

And don't worry, I am the calculator. I'll show you the result shortly

gloomy parrot
#

hi guys i'm trying to translate a unity game into another language but i've never worked with unity so i don't know how to do it properly. i've tried editing it's source files with a hex editor and replacing the original text string with mine. it worked to a certain extent: seems like only ASCII strings are allowed and only of a certain length (it's determined by the 4 bytes preceding it but it's still limited because there is other data after it). what is this format anyway and are there any tools for editing it?

vague tundra
#

Ahh, perfection. Thanks @lean sail

#

As for its usage, this is what I enviosoned my distance function would be for mapping the animation of two cards clashing together "Battling" in my card game

lean sail
gloomy parrot
#

oh why is it

lean sail
vague tundra
#

Thank you for the suggestion, but i prefer the neatness of modelling movement using functions

lean sail
dawn nebula
#

And then retrieve the value with animationCurve.Evaluate

pure scarab
mellow sigil
#

The easy solution is to use AddForce for movement instead of setting the velocity directly

#

The other way is to first convert the velocity to local coordinates, apply movement, and convert back to world coordinates

pure scarab
#

but wouldn't AddForce make the movement really floaty?

mellow sigil
#

No?

vague tundra
#

Oh cool, thanks @dawn nebula , I didn't know that existed(:

edgy sierra
#

has anyone here integrated unity with kafka or with a different message broker?

mellow mural
#

my code keeps throwing a UnityException: transform child out of bounds error and i dont know why

    public Image TopAbility;
    public Transform Topchild;
    public Image LeftAbility;
    public Transform Leftchild;
    public Image RightAbility;
    public Transform Rightchild;
    public Image BottomAbility;
    public Transform Bottomchild;
 void Update()
    {   
        if (TopAbility.transform.childCount == 1)
        {
            Topchild = TopAbility.transform.GetChild(1);
        }
        if (LeftAbility.transform.childCount == 1)
        {
            Leftchild = LeftAbility.transform.GetChild(1);
        }
        if (RightAbility.transform.childCount == 1)
        {
            Rightchild = RightAbility.transform.GetChild(1);
        }
        if (BottomAbility.transform.childCount == 1)
        {
            Bottomchild = BottomAbility.transform.GetChild(1);
        }
        

        if (Player.transform.rotation.z == 0 && BottomAbility.transform.childCount == 1)
        {
            SelectedAbility = Bottomchild.name;
        }
        
        if (Player.transform.rotation.z == 90 && RightAbility.transform.childCount == 1)
        {
            SelectedAbility = Rightchild.name;
        }
       
        if (Player.transform.rotation.z == -90 && LeftAbility.transform.childCount == 1)
        {
            SelectedAbility = Leftchild.name;
        }
        
        if ((Player.transform.rotation.z == 180 | Player.transform.rotation.z == -180) && TopAbility.transform.childCount == 1)
        {
            SelectedAbility = Topchild.name;
        }
}```
mellow sigil
#

Indexing starts from 0. If the child count is 1 then only GetChild(0) is in bounds

leaden ice
#

There's a LOT of problems with this code beyond that too 😕

mellow sigil
#

was just about to say

knotty sun
mellow mural
knotty sun
#

also you should read about floating point inaccuracies

mellow mural
knotty sun
#

true, but not the one you obviously think it is

mellow mural
#

is it not just the rotaion of the player?

half imp
#

is there a way to add some sort of wiggle or sway to a a rigged object?

knotty sun
#

yes, expressed as a Quaternion. For some reason you seem to think that by accessing the .z value of a Quaternion it will magically be transformed into an Euler value

tacit dawn
#

Hi,
I'm Using Unity 2022.3.11f1 and Rider as the code editor
I often get "errors" from Reolading Domain. When I say error, I mean that the Domain takes 15min + to reload and that I have to quit Unity.

#

I don't really know what settings I need to change to fix the problem, it's never happened to me before.

heady iris
#

close the editor, delete the folder named "Library" in the root of your project, and then reopen the project

#

It will take a while, and the editor will forget a few things (like which scene you had open)

#

This often fixes those weird freezes

lilac scaffold
#

I have 2 box coliders on my mesh one for the top button one for the bottom button how would i in code get individual on mouse downs for them?

dusky lake
dusky lake
# lilac scaffold I have 2 box coliders on my mesh one for the top button one for the bottom butto...
public class ParentScript : MonoBehaviour
{
    public void PressedButton(ButtonType type)
    {
        switch (type)
        {
            case ButtonType.Bottom:
                // Pressed bottom
                break;
            case ButtonType.Top:
                // Pressed top
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
        }
    }
}

public enum ButtonType
{
    Bottom,
    Top
}

public class PressableButton : MonoBehaviour
{
    public ButtonType m_ButtonType;
    public ParentScript m_Parent;
    private void OnMouseDown()
    {
        m_Parent.PressedButton(m_ButtonType);
    }
}
lilac scaffold
dusky lake
#

And then just reference the parent script in both pressable buttons

lilac scaffold
dusky lake
#

yeah your parent can have the mesh stuff

#

no reason you cant put the colliders on sub objects

lilac scaffold
#

wait so the TopButton and bottom are emptys with the box colliders?

dusky lake
#

Yep

#

Box collider + Pressable Button script

lilac scaffold
#

okay thank u sm

dusky lake
#

if you just have 2 box colliders on the game object it would be kinda hard to get which one was just hit because you would somehow have to infer the information if it was top or bottom and you dont have enough data for it, cause the colliders have no identifiers 😄

dusky lake
#

Hmm, so whenever I set timescale to 0 to pause my game I get this error in console: https://img.sidia.net/ZEyI5/sEfeSeDE09.png/raw

Is setting timescale to 0 generally bad practice? I thought about just going ahead and "manually" pause all path finding of mobs and player controls on pause but timescale to 0 would just be so much easier 😄

heady iris
#

Is there an easy way to search for "dangling" event subscribers? I want to find any components that are failing to unsubscribe before being destroyed

dusky lake
#

what kind of events are you using?

heady iris
#

C# events.

#

I guess I want to find every event field and search their subscribers for any methods on destroyed unity objects

dusky lake
#

Show me a line of code where you create that event please 😄

heady iris
#

feels like something I'd need a debugger for

#
        Application.quitting += HandleQuit;
#

e.g.

#

well, this is subscribing, not declaring the event, but you get the idea

lean sail
heady iris
#

so I'd want to catch anything that subscribes to this static event, then fails to unsubscribe after I quit the game

dusky lake
#

this might be what you want

heady iris
#

Yeah, I think I can get the information I need via reflection...

#

The hard part will be finding all of the relevant events...

#

So far I've tested this by randomly changing scenes and pushing buttons :p

somber tapir
dusky lake
somber tapir
heady iris
#

I could just do this statically, yeah

#

the most common problem will be "i forgor"

#

each += should be balanced with a -=

hexed pecan
#

Sometimes I -= before += just to be sure that there will be no duplicate subscriptions

heady iris
#

I'm less concerned about duplicate subscriptions on a single object

#

more about subscriptions for dead objects

deft timber
rigid island
#

Still trying to revamp this old project
Any new ideas on how I can approach a "Light meter" ? like in older Splinter Cell

#

sorry GIF adds weird artifacts to color, its supposed to be pitch black

#

it somehow works getting the player in the texture but the reading "light level" isn't correct (probably because I have no idea what I'm doing here)

#

I think this approach is reasonable for a light meter that would work like this, but not sure how these numbers are off.
so basically if you're in the light then the RT would read more color

hexed pecan
rigid island
#

I think this is where I messed up

for (int i = 0; i < colors.Length; i++)
        {
            lightLevel += (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b);
        }
        lightLevel -= 259330;
        lightLevel /= colors.Length;
        Light = Mathf.RoundToInt(lightLevel);```
#

its been almost a year and I have no clue why I used those magic numbers 😦

#

I never documented it like a dolt

#

also tried to play around with different Color formats and I think thats where things got worse lol

hexed pecan
#

Yeah idk about the -= 259330
I suppose that multiplying the rgb values with those magic numbers is because we humans perceive R, G and B with different weights so that makes sense

heady iris
rigid island
#

yeah except I have no idea where to go from there 😦

heady iris
#

I believe those are how sensitive the eye is to the three main colors

hexed pecan
#

Yeah its a cool technique, I plan on doing something similiar but maybe with ComputeShaders

heady iris
#

I just convert the color to HSV and then use the value

#

Dunno about the big constant you're subtracting.

#

Is your game using HDR rendering?

rigid island
#

All i needed was a comment on it and I never did that xD

rigid island
heady iris
#

the color values would go way out of the 0-1 range

#

although, this is the final rendered result

#

so it'd probably be tonemapped anyway

#

My game has (allegedly) realistic vision. It samples the HDR color values, then takes the log to get an exposure value

#

it compares that to the enemy's current eye exposure to decide how noticeable that light is

heady iris
stark ginkgo
#

Would you guys recommend loading UI as a prefab or create a UI scene which is additively loaded? There's also the option DontDestroyOnLoad. Working on a 2d top down game and the player moves between scenes quite often.

rigid island
heady iris
#

I'm currently using a separate scene for my "main menu" UI. It's nice, I guess, but it's not a huge improvement over just loading in a prefab

stark ginkgo
#

Haha, any one in particular you reccomend?

heady iris
#

and it makes communicating with the menu annoying

#

(e.g. to indicate that it wants to close)

#

I'd go with DontDestroyOnLoad

rigid island
stark ginkgo
stark ginkgo
heady iris
rigid island
#

ah yeah just noticed..

heady iris
#

that might just be the number of pixels in their texture

#

I would also suggest weighting the pixels differently

rigid island
#

must been stolen from someone else who stole it XD

heady iris
#

If you see 100 bright pixels and 900 dark pixels, that's still very visible

rigid island
#

i would not add that unless I knew for a fact what i was doing

heady iris
#

You could square the values and then square root the sum

#

Or do something logarithm-based

rigid island
#

soo much math 🥵

heady iris
#

You don't want to just take the max, since that would make a single bright pixel mega-visible

rigid island
#

for some reason the values dont' change at all now..oof..

hexed pecan
#

I would debug the value with GUI.Label in the game screen. Inspector and console views may not always update I think

rigid island
#

Will try that ty

hexed pecan
#

(Or GUILayout.Label)

heady iris
#

console log values will absolutely be up to date

#

I could believe that the inspector could fail to repaint

#

mostly because I've seen code that forcibly repaints it

rigid island
#

I did both still stuck at 0


        for (int i = 0; i < colors.Length; i++)
        {
            lightLevel += (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b);
        }
        //lightLevel -= 259330;
        //LightLevel = LightLevel / colors.Length;
        //Light = Mathf.RoundToInt(LightLevel);
        Debug.Log("Light: " + lightLevel);```
heady iris
#

verify that the colors array isn't just all-zeroes

#

or empty

hexed pecan
heady iris
#

It does randomly decide to not scroll

#

OnGUI is great for rapidly-changing stuff

#

you can even spend hours and hours building an elaborate debugger UI instead of actually making your game

heady iris
#

today I am working on tutorial popup messages

#

instead of making the game

#

but hey, games need those

hexed pecan
#

It does pay well in the end though. I recently split all my debug into modules (AI, Movement, Input...) that I can toggle for each character

rigid island
#

could've sworn it used to work somewhat..

heady iris
#

sanity check by making lightLevel start at 10 or something

hexed pecan
#

Navarone

#

I think i figured it out

rigid island
hexed pecan
#

Sorry lol

rigid island
#

damm i got hype for a sec XD

rigid island
#

the preview says stuff is happening in render texture I just don't know why no numbers move, it used to work iirc

heady iris
#

I presume the render texture is read-write enabled

#

actually, that isn't even a thing for a render texture

rigid island
#

maybe the color format or something ? i dont know what any of them mean so i haven't touched it

heady iris
#

have you logged an individual color value yet?

#

also make sure you're using the right render texture, I guess

rigid island
rigid island
hexed pecan
heady iris
#

oh yeah, that's a little interesting...

rigid island
#

still wasn't working tho

#

i tried making default one

#

lmao I did this```cs

for (int i = 0; i < colors.Length; i++)
{
lightLevel += (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b);

        Debug.Log("RGB_" + colors[i].r + colors[i].g + colors[i].b);
    }
and Unity imploded
hexed pecan
#

Thousands of logs at once will be super slow yeah

rigid island
#

I guess too many logs lol

#

yea wops

heady iris
#

i left a log statement in bursted code that was running tens of thousands of times per frame

#

owie

hexed pecan
# rigid island

Try another color format. Im not sure if that is even a floating point format (even after checking docs)

heady iris
#

what is colors, actually?

#

Color[] ?

rigid island
#

Color32

hexed pecan
#

Colors32

heady iris
#

ah, okay

rigid island
hexed pecan
#

Idk, I would print the min, max and average values of the whole image at first

rigid island
#

every forum post on this leads me to dead ends

hexed pecan
rigid island
#

is pixelvalue colors ?

hexed pecan
#

I guess it would be this part (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b)

#

Or even just (colors[i].r + colors[i].g + colors[i].b) / 3

#

For simplicity

#

Just to get an idea of the values you are working with

#

You could also do that with the R/G/B separately

rigid island
hexed pecan
#

The last line is off

#

You gotta divide avg by the total color count

rigid island
#

oh wops

hexed pecan
#

Maths!

rigid island
#

this also says 0

#

        float min = 0f;
        float max = 0f;
        float avg = 0f;

        for (int i = 0; i < colors.Length; i++)
        {
            lightLevel += (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b);

            min = Mathf.Min(min, lightLevel);
            max = Mathf.Max(max, lightLevel);
            avg += lightLevel;
        }
        avg /= 3;
        Debug.Log("AVG: " + avg);```
hexed pecan
#

avg /= colors.Length;

#

Though yeah if it prints 0 then something is off anyway

#

Is the min and max also 0?

#

I remember having massive headaches with Blit so I just learned to use compute shaders lol

rigid island
#

yeah its all still 0..strange.. even if it was half broken it was somewhat working before now its full on broken

#

I might need to try this again later with a fresher mind, been at it for 4 hours already

#

thought this would be easier/smart than Raycasts from lights but its turning out not so easy lol

dense void
#

hey I'm having difficulty with random planet generation, I've gotten it to generate randomly, but im having trouble programming it to generate in certain directions. I've managed to program it so I can manually set constraints to min X max X min Y and MaxY generstion but it continues to attempt to generate whereever it pleases causing it to just crowd along the borders of the constraints. I don't know how to fix this exactly, additionally I want it to delete old planets as the player ship moves along and generate new ones in front of the player but everything I try just isn't working.

hard viper
#

one issue at a time

#

first is to check that the randomly generated position is correct
second is to check if the planet is spawned at the position that was randomly selected

austere cape
#

hello guys I am working on custom editor and I face this problem.
When I debug those values on the picture they are changing but the slider react to the changment of the values soooo late

leaden ice
#

it's not really clear to me what you're trying to do with that

austere cape
heady iris
#

you only log when you scroll the mouse wheel

#

oh, that is not the issue

#

so the problem is that, when you scroll the mouse, minVal and maxVal are supposed to change

austere cape
heady iris
#

but then the slider doesn't respond immediately?

austere cape
#

yes exactlyy

leaden ice
leaden ice
#

ONGUI only responds to IMGUI UI events

#

it's not something that runs every frame

heady iris
#

yeah

#

OnGUI in game gets run every frame because the game redraws every frame (well, duh)

#

The editor only redraws when it needs to

#

I forgot entirely about that

leaden ice
#

so this is a combination of your Lerp usage + ONGUI

austere cape
#

so I should force on gui to redraw it

#

but the function is beign called and the debug is working why it dosn't redraw it

leaden ice
#

You could use EditorCoroutines for this

leaden ice
austere cape
heady iris
#

yes, beacuse the slider only updates when unity decides it needs to redraw the UI

#

actually -- can you share the entire script?

#

From the chunk you showed, it seems like it should redraw the slider right after updating those vlaues

hard viper
#

can I get confirmation on whether get contacts retrieves contacts as of last physics update, or just generates new contacts at time it is called?

stark ginkgo
#

Using the new input system, currently I just poll the keys to check if they're pressed, somewhat mimicking the old input system. Is there any reason I shouldn't do this? Anyone do it differently?
Example:

        if (InputContainer.Instance.inputController.Player.Sheath.triggered)
            stateController.TransitionToState("unSheathState");
leaden ice
#

most people go event-based though

stark ginkgo
#

Is there any reason to go event-based over polling? Any performance differences?

leaden ice
#

it's not a performance thing. it's about how you want to organize your code.

austere cape
# heady iris actually -- can you share the entire script?
void OnGUI()
{
  Vector2 s = maxSize;
  s.y = 1;
 d.begin = d.end;
 d.end = DateTime.UtcNow.Millisecond;
 scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(position.width), GUILayout.Height(position.height));
 Horizontal(() =>
 {
   EditorGUILayout.Separator();
   GUILayout.Box(new Texture2D(0, 0), GUILayout.Height(54), GUILayout.Width(position.width / 2f - 10f));
   GUILayout.Box(new Texture2D(0, 0), GUILayout.Height(54), GUILayout.Width(position.width / 2f - 10f));
   EditorGUILayout.Separator();
 });
   EditorGUILayout.Separator();
 Vertical(() =>
 {
   FlexHorizontal(() => { GUILayout.Label(currentMouseValue.ToString()); });
   Horizontal(() =>
   {
     GUILayout.Label(startValue.ToString());
     GUILayout.Box(new Texture2D(0, 0), GUILayout.Height(54), GUILayout.Width(position.width*0.8f));
     var rect =GUILayoutUtility.GetLastRect();
     var currentEvent = Event.current;
     Vector2 mousePosition = currentEvent.mousePosition;
     if (rect.Contains(mousePosition))
     {
       float x =((mousePosition.x - rect.xMin)/rect.width);
       int a = endValue - startValue;
       currentMouseValue = (int)(x * a) + startValue;
       if(currentEvent.type == EventType.ScrollWheel)
         {
           delta = currentEvent.delta.y;
                        if (delta < 0)
                        {
                            minVal = Mathf.Lerp(minVal, currentMouseValue, 0.01f);
                            maxVal = Mathf.Lerp(maxVal, currentMouseValue, 0.01f);
                            Debug.Log(minVal);}
                        else
                        {}
                    }
                }
                GUILayout.Label(endValue.ToString());
            });
            EditorGUILayout.Separator();

            EditorGUILayout.MinMaxSlider(ref minVal, ref maxVal, minLimit, maxLimit);
            startValue = (int)minVal;
            endValue = (int)maxVal;
        });
        GUILayout.EndScrollView();
    }
heady iris
#

please share code on a paste site !code

tawny elkBOT
stark ginkgo
frozen mesa
#

hi can anybody help me with Nav Mesh Components i have i set up on my enemy. so every time when i hit play the enemy just fall down or fly up or whatever

rigid island
#

also show your navmesh bake

frozen mesa
#

i dont have rigibody

#

i have baked everything

rigid island
#

show it

#

and show vid of issue

frozen mesa
#

how do you mean show the bake

rigid island
#

also this is the wrong channel prob

frozen mesa
#

sorry

#

so should i go to the code begginer right?

rigid island
frozen mesa
#

ok so can we go to the code begginer thanks.

quaint crypt
#

hello, i need to tackle serialization in my game, and saving game state. as far as i can tell serializing as json is a pretty common and simple solution, and when needed i can transition to ugs + cloudsave and put the save files there. (is this a good approach?) is there a unity package that is recommended over using unitys own jsonutility?

heady iris
#

You can define custom (de)serialization processes for various types.

#

I use a system where scriptable objects get serialized as an ID value, for example

#

JsonUtility doesn't handle dictionaries, iirc

#

and is generally pretty limited

quaint crypt
#

@heady iris thanks a lot!

heady iris
#

I don't serialize too much "game state" right now -- it's mostly stuff like a list of save points, the player's stats, and so forth

#

It's a soulslike, so you don't just save in completely arbitrary places

#

If you're making a save system for an RTS, you'll need to remember a lot more information!

quaint crypt
#

@heady iris yeap definitely. now i just need to figure out how to install it 🙂

heady iris
#

What version of unity are you using?

#

If it's new enough, you can just install the package by name in the package manager

quaint crypt
heady iris
#

Okay -- go to Window > Packager Manager

#

click the "+" icon and pick "add by name"

#

then punch in com.unity.nuget.newtonsoft-json

quaint crypt
#

@heady iris oh wow that was easy, didn't know i could install it like that. thank you so much!

heady iris
#

np!

#

Some packages are hidden and don't show up in the unity registry

rigid island
rigid island
#

The api uses a Dictionary<string,object>

#

It’s just funny because Json.Net does not like Vector3

#

Just remember to make a custom struct lol