#archived-code-general
1 messages · Page 219 of 1
Multiplayer coding help
seems like it freezes at the triangulation
Break with a debugger.
but the unity editor completely freezes, it doen't respond to input, not anything
Why would unity editor matter?
The debugger is in your ide.
you mean the profiler right?
Debugger is not profiler….
or this??
It is a function provided by your ide
No. Do you know what an ide is?
you mean the debugger in visual studio?
Yes
Yes.
I suggest going through this guide. Specifically the debugger section.
https://unity.huh.how/debugging
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
how are you switching your sprite from left to right and right to left? show code
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
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
Awesome thank you! Works like a charm
where do you set LS ?
why? why not just set it before you set the localScale to 0,0,0 ?
Your IDE looks underhighlighted, if you're not getting autocomplete and code completion you need to configure it !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
@finite swift 👆
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?
Is GoToMainStage supposed to take in any arguments?
No, and it only errors sometimes
Show me the function
All the code leading up to it?
No, just the function
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();
}```
I don't have access to that? It's a Unity internal one
Which leads me to not understanding why it's giving me that error
can you screenshot the error and post your complete code to a paste site
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?
The whole massive console error?
Well.. might as well I guess
More is better than less
And you've cut out the most important bit
Also the 3 scripts involved, the entire thing?
Cut out? That's the entire thing?
There isn't more?
my bad
So do I paste the entire script of all 3 scripts?
PrefabOptions script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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
certainly nothing you can do about it, there's nothing wrong with your code
Okay I was worried maybe I was doing something to break the editor
Which I mean, I might still be doing somewhere
you could try to put a call to GetMainStage before the GoTo and see what it returns
Don't fully know what you mean, call it in the other script? I'll see
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
SceneManager in UnityEngine namespace? if so, there isn't a MainStage in it
UnityEditor
Yeh that'd make more sense 😅 sorry
mainStage isn't null
It went through and gave an error
then it is a bug

so wrap it in try/catch to mitigate it
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
no, MainStage should never throw an exception unless something very silly has happened in the Unity C++ code
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
maybe raise a bug report
Okay, this is what I'm working on for context btw
It's been really difficult getting the hang of Unity editor stuff, especially UI stuff but hopefully now I can move forward
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
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();
}
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
tell your devs to read this page, especially the section Calling Unity scripts functions from JavaScript
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
Oh I just double checked and it actually fails for 2 frames and then the 3rd frame goes through
sounds like an unexpected Thread race condition
Yeh maybe.
you could drop the code into an EditorCoroutine with a while loop
I just do this currently
I told them but they are keep telling it's not giving data pff.
I didn't add it too code. That's why?
there is nothing in your emscripten that would give them data, wtf are they expecting?
that is not the way the system works
They are saying it's not redicting
How can i test it? From console to proof them it's working
does not surprise me, that doesn't look like a valid URL to me
Console.Log it
no, console.log("in trackEventBack");
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
so our bit is working, the rest is down to your app devs
😦
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
Share the actual error...
wdym
that is the error
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
Yes.
Use a regular for loop. Modify it and assign the modified struct back to the array
Or make it a class.
agh
thats annoying
ok
How COULD anyone know without seeing code? 😄
See the #854851968446365696 for what to include in questions.
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
{
...
}
}```
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
firstly I ask, then i can share code, avoiding spam
you can use pastebin
Ah, the rules say https://dontasktoask.com/
So don't do that. Just post code.
how to embed code?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
```cs
code here
```
I don't have this character in my keyboard, i mush copy from web every time?
Italian keyboard
They tried that as well. It was doing the same thing. They instantiate the pause menu in the player start. So I don't know if the DontDestroyOnLoad is needed?
are you on mobile?
no pc
Paste sites are better. However, on my keyboard that key is to the left of the one, same key as the tilde ~
yeah, it’s a very weird charcacter
the pipe
set timescale to 0 last, to avoid anything else getting interrupted
Then just use a paste site 🤷♂️
Oh, or you can copy paste it from above!
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
cannot paste too much characters
Yeah, embedding is for like 5 lines of code
If more, do a paste site
that’s the best I can do for you, fam
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.
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.
the placement in bottom left?
yes
while you explain your problem, one pattern that is very useful is:
[field: SerializeField] public float myFloat { get; private set;}
Check if the index of the item is odd, if yes, add an Y offset
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
@ember ridge Does this need to be done from code though? You could just place the slots there by hand
should I wrap the whole list of items in a horizontal layout? since I need to position them in the bottom of the corner
nah, I want to place them by hand, but couldn't make it work
Horizontal layout could work 🤔 I don't really use Unity UI, maybe someone else knows
Or you can try in #📲┃ui-ux if not
my problem is that with this script, my camera move in the Y axis while pushing bottom screen with my mouse, but the intended movement is only backward movement in z.
the camera move in backward while pushing bottom screen, but I can't figure out why it implement every second on Y axis while moving.
it sums up
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
ok, I will ask there then, thank you.
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
clean code, I'll give a try!
one more question, what does B stand for in the context?
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)
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.
thank you
greetings, has anyone here used unity3D with kafka?
anyone have a clue?
Can someone help me. I have posted my query here #1171723008424038402
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";
}```
integer division
divide by 1000f instead
int divided by int returns int
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
yes, just because you display an int with decimal places doesn't make the actual value have them
That happens after the division too
so simply making it into 1000f fixes it then?
yes because any operation involving an int and a float will return a float
How should i make a custom editor component which would clone my object into a grid?
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! 
Sometimes reimporting files fixes bugs related to not finding something. It's worth a try.
I'll try it!
you really don't want to have Unity projects in OneDrive folders it can cause strange behaviour
If you are looking for cloud hosting look into github/gitlab/etc
Having your project on onedrive or something like that is just asking for trouble
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
Mind is kind of rotting learning state machines
Watched three videos and still kind of in the same place
Any tips?
Trying to use vscode with Unity, just fresh installed but dont have the documentation in vscode and i get this error, any fixes?
I don't use OneDrive for cloud hosting, pretty sure it was just enabled and I never bothered to disable it.
!vscode
!vscode
double kill
🦥
restart your computer if you have actually followed all of those steps correctly
is there anything else i can do
have you followed all of the instructions in that guide and also restarted your computer?
i didnt install vs2022 with unity would that affect it
no
yes i have
then consider switching to a real IDE like vs2022 instead of a fancy text editor
bro? XD
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
why cant ppl just say they dont know instead of being angry
i then check the distance between the bullet and hit object for determining when to destroy the bullet
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
but this method seems to be a little inconsistent
Who is angry?
ive used vs2022 before its just wanted to try using vscode and seen ppl use it
Ok, well you're gonna need to help us help you
Can't say much without knowing what you've done
vs code is just a fancy text editor with plugins to approximate the features of a real IDE. you'll have a much better development experience using a proper IDE like visual studio or rider
Show the package manager
I was typing it then this person says to just switch
tysm
Yeah, well, for the reasons boxfriend gave and I gave, switching may be the best choice. Vs IS better...
I'm willing to help, just show the package manager as I asked
you're gonna have to debug why dotnet is missing.
show us all the plugins in VScode
the issue is that they don't have the .net sdk. which means they either neglected to actually follow the instructions in the configuration guide, or they neglected to restart their computer afterwards since the extension should install the sdk as well
Remove the Visual Studio Code Editor package. Both use the Visual Studio Editor package
Yeah, I figured I'd just start at the beginning haha
done, still there
preferences -> external tools
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?
hmm it might need a proper restart or something if the whole dotnet is somehow missing
Yes I have
And I just tried to regenerate everything to see if thatd help
Ill try restarting again
Ok, well everything else is correct it looks like 🤷♂️
yea if its still an issue install .net sdk manually or sum
yea im trying that now
then ill restart
thx
thx bro it works now 👍🏻
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
the traditional UGUI way would be with 81 panels inside a GridLayoutGroup, yes
I'd stick with that unless there's a compelling reason not to, as it will be the simplest to implement
oh, GridLayoutGroup.. I'll look that one up, thanks!
81 panels don't sound like a huge issue.
GridLayoutGroup works pretty well for preprocessing icon positions and scales. If you want to boost performance, disable the GridLayoutGroup after using it. Using multiple canvases also might boost the performance (because after modifying one element on Canvas all other elements also need to be redrawn).
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..
i mean how else could u do it
what's sort of the limit of spriterenderers you can throw into a project before it really goes wrong?
i think ull be fine
my old laptap can handle 10k without problem
oh wait
Moved the project out of OneDrive and tried re-importing everything, still have those two errors there. I'm gonna research this a little bit more and let you know if I end up fixing it. I'm also gonna check if I have any illegal characters in my file names as one of my folders in OneDrive had that happen to it.
i had to make 81 text objects too...
i think ull realise when u get on bigger projects its rly not that much haha
just make one object properly, and duplicate it when you sure it's fine
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
instantiate is costly btw
ill put it in a loading screen yeah
emphasis on "should"
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.
I had to manually install the SDK myself for some reason.
Technically you could create some system that works similarly to the terrain system or tilemap system, but I don't think it's worth the effort. 81 objects are not that much.
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
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)
explain the problem you're trying to solve
not "how to use compute shaders to do X", but "how to do X"
i'd definitely try it some other time, but yeah i'd rather just make my inventory be happy and move on to the next thing
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.
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?
Yeah you can do a Comparer<RaycastHit2D>.Create(your lambda here), and cache it somewhere
uh... what?
his guys is there a way to save addiitvely loaded scenes in not at runtime in unity
huh. interesting
Yeah, drag the scene into the hierarchy
Edit: oh, misread
so Comparer has a .Create constructor, that makes a comparer with a lambda?
I am not sure what you're asking actually
no worries but yeah its in the hierarchy but git won't save that
like i just opened it additively but when i go to push git doesn't save VideoCont scene as additively loaded
Git won't save the scene when you make changes when it's loaded additively?
Pretty much yep.
There's also the Comparer<T>.Default property which, if I remember well, tries to see if the type implements IComparable<T>, and automatically creates a comparer for you
wow, that's slick, SPR. ty. I wish I could do it without caching anything, but this is ok too.
anyone have a basic camera controll script that mimicks the scene camera behavior (wsadeq and shift?)
I havent seen that issue specifically, maybe it's taking some time to appear on git? I remember some stuff like me changing SO data did not appear instantly
I now have
raycastResults.Sort(0, totalHits, sorter);```
That is pretty standard. Just look up rts movement and make shift change the speed
oh hmm but i checked the status and commits wasn't even staged
use imagination. imagine a world where the indentation looks good
Just make sure to create the comparer once (store it into a static class for example), not sure how expensive that is
what about UI Documents? 🤔
It being committed isnt really relevant, I just meant it might take some time to be recognized as changed. Try changing something again, check your file explorer and see the last modified date
I changed it now to private static Comparer<RaycastHit2D> raycastHitSorter =
ok yeah ill try and see
What about them?
Like use them instead of an additive scene?
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
i checked docuemntation online I think I found an open source script that saves additively loaded scenes
for anyone that may need it as well
Additively loading several scenes at once in the editor isn't something that affects the built game
and it's not saved
but yeah, I can imagine you could write a script to remember that
No, I've just had a glance on a screenshot. My comment doesn't have anything to do with their issue. Guess it's quite hard to organize the Inspector without UI Documents.
Ah ok.
yes probably so and that would answer why my windows build kept being horrible the entire time
Does any one know why WaitUntil doesn't work in a static coroutine?
i don't know what a static coroutine would be
a coroutine runs on a specific MonoBehaviour
a static IEnumerator
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);
}
and how do you start the coroutine?
using the StartCoroutine method
What is the WaitUntil supposed to even do. It would return immediately
and which object is this running on?
I imagine you're destroying the object that is starting this coroutine, since this is related to scenes?
It won't?
no, the scene load happens at the end of the frame
scene load takes some time, if there's no wait until, I'll get some bugs
i presume this is the cause
Ah yeah, I only read that line 🤦♂️
Getting the scene name alone would be immediate
well, it happens on the next frame. close enough!
anyway, tyvm @simple egret. The clean code now makes me happy. 
No, it did work when this coroutine wasn't static
I've changed some methods to static when refactoring my code
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!)
But static won't? Why?
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?
ok, let me test it out quickly
yes, I'm asking why, as you've previously mentioned it
this is the object the method is running on
I see
a static method isn't associated with a specific instance, so there is no this
yes, I understood what you mean now, thanks
anyway, I don't call this there
yeah, that'd be a compile error
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
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
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..
wait until () => { Debug.Log(SceneManager.GetActiveScene().name); return SceneManager.GetActiveScene().name == sceneName; }
that'll log the name of the active scene each time it checks
that would be too early
yes.
since the scene will load one frame after you call the LoadScene method
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
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...
It will work if you load additively, or called DontDestroyOnLoad() on this object
well, you might have changed more than one thing at a time
git status | wc -l
53
😬
ask me how I know about that
Exactly! Before it was a non-static method with an embed coroutine. A coroutine cannot be called within a static method, so I've changed it from method to a coroutine...
that's why...
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
so do you have any suggestions then?
do I change it back to a non-static
isn't it the best variant here?
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
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);
}
}
yes, because this is an instance method on a MonoBehaviour
you haven't shown how you're doing it now. show us that.
In an another class.
I've just called the method before
now I'm gonna do this again I guess?
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.
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
LevelManager.instance
Singleton. High chance this has a DDOL call in Awake
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.
so as SPR2 has previously mentioned, the class where the coroutine was called wasn't destroyed, so the waituntil could execute
yes
that's the problem
okay, so your old code started a coroutine on the LevelManager instance
So by starting a coroutine in another class, we make sure it won't disappear
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.
yeah, it's irrelevant
the script is destroyed once a scene is changed
LevelManager.instance.StartCoroutine(...) will start a coroutine on the level manager instance
exactly
and it isn't destroyed
so the stuff after WaitUntil is successfully called
then just do that, and it'll work fine
sure, just wanted to make it static
That is unrelated.
I don't think you understand the significance of this.
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...
No, I do understand this.
is 1E-5f ok syntax for a float? want to make sure I don't summon some eldrich binary demon
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());
}
oooh, we teaching the man about static
You got around this by changing your code to look more like this
public static IEnumerator Foo() {
return Bar();
}
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
Wait till they hear how their local function can access variables outside of it lmao
This means that someone else has to start the coroutine.
And that someone else, in your case, was an object that got destroyed during the scene load
An easy explanation is that the class where a coroutine was started simple destroyed, that also breaked the coroutine.
Right.
You made LoadSceneAndPlay return an IEnumerator, rather than starting a coroutine
I've actually said this some time ago already 😅
example:
private static pi = 3.14159f;
public float radius;
public Circle(float radius) {this.radius = radius;}
}```
then why did you say this?
I was explaining how you could do LevelManager.instance.StartCoroutine to run a coroutine on the level manager object.
I've said that I wanted it to be static. As you see, it's not possible with current circumstances. That's a pity
Circle.pi is owned by the definition of a Circle, but radius is owned by individual instances. individual circles have their own individual radii.
LevelManager.instance.StartCoroutine(LevelManager.instance.LoadSceneAndPlay(...)), for example
wanted what to be static?
you can't run a coroutine static. it needs to run on an instance
Are you trying to get rid of the LevelManager instance entirely?
yes, I have understood it before 😅 but your explanations were really good
yes, I was trying to
Ah. I see.
a method
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
I have got rid of it. Almost. But the coroutine...
yeah.
There will need to be an object somewhere to run the coroutine on, yeah.
it's ok so, LevelManager is a ddol singleton so I'll just let that method be non-static
it's just annoying that not everything is static..
thank y'all for your help 😄
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?
I'm not really sure I'm understanding the distinction between GameObject and Transform here. Every GameObject has a Transform.
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?
Anyone have any idea why my shader would cause my object to be rendered this way?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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.
In Unity world typically when people talk about Transforms they're talking about the Transform component
so I assumed that's what you meant
And since you're in Unity world I gave you an answer that involves the Transform component
sounds like you just want to reparent something and keep its old local transform
I don't want to change parents tho
In a way yes, but without the actual parent changing
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
this is okay to have.. right?
define "ok"?
Rotation is kind of the hard part because it would need to be rotated as if the new transform were the world axis.
are you manually positioning these things? it seems odd to have the image and text for every item to have the same parent
they're basically inventory slots consisting of an icon and item count each
I'd expect something more like
nothing that would cause major performance issues basically
- slot
- icon
- label
- slot
- icon
- label
- slot
- icon
- label
Wouldn't it just be:
Quaternion localRotation = movingObject.rotation * Quaternion.Inverse(oldViewer.rotation);
Quaternion newWorldRotation = newViewer.rotation * localRotation;```
e.g.
Transform.localToWorldMatrix
everything is handled by unity UI auto-layout
oh right, unity has that sort of stuff built into it
It takes a little while to learn how to use it correctly
The UI docs do a good job of explaining it
That will (probably, I haven't tested) set the rotation correctly, but the moved object also has to translate with a rotation.
Hold on, i'm going to draw something.
I do not follow.
that's handled by Fen's earlier code
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
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
yeah, my code handles that part
cool I'll combine them then and see what happens
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
I'm not doing anything with scale (yet, hopefully ever)
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);```
yeah we get this
yeah, just shuffling objects around
and the code we already shared should do it
I might just do that
I've done similar things in the past to avoid having to think too hard
Hello, what is a good option with Unity Gaming Services that allows players to log in only with the current game version?
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:
that's actually a good questions, but the problem is that if you can solve this you've solved cheating in games as a whole 😅
but a simple approach would be to send the current version as part of the login / join request, and have the server reject it if it does not match the host. the problem is making sure no one fudged the version number (or any other variable for that matter)
i don't think they want to make it impossible to connect with an old version
just to prevent honest players from doing so
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?
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
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.
Where would that be?
Thank you
You can't. The client can tell the server whatever it wants. The client can also run whatever code it wants. You can implement a soft approach to disconnect users with the wrong client version, but it can be easily avoidable, if that's what you're asking.
Turns out my version has Physics Debugger but not the one that shows queries
then you'll need to show code or something if you want help
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:
I thought it was a quick way of knowing if I could place a new room adjacent to another
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?
Bounds bounds = moduleData.GetBounds();
if (!Physics.CheckBox(bounds.center, bounds.extents, instanceRoot.transform.rotation, _modulesPhysicsOverlapCheckLayers))
Btw, that's the implementation that uses colliders, I'm using another that does the same with the room's renderers
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
But aren't I getting the "tightest" box to a room with this method?
I've been asnwered this just a moment ago hehe...
collider.bounds is axis aligned
I described how CheckBox works
CheckBox uses whatever you give it
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
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);
}
I was about to suggest using Gizmos, so that's good
Do you know an equivalent gizmos debugging that rotates the bounds as Physics.CheckBox would do?
Drawing a rotated box requires you to modify the gizmos matrix
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
It's a bit annoying.
(notice the commented lines at an attempt to do so)
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
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.
Sorry for the possible miscommunication but which thing is axis-aigned? My debugging or the physics call which takes a quaternion?
That's just my debugging
your debugging uses GetBounds()
is that not what you're using to run the box query?
Oh, wait, I have to say that that GetBounds() is my implementation, not a method of a collider or anything. It's this one:
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
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
[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?
general timer loop?
no loop, one shot delay
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
even with invoke, https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
If you need to pass parameters to your method, consider using Coroutine instead
If you want a 3 second delay, then maybe whatever calls this method should wait 3 seconds then call the method instead
you will not be able to return a value that represents a delayed-created object without waiting. That makes little sense.
hi praetor, i figured it out
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;
right so... you used a coroutine and async
i forgot tasks exist
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 . . .
because i dont want the delay to be the caller's responsibility
why? the caller has to wait anyway if you're delaying inside the call, no? because otherwise the return won't work
i guess i could
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
Async await can be less boilerplate code
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)
Or more...
Depending on the use case
oh duh
wait does that pause the coroutine until the YourOtherCoroutine returns or does it keep going
it will wait for that new coroutine to complete before proceeding with the coroutine that started it
if not, how do i make it wait
that's the whole point of the yield
just makin sure
if you didn't want to wait, then you would have to use StartCoroutine otherwise it wouldn't have been started correctly
welp i rewrote my whole tutorial system and removed basically all of the boilerplate so thanks guys
tried to create new project on a new device on a 2019 lts version, got this error everytime i start it
update all packages and delete your library folder
okay, thank you
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.
Maybe go into details about your implementation of On Pointer Enter. Detection should not differ for entry on pointer with or without dragging/selection of an item but maybe there's something other we should know about.
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.
Assuming it's either a Minecraft/Terraria hot bar or Diablo inventory system
Yeah, exactly that. After you drop an item, the tooltip should renable because your cursor should still be over it.
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.
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.
So is the problem that it's showing the tooltips for the previous item?
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
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
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*
If the first, maybe disable the entry script, swap items and re-enable.
Depends on which is actually occurring.
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++
Seems like this would fit better in a c++ discord 🤷♂️
Unity uses c# for one thing...
you can just google it
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
Who's transform.up are you using?
the player's
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?😅
yes.
the ray IS being drawn up... hmm...
just did a Debug.DrawRay(transform.position, transform.up, Color.red);
Yep. Then the issue must be somewhere else. Maybe share details on what exactly goes wrong first.
https://paste.ofcode.org/3JdEXHkQBYjcaMdbFVZF3U this is the simple script that controls the player
https://paste.ofcode.org/VQhC4eEHzaK2rAYFCAsFme and this is the one that rotates the player
Start from describing the issue. Maybe demonstrating with a video?
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
Any math kings out there?
What kind of function do you think might fit the following desired graph? A combinaton function is fine
why do you need to find a formula to a drawn function? this likely will not be a pretty formula at all given half the graph is quadratic looking and the other half is like some stretched middle of a cubic. this is also not a code question
Welp, you almost answered like a good bloke! Thanks:D I'll look into cubics - that sounds excellent
? i am asking what this is for, to possibly suggest something else. Just knowing the term cubic wont help you here
there are curve fitting equations, and calculators online
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
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?
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
you arent gonna find help here for modding something since its against the server rules
oh why is it
im unsure what this means still, you could just manually create the animation in unity. This does resemble the image youve shown, but if you suddenly want to adjust the graph then you are now in a tough spot
Thank you for the suggestion, but i prefer the neatness of modelling movement using functions
because it is not always legal, and just against TOS
I see you got your answer below, but just for future reference, you can use the AnimationCurve to define pretty much any curve you want in the inspector.
And then retrieve the value with animationCurve.Evaluate
how would i fix it? i'd can't get it to work
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
but wouldn't AddForce make the movement really floaty?
No?
Oh cool, thanks @dawn nebula , I didn't know that existed(:
has anyone here integrated unity with kafka or with a different message broker?
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;
}
}```
Indexing starts from 0. If the child count is 1 then only GetChild(0) is in bounds
There's a LOT of problems with this code beyond that too 😕
was just about to say
you really need to read about Quaternions before using them
thanks that fixed it
i don't think i'm actually using any, i'm only using transform to get the child objects
Really? And what do you think Player.transform.rotation is?
also you should read about floating point inaccuracies
yes but the z rotation just returns a float value
true, but not the one you obviously think it is
is it not just the rotaion of the player?
is there a way to add some sort of wiggle or sway to a a rigged object?
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
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.
I'd suggest deleting the Library folder so that Unity re-imports everything
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
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?
Put each collider on a seperate sub-object, then add a script to each catching this: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
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);
}
}
do i still use the 2 box colliders?
Yes, put your gameobject like this:
Parent (ParentScript)
-> TopButton (PressableButton, BoxCollider)
-> BottomButton (PressableButton, BoxCollider)
And then just reference the parent script in both pressable buttons
cant do that its all one mesh
yeah your parent can have the mesh stuff
no reason you cant put the colliders on sub objects
wait so the TopButton and bottom are emptys with the box colliders?
okay thank u sm
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 😄
makes sense actually now
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 😄
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
what kind of events are you using?
C# events.
I guess I want to find every event field and search their subscribers for any methods on destroyed unity objects
Show me a line of code where you create that event please 😄
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
Maybe print the invocation list on destroy?
so I'd want to catch anything that subscribes to this static event, then fails to unsubscribe after I quit the game
this might be what you want
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
settings the timescale to 0 can cause problems with animations and such that you might want to play during a pause
All animations that should play during the pause are on unscaled time
How big is your code? You could just search through all of your scripts and look for +=
I could just do this statically, yeah
the most common problem will be "i forgor"
each += should be balanced with a -=
Sometimes I -= before += just to be sure that there will be no duplicate subscriptions
I'm less concerned about duplicate subscriptions on a single object
more about subscriptions for dead objects
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
for context previous script I tried with render texture
https://hatebin.com/jtqmhtyggd
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
In what way is the reading not correct?
they do change when i start the game but they don't change when I stand in dark vs stand in lgiht
probably some reallly bad math
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
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
ah, that's a good idea -- just render the player alone and measure how bright the image is
yeah except I have no idea where to go from there 😦
Those floats look familiar.
I believe those are how sensitive the eye is to the three main colors
Yeah its a cool technique, I plan on doing something similiar but maybe with ComputeShaders
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?
All i needed was a comment on it and I never did that xD
how would i check
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
I believe only the HDRP works with realistic values for lighting
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.
Oh ok I'm in URP
All of them are pretty workable. I've done them all :p
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
Haha, any one in particular you reccomend?
and it makes communicating with the menu annoying
(e.g. to indicate that it wants to close)
I'd go with DontDestroyOnLoad
btw here is where I got the magic numbers (simply googled the statement)
@hexed pecan @heady iris
https://forum.unity.com/threads/how-to-get-the-brightness-of-an-object-texture.1004932/
Ahh yeah that makes sense
Yeah that's what I'm already leaning towards, thanks for confirming it though
ah, the original didn't divide by the length
ah yeah just noticed..
that might just be the number of pixels in their texture
I would also suggest weighting the pixels differently
must been stolen from someone else who stole it XD
If you see 100 bright pixels and 900 dark pixels, that's still very visible
i would not add that unless I knew for a fact what i was doing
You could square the values and then square root the sum
Or do something logarithm-based
soo much math 🥵
You don't want to just take the max, since that would make a single bright pixel mega-visible
for some reason the values dont' change at all now..oof..
I would debug the value with GUI.Label in the game screen. Inspector and console views may not always update I think
Will try that ty
(Or GUILayout.Label)
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
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);```
Yeah, I mean the console bar at the bottom that shows the latest message - but I could be wrong
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

I feel called out 
today I am working on tutorial popup messages
instead of making the game
but hey, games need those
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
did that but says like 6000+ so array is not empty
could've sworn it used to work somewhat..
sanity check by making lightLevel start at 10 or something
Hmm false alarm I think
Thought it is because you use Color32 but its probably fine
Sorry lol
damm i got hype for a sec XD
just makes it stay at 10 instead of 0 😦
the preview says stuff is happening in render texture I just don't know why no numbers move, it used to work iirc
I presume the render texture is read-write enabled
actually, that isn't even a thing for a render texture
maybe the color format or something ? i dont know what any of them mean so i haven't touched it
have you logged an individual color value yet?
also make sure you're using the right render texture, I guess
good idea I will try
Why does this show the format R16_G16_SFloat 🤔just 2 channels?
oh yeah, that's a little interesting...
oh yeah that was the old render texture
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
Thousands of logs at once will be super slow yeah
i left a log statement in bursted code that was running tens of thousands of times per frame
owie
Try another color format. Im not sure if that is even a floating point format (even after checking docs)
Color32
Colors32
ah, okay
tried a few and it just changes the colors slightly in RT but nothing moves values wise :\
Idk, I would print the min, max and average values of the whole image at first
not sure how to do this , any pointer?
every forum post on this leads me to dead ends
float min = 0f;
float max = 0f;
float avg = 0f;
for(...)
{
min = Mathf.Min(min, pixelValue);
max = Mathf.Max(max, pixelValue);
avg += pixelValue;
}
avg /= totalPixelCount;```
You are kinda doing the avg already
is pixelvalue colors ?
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
like this ?
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;
}
lightLevel /= 3;```
oh wops
Maths!
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);```
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
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
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.
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
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
Your Lerp usage isn't really correct
it's not really clear to me what you're trying to do with that
it's just for testing i know.
the real problem here is the min value is changing when I debug it but the slider won't change
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
so the value is changing but they are changing late in the scroll bar
but then the slider doesn't respond immediately?
yes exactlyy
well your code is missing context but isn't it inside OnGUI or something?
it's iside onGui
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
so this is a combination of your Lerp usage + ONGUI
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
You could use EditorCoroutines for this
I'm only seeing the function called at the exact times that it's updating
the debug show the results but the slider reacts late
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
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?
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");
There's nothing wrong with this, no.
most people go event-based though
Is there any reason to go event-based over polling? Any performance differences?
it's not a performance thing. it's about how you want to organize your code.
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();
}
please share code on a paste site !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ahh okay thanks for clearing it up, gonna stick with my current system then :)
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
sounds like you have a rigidbody or something on the enemy? there is not much to go by here
also show your navmesh bake
how do you mean show the bake
the navmesh area?
also this is the wrong channel prob
prob. we dont know if its code related or not, you haven't provided much info
ok so can we go to the code begginer thanks.
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?
Most people use Json.NET.
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
@heady iris thanks a lot!
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!
@heady iris yeap definitely. now i just need to figure out how to install it 🙂
What version of unity are you using?
If it's new enough, you can just install the package by name in the package manager
2022 LTS
Okay -- go to Window > Packager Manager
click the "+" icon and pick "add by name"
then punch in com.unity.nuget.newtonsoft-json
@heady iris oh wow that was easy, didn't know i could install it like that. thank you so much!
iirc unity cloud save also uses json.net so transition should be easy
I think for save files and stuff you can do it in pretty much any format: https://docs.unity.com/ugs/en-us/manual/cloud-save/manual/concepts/files
I’m talking about on the back end it gets serialized as a json
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