#archived-code-general
1 messages · Page 244 of 1
and I spam so many Debug tools that profiler is normally not super accurate in editor mode
shoot..is there no efficient way to do this.?
ty I'll look into profiler
hmm ill give it try
You can just profile in editor, the same processes will still be present in the build, so if you see a lag spike due to some code or loading etc that should still be there in build, so if you fix the issue in editor mode that should fix it in the build
Also I'm not sure how the "scene" camera works as far as profiler, you'd think that the profiler would be only giving you info based on the Camera in game but i believe that in some cases the scene camera acts as a second camera
check if there is an impact on performance by closing the scene panel
I knwo this is the case for some functions like "IsInView" or whatever it is for renderers.
I'm not sure if its a bug or intended
does this look correct
public static HashSet<Color> ReadPixelColors(this Texture2D texture)
{
Color[] cs = texture.GetPixels();
for (int i = 0; i < cs.Length; i++)
{
cs[i].r = cs[i].a;
cs[i].g = cs[i].a;
cs[i].b = cs[i].a;
cs[i].a = 1.0f;
}
return cs.ToHashSet();
}```
var hash = colorTexture.ReadPixelColors();
foreach(var h in hash)
{
hashedColors.Add(h);
}``` still white just not 90000 colors
now I remember also why I used GetPixelData 😔
> Each pixel is a Color struct. GetPixels might be slower than some other texture methods because it converts the format the texture uses into Color. GetPixels also needs to decompress compressed textures, and use memory to store the decompressed area. To get pixel data more quickly, use GetPixelData instead.
>
> A single call to GetPixels is usually faster than multiple calls to GetPixel, especially for large textures.
>
> If GetPixels fails, Unity throws an exception. GetPixels might fail if the array contains too much data. Use GetPixelData or GetRawTextureData instead for very large textures.
https://docs.unity3d.com/ScriptReference/Texture2D.GetPixels.html
i have a lot of expensive editor-only debugging checks, so profiler in editor isn’t always accurate
sometimes super inaccurate
Can someone explain why this code produces this log:
private void _Release(Vector3 position = default, Quaternion rotation = default)
{
Debug.Log($"{rotation} {rotation == default} {rotation == Quaternion.identity} {rotation == new Quaternion()}");
}
(0.00000, 0.00000, 0.00000, 0.00000) False False False
Because you've passed an invalid quaternion as the parameter
Quaternion.identity (and default etc) is (0, 0, 0, 1)
no, default is 0,0,0,0 and is invalid and should never be used
try showing what default is
hello i have problem. how to move smoothly objects and not on lines in unity scene?
i expect default to be all 0
but if rotation is default, you might be getting false because == with floats is suck. just a thought
no it is false because it must pass a validation test, which it fails
is that just part of the == for quaternions?
for any operation on a Quaternion
because 0,0,0,0 should be an invalid quaternion
Yes, and two invalid things are not equal to each other
Default quaternion and new quaternion struct are both all 0s
yeah, then it’s the overloaded == operator
you can check it btw
just check source code for == under quaternion. hopefully it isn’t injected
I checked it, I think something else is going on, it's just a comparison of the 4 component floats
it's not, the code is very clear, only valid Qaternions allowed for operators
How would you recommend passing in a default val for a quaternion as a method arg?
I know that you use Unity Events by += subscribing and -= unsubscribing functions to them. But, it seems I cannot find a function to unsubscribe everything from the Event?
I'm making a modal window for my UI, I want to set it up so that it hands in my main UI object, and various situations that require an y\n reaction from the player will activate that UI object and subscribe to one of it's Events. I then want to ensure that at no time no matter what no more than a single subscriber for that event exists and the past subs wouldn't linger, so in the function that gets called when a button in the modal window is pressed I want to call Invoke on the appropriate event, and then unsubscribe all subscribers from it:
public event Action PressedOk;
public event Action PressedCancel;
public void CallbackOk()
{
PressedOk?.Invoke();
PressedOk?.UnsubscribeAll(); // This one is missing
this.gameObject.SetActive(false);
}
public void CallbackCancel()
{
PressedCancel?.Invoke();
PressedCancel?.UnsubscribeAll(); // This one is missing
this.gameObject.SetActive(false);
}
I suspect if that function is missing, my idea for how modal popup should work isn't exactly a correct one?
iirc it must be a constant so try making one from Quaternion,identity or 0,0,0,1
Quaternion rot = Quaternion.identity;
Quaternion rt2 = Quaternion.Euler(0, 0, 0);
Quaternion rt3 = new Quaternion();
Debug.Log(rot == rt2); // true
Debug.Log(rt2 == rt3); // false
Debug.Log(rot == rt3); //false```
RemoveAllListeners
No such function I can find, however I found a similarly sounding one, would that be correct? Not sure why it requires two arguments though, based on the description at the Microsoft docs, I think I should pass the same into both anyway.
Action.RemoveAll(PressedOk, PressedOk);
Oh sorry I thought you were talking about UnityEvent
for a normal event just set it to null
- those are just regular events, not UnityEvents
- just assign null to the event
Oh, got it, thanks!
does anyone know what this line of code is doing? (the whitemask and blackmask are also integers)
const int colourMask = whiteMask | blackMask;
I'm not too sure what the | symbol is doing
it's the bitwise OR operator
e.g.
0b00010000 | 0b00000010
Gets you cs 0b00010010
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operations and directly supported by the processor. Most bitwise operations are presented as two-operand inst...
tysm
What game mechanic are you making?
Why are you setting the RGB to the alpha value
ahh I didn't know how to use getPixel just realized I blindedly copied 🥲
I'm trying to just get the amount of colors on a texture, mainly to average them to see if it has many colors above black
I want to use for other stuff too but mainly to see if what the RT camera is looking at is lit up by lights
Okay so the for loop that sets RGB to the alpha value is not intentional at all?
Because that would make it all white if it has full alpha
nah I copied that from a forum post
do i need that loop at all?
wooo
thanks for making me notice stupid mistake..
for some reason when I read my made texture from RT though...
I think the color format has something to do with it but idk how ton change it
here are the differences in format
So RT is RGBA32 and normal texture is RGB8
This looks like it would match RGB8
thats the texture from RT
this is the original RT
I can't find info about RGB8 but I guess it's 8 bits per channel
Im trying to block clicks under gui button using if (EventSystem.current.IsPointerOverGameObject()) return;, but this also blocks clicks on terrain, I think because my canvas covers the entire screen?
Or maybe it is 3+3+2.. Idk
That alone should not block the screen unless there is a raycastable "image" or something that covers the entire canvas
hmm is there no way to make RGBA32 an RGB8
I tried this manual copy didn't work
public static Texture2D ChangeFormat(this Texture2D oldTexture, TextureFormat newFormat, out Color32[] color)
{
Texture2D newTex = new Texture2D(oldTexture.width, oldTexture.height, newFormat, false);
Color32[] cs = oldTexture.GetPixels32();
color = cs;
newTex.SetPixels32(cs);
newTex.Apply();
return newTex;
}```
ir just copies it black
@delicate oliveWill this check not stop me from clicking on my buildings etc. too?
You mean the IsPointerOverGameObject() check?
I'm looking at the docs but the RenderTextureFormat names don't match the names in the RenderTexture inspector dropdown...
https://docs.unity3d.com/ScriptReference/RenderTextureFormat.html
I would try something that has 8 bits per channel
@delicate oliveYea
yeah thats whats weird
Maybe R8B8G8A8_UNORM?
I've been using it in my 2d game so no it shouldn't stop that unless you have something like an image blocking the entire canvas
Do i have to switch the new texture iirc CopyTexture method throws error
Wait, are your buildings UI Images or 2d SpriteRenderers?
if you recall I had this yesterday ```cs
yield return new WaitForEndOfFrame();
newTex = new Texture2D(
renderTexture.width,
renderTexture.height,
TextureFormat.RGBAFloat,
0, false);
Graphics.CopyTexture(renderTexture, newTex);
met.mainTexture = newTex;
yield return new WaitForEndOfFrame();``` @hexed pecan
if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject()) return;
Makes me unable to click on anything else but UI
My buildings and units are in 3d
Change RGBAFloat to RGBA32 and use R8B8G8A8_UNORM for the render texture
Logically it should work, both have 8 bits per channel and 4 channels
@rigid island See my edit
close I think
its not black but now im having the same color than when I did ReadPixelData with original format on new texture```cs
//pixelData32 = newTex.GetPixelData<Color32>(0);
// for (int i = 0; i < pixelData32.Length; i++)
// {
// if (!colorsNewTexture.Contains(pixelData32[i]))
// {
// colorsNewTexture.Add(pixelData32[i]);
// }
// }```
To find the UI blocking the view, you could do something like this:
public GameObject GetGameObjectOverPointer()
{
var lastPointer = GetLastPointerEventData(-1);
if (lastPointer != null)
{
return lastPointer.pointerCurrentRaycast.gameObject;
}
return null;
}
// Debug the logic using log statements to for example print out the name of the gameobject if it isn't null
Slight correction; to use the protected GetLastPointerEventData() function, the class needs to derive from StandaloneInputModule
How is this not managed by Unity by default
It is, I just believe it's some object on your end blocking the entire canvas
you can see what UI is blocking with the event system panel already
Really? I've never seen it show the object I'm hovering over
yea it shows everything
pointerEnter
if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject()) Debug.Log("Clicked on GUI");
This fires on EVERYWHERE I click
Ohh I didn't even realize you could drag the bottom panel to see all that stuff
use the panel 🪄
Always looked at the "First Selected" field on the EventSystem component and it was always null so
What panel?
click on your event system, there is a panel in the inspector. it may be collapsed at the bottom
^ panel
also you have to be in play mode
🤔 not really sure why you dont see anything tbh
It should also show the object in the inspector when it is in Debug mode
Where's your standalone input module? I have it here
I dont have one
Oh you must be using the new input system then
Its converted
It shows you had "pause button" selected..?
So it must be detecting somethign
Ya it detects my gui buttons
But does "selected" mean "hovering" or does it mean you've clicked the button?
This option also clears the selection when clicking on terrain
It always says Selected:
What if you just try disabling the canvas and see if you can click the 3D objects
I can not
Then if you can, work down the canvas hierarchy object by object until you find the culprit
So it's not the canvas
Did it register input b4?
Ya, if I remove the eventsystem check I can run my raycast
void Update()
{
if (Input.GetMouseButtonDown(0)) {
// if (EventSystem.current.IsPointerOverGameObject()) Debug.Log("Clicked on GUI");
Destroy(_placedMouseCursor);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask)) {
Debug.DrawLine(transform.position, hit.point, Color.red);
_placedMouseCursor = Instantiate(mouseCursor, hit.point, Quaternion.identity);
MoveAgent(agent);
}
}
}
Is the EventSystem a part of the new input system? Because you're using the new system and if it's not then you shouldn't even be doing the check with the old system
I haven't used the new system so I dunno
ChatGPT says it is part of the old system
and that there is no equivalent in the new system
Found this thread:
https://forum.unity.com/threads/is-there-a-replacement-for-eventsystem-ispointerovergameobject.740462/
Maybe you're using a version older than 2019, or your inputs aren't configured correctly
I guess we're at a dead end (at least on my part) because I have never used the new input system; maybe people in #🖱️┃input-system are more knowledgeable with this
hi!
i want to have a list of scritps to be add on the object when it is instantiated, how can i do that?
Loop over the list using foreach and on each iteration, add a component to the object with the component being the script in the iteration
it makes sense, but what i don't know is the type i should declare the list
MonoBehaviour..?
List<System.Type>
Component should be fine, if you want to be adding stuff like rigidbody
i tried and didn't work
But can all System.Types be used as a Unity component?
no, but it's your list so you control what goes in it
Yeah but he wanted to use the list in a function that adds components to an object
yeah, so?
Using System.Type in the list would not allow for that functionality..
of course it would
you can cast
Yeah, but why cast when you can just directly declare it as a list of MonoBehaviours/Components?
no need to cast Addcomponent has a Type override
Doesn't it cast under the hood then?
no
oh it does have an override
no, System.Type is not serializable, but then you never mentioned that
System.Types aren't serialized, use something like MonoBehaviour
that make sense
Also, do you really need to use AddComponent? You could consider methods like prefabs
i thought on the addcomponent for scalability
Alright, I don't know your systems so you do what is best
this does sound weird to be adding a list of components, but if you do continue like this then you probably do want to use Component instead, or else you wont be able to add rigidbody or similar stuff
Depends on what you're using this for; spawning enemies?
Then I would use a prefab 100%
i have a bullet and want to add modifiers to it
this is a prototype btw so i can test all the ideas
AddComponent does have a string override, so you could have a simple List<string>
Idk, this may be a great way for that as it uses composition (which is good for modularity), but another approach would be to just have one class like BulletModifiers attached to the bullet and access that when you want to add effects to it
i forgot about that
give me a minute
If you need this to be 100% modular, like the user can fully customize what a bullet can do then I'd just store the modifiers in one class and maybe have the functionality on a scriptable object.
If it's a difference of selecting between 5 possible bullets, just make prefabs
It's marked as Obsolete, not sure if that matters though?
But using string means that changes in file names would not be reflected in the list so I don't think it's the best way
It's definitely not the best way, just a quick way to test
And when refactoring for example, file name changes are pretty common so
Yep
yeah it gives me compile error for being obsolete
but i think it is possible to convert from string to type
yes, using Reflection
Is that really a compile error? I thought itd just be a warning
Not sure if it's a compile error, but it brings up this prompt:
It does show up as a compile error in VSCode though
Though really you could just define this list manually in code since you're testing it. You definitely dont need strings and reflection for this feature. Doing this really should be fine
#archived-code-general message
Interesting
it works btw
now i just need to do it for the list
do this have any significant performance impact?
You could also make a dictionary that maps an enum value to a type
idk that C# had dict
that's cool
i liked the string aproach
just need to know that
thats just something you'll have to profile, itll be slower for sure compared to just already having the right type stored
i think i can do something
i can just have the list of types ifself
but now it works, thank you all
Is it possible to use the netcdf library in C# to play simulations in Unity or does anyone know how to do this in Unity =) ? Hey guys I currently have a C++ project where I simulate tsunami waves 2 dimensionally. To save the values of the waves I use the netcdf,zlib , hdf5 library. The calculated values are then saved in this .nc file and I can then display the values in a program "Paraview", i.e. play the time steps and then see a simulation. My goal now is to bring everything into Unity and play my simulations directly in Unity.
hello, why camera 02 is not turning on using UnityEngine;
public class LevelLoader : MonoBehaviour
{
public float targetY = 5.14f; // Docelowa wysokość Y, po której obiekt przechodzi na kolejny poziom.
public Transform Player; // Referencja do obiektu gracza (Square).
public Camera camera0;
public Camera camera1;
public Camera camera01;
public Camera camera02; // Nowa kamera
private bool isTransitioning = false;
private void Update()
{
float playerY = Player.position.y;
if (!isTransitioning && playerY >= -5.39f && playerY <= targetY)
{
SwitchCamera(camera0, camera1, camera01, null); // Zmień na kamerę 0
isTransitioning = true; // Ustaw flagę przejścia na true
}
else if (isTransitioning && playerY > targetY)
{
SwitchCamera(camera1, camera0, null, null); // Zmień na kamerę 1
isTransitioning = false; // Resetuj flagę przejścia, gdy gracz wraca poniżej 5.14
}
else if (isTransitioning && playerY < -5.39f && playerY >= -10.78f)
{
SwitchCamera(null, camera0, camera01, null); // Zmień na kamerę 01
isTransitioning = false; // Resetuj flagę przejścia
}
else if (isTransitioning && playerY < -10.78f)
{
SwitchCamera(null, camera0, null, camera02); // Zmień na kamerę 02
isTransitioning = false; // Resetuj flagę przejścia
}
}
private void SwitchCamera(Camera enabledCamera, Camera disabledCamera1, Camera disabledCamera2, Camera disabledCamera3)
{
if (disabledCamera1 != null)
disabledCamera1.enabled = false;
if (disabledCamera2 != null)
disabledCamera2.enabled = false;
if (disabledCamera3 != null)
disabledCamera3.enabled = false;
if (enabledCamera != null)
enabledCamera.enabled = true;
}
}
first, !code 👇
second, you should consider using Cinemachine instead of that and it will be as simple as just enabling/disabling and/or setting the priority on different vcams instead of that mess
as for why this isn't working, what debugging have you done to ensure that your conditions are what you expect them to be?
📃 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.
in the case of other cameras it works, it doesn't work here, this is my first game I'm making so I don't know much about it
and when it comes to cinemachine, now that I look at it, it is probably used to track the player, the idea of the view in my game is a bit different
you don't have to track the player with cinemachine. it's meant to control your camera
but you still haven't answered what debugging steps you've taken to ensure that your conditions are being met
what do you mean by debugging steps, I'm seriously a beginner?
then #💻┃code-beginner next time.
and https://unity.huh.how/debugging
Is it supposed to move constantly?
testing it
That will practically only move it once, 2 units right of the starting position
but it stays in place, not sure if its jittering
Then gameMode is probably not 1
Or you have something else changing its transform, like an animator with root motion
its just a sphere and i put a debug statement there and its being called
I instantiated it but I call starting position after that
It says that it moved once and then stalls there
Also answer this ^
I suppose yes?
im testing it so yes for now
You are setting the pos to startingPosition + offset, neither of those values are changing so it will stay in place
You can do transform.position + offset if you want it to constantly move
but its in the update
That will move it 2 units every frame though, so you want to multiply it with deltaTime to make it correctly scale to framerate
Okay but you aren't changing startingPosition in update
I am having an error when trying to instantiate a gameobject. Anyone have an idea how to squash this one? The script is accessing a public gameobject which I have asigned in the editor. When I play the cene the object can be seen assigned in the editor. Why is my script saying it is null?
Why is my wheel collider so big ?
are you sure you are calling the healthRefresh method on that particular instance of this component and not perhaps a prefab?
this is a code channel
Ok which is the correct channel for this ?
Thanks! I was creating a new instance instead of finding the one in the scene.
if I have an object of type Type, is there a way to check if that type implements a given interface without instantiating it?
t.IsAssignableTo(typeof(IInterface))
ty vertx. is that performant, out of curiosity?
I just need to ask because sometimes, I get these functions that are a perfect fit, but surprise: giant lag
huh, VS can't find IsAssignableTo
In Unity's version it used to be IsAssignableFrom, just reverse the arguments
much more confusing way of doing it, so they flipped it thank god
I see that. but I see IsAssignableTo in the source. I just can't access it for some reason. it says no such method found in System.Type
Yes, it doesn't exist in this version of .NET
ty for all the help. got it all working. 👍
Looking into Additive Scenes currently, It doesn't look like you can simply load an additive scene in and place it at a specific position natively from what I can tell.. I have some ideas of how to position the additive scenes in the active scene but it's a hacky solution.
How do others work with them generally?
Scenes don't have positions
If you want things IN scenes to be positioned differently, you need to put those things in their positions
right, that makes sense. So you have build these scenes with specific coordinates in mind to ensure scenes don't overlap each other.
Pretty much. I don't usually do additive scenes for locations simultaneously.
I do one for managers and stuff. And another for a location. Then I only have one location open at a time. So i'm not positive how others handle that part
in my case, it is for level chunks. Probably see if Prefabs are just as viable
my collider isn't disabling when I do this
{
ChangeAction(ActionState.hit);
Rigidbody.velocity = Vector2.zero;
Hurtbox.enabled=false;
ChangeEffect(EffectState.hit);
animator.SetInteger("Effect",(int)effect);
//Parent.Animator.SetInteger("State", (int)ActionState.hit);
Controllable = false;
gameObject.layer = 9;
Debug.Log("Hurtbox: " + Hurtbox.enabled);
}```
or well
the debug returns false, but it's still enabled on the inspector, and when I check it here it returns true
void endInvincibility()
{
Debug.Log("Hurtbox: " + Hurtbox.enabled);
Hurtbox.enabled = true;
ChangeEffect(EffectState.normal);
animator.SetInteger("Effect", (int)effect);
gameObject.layer = 0;
//Parent.Animator.SetInteger("State", (int)ActionState.idle);
}```
no other part of the game even references the hurtbox
sounds like you're referencing the wrong collider
i'm not, clicked on "hurtbox" on the inspector and it's the right one
then it's getting re-enabled elsewhere
ok so, it's in the animator since when I disable it it kinda works.......but IDK how/why it does that since my animations don't reference my hurtbox
the current animation, for example
https://docs.unity3d.com/Manual/class-State.html
See "Write Defaults"
I have a general question not necessarily help with code but I’m trying to generate an enemy base in 2d that consist of walls turrets buildings ect I’d obviously assume I have to instantiate some prefabs and what not but what would the logic be like behind that for randomly generating a base
how would I get the walls to spawn in an orderly fashion for example
I've extracted a function in one of my scripts as an extension abstract generic method, because I needed to do same thing in another script, and it for some reason doesn't work like that - even in the initial object I plucked it from. What might be the problem?
public static T FindInParents<T>(this Transform p, int hierarchyDepth=5) where T : class
{
Transform currentParent = p;
T obj = null;
for (int i = 0; i < hierarchyDepth; i++)
{
if (obj == null && currentParent != null)
obj = currentParent.GetComponent<T>();
if (obj == null)
currentParent = currentParent.parent;
else break;
}
if (obj == null)
{
DevLog.LogError("No parent has "+typeof(T).FullName+" component");
}
return obj;
}
this is incredibly vague, what part doesnt work? are you getting an error?
Yes, sorry. It constantly returns null and can't find anything in parent objects (It's purpose is to try to find a component "upstream" in the hierarchy), despite finding components when it was a simple regular void in the original object
did u try using the debugger to see why
Isn't using the Log function a debug?
the visual studio debugger can show u line by line what values are, and your debug only prints at the very end. cant really see whats happening properly
I use Rider, and while it activates the debug mode in unity, it is completely empty:
not really sure how rider debugger works tbh
Oh, I needed to add a red dot to the line of the code...
Yeah, that's a breakpoint. It halts the execution of code when that line is run.
Super powerful. There are conditional breakpoints too.
Ok, I can see what's happening now, it seems like the problem is that the for Loop runs only for two iterations no matter what. Even if I just hardcode 5 iterations, for (int i = 0; i < 5; i++), it checks the current transform, the parent of that transform, and then seemingly stops - next breakpoint happens for script on another object.
@thin hollow So, I am only just coming in to this, but I see you have two conditions that check if the object is null, and else it breaks.
Could the object simply NOT be null? The first if statement sets it to something currentParent is not null
for (int i = 0; i < hierarchyDepth; i++)
{
if (obj == null && currentParent != null)
obj = currentParent.GetComponent<T>();
if (obj == null)
currentParent = currentParent.parent;
else break;
}
Were one of those if statements supposed to say if obj != null?
I would use the debugger to on the obj = currentParent line
It is on that line, yes, actually. The logic for the if check is to see if obj wasn't found yet , and if parent isn't null - to avoid null ref exception when I try to call GetComponent on it.
am I missing something? Whats the i variable here for?
for (int i = 0; i < hierarchyDepth; i++)
{
if (obj == null && currentParent != null)
obj = currentParent.GetComponent<T>();
if (obj == null)
currentParent = currentParent.parent;
else break;
}
I dont see you using it anywhere
you arent iterating over the transform hierarchy anywhere
It's a for loop. it needs i to iterate.
okay so what are you exactly iterating over here
That is just a standard for loop. i is the conventional variable to use in it
just i times over the direct parent?
just trying to understand the goal here
okay I got it, 1 sec
I read it as a deep hierarchy. Many levels of children, grandchildren, etc.
It iteratively checks up the chain for a given generic component
yep yep got it, I was confused due to how this was written, a lot of the checks seem a bit redundant
The way it supposed to iterate is "try to get component from the current transform, if it returns null, set current transform to the current transform's parent, repeat until component is found or loop ran out"
hmm yeah it seems very sane, let me plop this on an empty project and see if I can get it working
you dont need to check if the object you are passing is null, if its null then it means you got into a null parent aka top hierarchy object so you can do something like this instead
Transform currentParent = p;
T obj = null;
i = 0;
for (int i = 0; i < hierarchyDepth; i++)
obj = currentParent.GetComponent<T>();
if (obj == null){
currentParent = currentParent.parent;
if (currentParent == null) break; //If the parent is null then we stop traversing the hierarchy
}
}
but yeah doesnt fundamentally change the code, gimme a minute to get unity running
Huh, weirder, I commented out else break;, and now it completes the loop. Upside - it works, downside - I think this way it doesn't stop and runs out the remaining loops even after object was found. A little, but waste of resources. Not ideal, but I don't think I will have hierarchies deeper than 5 or 6, so...
Still, why it does this?
what do you mean?
I just called your code and it worked on my end
but it returned itself
if for some reason the class you are running this from also has the component you are looking for it will return itself
I call it in this way:
ICollisionTriggerReceiver parentInterface = transform.FindInParents<ICollisionTriggerReceiver>(5);
And, no, the class I run this from doesn't have ICollisionTriggerReceiver interface inheritance, it's only on the parent.
hmm yup your code doesnt find the object on my end
I thought maybe the issue is due to ambiguity of ifs with those missing parenthises, but with both
for (int i = 0; i < 5; i++)
{
if (obj == null)
{
obj = currentParent?.GetComponent<T>();
if (obj == null)
currentParent = currentParent.parent;
else break;
}
}
and
for (int i = 0; i < 5; i++)
{
if (obj == null)
{
obj = currentParent?.GetComponent<T>();
}
if (obj == null)
{
currentParent = currentParent.parent;
}
else break;
}
it breaks again. =\
there is something really weird going on
for (int i = 0; i < hierarchyDepth; i++)
{
Debug.Log($"Checking for Component on: {currentParent.name}");
obj = currentParent.GetComponent<T>();
Debug.Log($"Obj is null?: {obj == null}");
if (obj == null)
{
currentParent = currentParent.parent;
if (currentParent == null) break;
}
}
ohhhh nvm
this works for me
public static T FindInParents<T>(this Transform p, int hierarchyDepth = 5) where T : class
{
Debug.Log($"Running");
Transform currentParent = p;
T obj = null;
for (int i = 0; i < hierarchyDepth; i++)
{
Debug.Log($"Checking for Component on: {currentParent.name}");
obj = currentParent.GetComponent<T>();
Debug.Log($"Obj is null?: {obj == null}");
if (obj == null)
{
currentParent = currentParent.parent;
if (currentParent == null) break;
}
}
if (obj == null)
{
Debug.LogError("No parent has " + typeof(T).FullName + " component");
}
return obj;
}
Hmm, you think its because of the daddy parent issues?
I think your code will not find anything if the desired component is from the first child of the object, instead of the object itself. I think this code trying to find the first encountered component instead of trying to grab one from the topmost parent has more potential usage in the future .
Hm, yeah, your version seems to work even with the "break" that, well, breaked it before. Weird >_<
for (int i = 0; i < 5; i++)
{
obj = currentParent?.GetComponent<T>();
if (obj == null)
{
currentParent = currentParent.parent;
if (currentParent == null) break;
}
else break;
}
just to make sure, you want a version of this script that returns the last ocurrence of the class right?
no, the first it gets. For the last I think I can always crawl to the topmost parent with iteration and call "findComponentInChildren()" from there.
gotcha gotcha
then yeah that should work for you then, let me do a double check with another class just to be sure
I think I am finding a unity bug here
If I check for a rigid body class
it breaks
for some reason the returned obj is not null
but its null when checked
bizarre
it only happens when looking for a rigidbody haha
Yeah i think this is some bizarre unity issue, this doesnt work for any UnityEngine class
oh
obj == null
yeah this is wrong
you cannot do that for Generic types
Does anyone wanna be a playtester for a unity project?
@thin hollow okay this is the fixed version
public static T FindInParents<T>(this Transform p, int hierarchyDepth = 5) where T : class
{
Transform currentParent = p;
T obj = null;
for (int i = 0; i < hierarchyDepth; i++)
{
obj = currentParent.GetComponent<T>();
if (obj == null || obj.Equals(null))
{
currentParent = currentParent.parent;
if (currentParent == null) break;
}
}
if (obj == null || obj.Equals(null))
{
Debug.LogError("No parent has " + typeof(T).FullName + " component");
}
return obj;
}
it was indeed some unity fuckery
You cannot directly check for obj == null
because it is not a Unity type
this checks both cases, as a system object and as a unity object
probably missing some context because i didnt read the entire conversation but you cannot use null conditional (?) or null coalescing (??) on unity objects
https://docs.unity3d.com/ScriptReference/Object.html
This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
Damn, I would never caught that if I encountered this, thanks!
Hello, I have run into the error :
ArgumentException: GetComponent requires that the requested component 'Image' derives from MonoBehaviour or Component or is an interface.
This confuses me as I believe that an Image is a component, contrary to what the error states.
Um, doesn't MonoBehaviuor inherit from Object but can be checked via ??
did you declare a class/struct named Image by chance? hover over the Image in your IDE and see where it comes from
no
It comes from UnityEngine.UIElements.Image
unity overrides the equality operator, ? and ?? dont use the override so its not guaranteed to perform as expected. also maybe your issue could've been fixed by just using where T : Component. not really sure what was going on with that equality check "fix" but it looks questionable tbh
It’s the generic
You can absolutely use == null in Unity stuff
But the code using a Generic null check was the issue, that’s just not a thing in general
i didnt say you cant 🤔
Oh you meant the operators lol
But yeah the issue was exactly what was described here
Obj = null was being reported as false even when the object was indeed null lol
maybe you need the UnityEngine.UI one 🤔, not entirely sure otherwise
I was ussing this method to avoid another bug I've encountered with UnityEnging.UI not showing up in my IDE
The solutions of which seemed drastic
One of usecases of this function is me trying to find interface, so no dice, though it's nice to know there can be other things besides where T : class
You can do all kinds of constraints. You could have where T : MonoBehaviour or where T : Enemy (if you have that defined)
What do you mean not showing up in your ide
Tbh I dont see why you would need a function like this, it doesnt make a whole lot of sense where a function would try to find a component in its parent then give up after a certain amount of steps
The package is installed but is not recognised
The whole idea of finding a component in a parent to me is very bizarre too
If you have a sane architecture you almost never wanna do that
I was getting the component because due to the UnityEngine.UI not showing up in the IDE, I could not use the UnityEngine.UI Image, and instead had to use the UnityEngine.UIElements Image, which cannot be referenced publicly
so because I couldn't reference the thing I wanted dirrectly, I tried to workaround it and failed
Talking about the other code not yours hehe
My first case for which I initially thought it up: I needed to have several trigger colliders on one prefab and to also discern between the triggering of different colliders (It's an object that does different things based on from which direction player have come from, basically, and directions aren't aligned with the coordinate grid). So I implemented interface for the prefab object that receives typical OnTriggerEnter function analogs, but with additional references to what child they were triggered from. I didn't want to hardcode in parent-child structure (what if I'll want to reuse this in another prefab with a different amount of children?), so I made this code so that child objects would seek the interface in parent on their own.
i dont recall needing to install it, but im pretty sure its this
i think this is trying to be too generic, you can easily just drag a reference in for the prefabs. You'll have a much harder time debugging in the future when something goes wrong
This is the Package Manager, right? For me Unity UI was already installed as well, I think it's a fundamental thing
yea but not really sure why your ide doesnt show it tbh
It might be a Visual Studio Code Editor issue, I will look into that. Thank you for the help either way 👍
If you want a pro tip about interfaces in Unity @thin hollow
If you are gonna have any kind of serialization and prefabs you should try not using them lol
You are gonna have a lot of headaches
Nowadays I use virtual methods and avoid the issues down the road
Why? what problems do they bring?
I have my entire level design philosophy built around basic "triggerInterface" with which different classes can activate any other object you reference to them in the Inspector....
Nested serialization (prefabs and prefabs of prefabs) really mess the references up
Food for thought it might not be something that happens to you hehe
All of my references are set once in the editor and won't change during gameplay, so they aren't being serialized.
Though, for NPCs, that's not true, so that's an important warning to look forward to, thanks again!
Would probably need to serialize GUIDs instead of direct references, and on loading search for objects with that GUID to reassign the references...
Btw setting stuff in the editor is serialization
In fact that’s a really easy way to break interface serialization, nested prefabs completely break interface references and you have to assign them at the top level prefab
Wait, but if it's nested serialization that messes references up, how not using interfaces will help to avoid this?
That doesn’t happen to normal references
How are you referencing interfaces in the editor btw?
Hm, I cant say for sure for my entire project, but for Trigger system specifically I reference GameObjects, actually, and then on call of the function to trigger the event, it checks if the game object has TriggerInterface on it. I don't remember why I didn't reference interfaces directly, but now I kind of glad I didn't?
You can’t really do that by default yeah which is a big downside
Using something like Odin Inspector you can reference them directly and that’s when things break
Ah, well, that's easy then, I can't use Odin cuz I can't pay for it. XD
how do you shuffle a list
hey im working on a game, and when built, it crashes. i was wondering if yall know what can commonly cause a unity game to crash (besides hardware issues). programming-issues wise i mean. null references dont really cause crashes they just stop running code for that script so what actually warrants a crash crash, like full application close
public static List<T> Shuffle<T>(List<T> _list)
{
for (int i = 0; i < _list.Count; i++)
{
T temp = _list[i];
int randomIndex = Random.Range(i, _list.Count);
_list[i] = _list[randomIndex];
_list[randomIndex] = temp;
}
return _list;
}
NRE can crash your game since there is no any guard stopping you making write/read violation
If you have player logging enabled in build settings, you could go to ".../AppData/LocalLow/MyStudio/MyGame/Player.log" and see what caused the crash..?
Does Player.log log crash messages?
ios game so i cant do that sadly - cant build for pc either
why on other projects it worked with just SceneManager.LoadScene("Game 1");, but now i need to do SceneManager.LoadScene("Project Data/Game/Scenes/Game 1"); Also in this case if i were to check for scene name, should i check for the full path or just Game 1?
it's UItoolkit
avoid hardcoded path. you can do something like this SceneManager.LoadScene(SceneManager.GetSceneByBuildIndex(index))
ah, so the index would be the one in build settings right? 0,1,2...
yes
Thanks
also, maybe someone already tested this so i dont have to. When player tries to load the game for the first time with Google play games services, does it return an empty by array with success, or is there an error?
For people new to async/await approach,
Let's say we have a method:
public async Task RenameUser(string userId, string newName) {
throw new NotRegisteredException();
}
What will the return type look like and how can the method caller handle this exception?
you'd want Task<T> to return something
async Task<bool> AsyncFoo()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(5), myTokenSource.Token);
}
catch(OperationCancelledException)
{
//Do your thing when token was cancelled
}
return true;
}
In the Unity build how can I make it detect display 1 and display 2 ?
your intention must be clear when throw-ing, based on your example, I don't think throwing is the correct approach for user registration
Do I?
E.g. Task.Delay() from Microsoft doesn't have a type parameter.
I made up this example to make the question clear 🙂
Tasj.Delay is just a Task
here from the docs
yep, exactly
By return type I mean will Exception be thrown upwards the stack or will it be "Task" with IsFaulted == true.
But I got it clear already, thank you.
you can always check them via Task.Result
if you're wrapping your logic around the tokensource cancellation then just check the token instead
also, it is a good practice to throw in async/await when cancelling sources
You're confusing returning and throwing. If you throw, it would probably propagate up the async state machine
Unless you await it I guess🤔
Always confusing business with the async throws
so I'm watching a tutorial on an inventory system using script able objects. is it always bad to change script able objects at runtime or is it fine to use in an inventory? would making an onapplicaitonQuit function to clear the inventory work?
Rather than having hard inscrutable rules like "never change an SO at runtime" it's better if you just understand how ScriptableObjects behave in the editor, at runtime, etc, and then you will know what to expect if and when you change them at any time
I understand that changes to them persist but could you elaborate? i'm just trying to learn best practices for unity dev and overall coding architecture. I feel that many tutorials overlook this to simplify everything like making everything public.
Changes to them persist only in one specific circumstance:
The SO is an ASSET and you're currently in the editor.
Under all other circumstances, changes will not persist
so why have I heard that they should only be used to store data that won't be changed? Is it acceptable to use it for an inventory?
Because people often run into that specific circumstance and also people love hard rules without understanding behind them
It's acceptable to use for an inventory if you understand the nuances and the behavior that will come from how you are using it
Obviously the difference of serialized vs non serialized data also comes into play
how so?
How not so?
Serialization is central to that whole persistence issue
Since only serialized data can possibly be persisted by the engine
A lot of people use SOs as a convenient referencable object in the editor.
You could do that and have a non serialized inventory on it and there's no risk of persistent changes
So it really just depends on exactly the details of your usage
SOs can be used many ways, but the only reason I don't write to them is because plain c# objects satisfy my requirements already.
it's actually fine if you want to dupe data to write to
so you would instead make a inventory singleton?
I don't think I fully understand what serialization does, care to explain? you mean adding [Serializable] correct?
That's a tiny piece of the serialization system
I usually just make them as a plain c# object, but if you've a one player game where you've a single inventory I could see some use.
Serialization is how Unity saves and copies data all over the place.. it's how data is saved in assets and scene files, and how it's copied when you call Instantiate, and how fields are shown in the inspector
ScriptableObjects are just one type of asset
so what does adding serializable do?
Does anyone know how the "tick" system works in Unity?
Marks a class as being serializable
Which one?
clearly, but what does that mean
i dont really know which one
does it just allow it to be shown in editor
It means Unity will be able to serialize it in all the contexts I described above
Showing in the inspector is just ONE of the things I mentioned
See again #archived-code-general message
Sure, but there are a bunch of ticks you could think of, i.e. network ticks, fixedupdate ticks and the ones you already said.
So I'm not sure which one you want to know about.
oh yeah, fixedupdate and update ones
you can set the tick in project settings
thx guys
With nice diagrams and everything
Think of a clock ticking
That's it
Just a thing that happens repeatedly at a constant interval
ok thanks
its Update called every frame or as much as possibel depending on your CPU?
Both. It's called every frame. Frames happen as much as possible unless you use vSync or other artificial limits
oh, ok, dumb question I guess
Hello, I'm following Jerry Tessendorf paper on simulating water. I'm a bit confused with complex vectors ("I hope that's how they called"). Anyways, I have formula for normal maps (attached picture). The issue is that I don't understand how to express i*k (the first part) , where k is vector with both real parts. Any, help would be helpful!!!!
You'd have to create a data type to represent complex numbers
You could make a ComplexVector3 type to represent complex vectors
It may consist of 3 complex numbers
I know that when u express real number in complex plain you get vector2, first part real and the second imaginary. So, now I would need vector 3 where 2 first numbers are real and last one is imaginary? Or do Ineed vector4?
K is vector2
Vector2 is a cop out
Make an actual ComplexNumber type
You could use Vector2 inside but you need to define the interactions properly because you can't just do operations on Vector2 like normal.
Cop out?
It's lazy
It just happens to be a struct that holds two numbers
So it CAN represent a complex number
But it's not going to solve any problems for you
you have to define the multiplication operator for imaginary number
you can use three vector2 btw, but you cant overload the operators of vector2
I think it would be much clearer and cleaner to make a custom Complex struct
And define all your operations/functions/operators etc as necessary
I'm a bit more confused with the mathimatical part, the programming part is clear. So if I have real number: 3, I can express it as 3 + 0i. How would it work with complex vector?
and you need to make you own Pow of complex number (e^(real part))*eular formula iirc
Yeah, this part is easy.
what executes first FixedUpdate or Update
thx
complex numbers are just numbers
where a vector of type float would be (float, float, float), a vector of type complex would be (complex, complex, complex) say
I think for complex numbers it's (float, float)
Oh you ment for vector
to stop things getting very messy I'd go with PraetorBlue's suggestion of implementing that complex type yourself and ensuring all elementary operations are what you want
But how we go from vector2 with both real parts to 2x vector3 in complex plain?
a complex number is just a number
you can think of it as a vector of two parts, but conceptually it's just a number
So, if we have 2 real numbers how we end up with 3 real numbers?
sorry @mental rover I dont get it, does Physics occur before Logic?
and i still dont understand the tick thing
you don't
Maybe you ment that we end up with 2x vector2, where 1st vector is for storing real numbers and second one is for storing complex?
you can have a custom struct
public struct A{
public static operator XXXXX.....
}
```then you can have a Vector of A
```cs
public struct Vector2A{
public A x,y;
}
Honestly I think you may want to start from the fundamentals of what a vector is and what a complex number is in the mathematical sense. It sounds like you're conflating that concept with Vector2/Vector3, i.e a 2/3 dimensional vector of type float in C#/Unity
The programing part is no issue, however I will do more research on complex vectors. Thank you anyways.
Anyways, I will try calculating this part twice first I will calculate for k.xi... and then for k.yi... As this will give me tangent and bitangent. @mental rover
if you are determined to not understand what a complex number is I'm sure you can find a way through computing the original sum like that
if it works it works right
I think we are misscomunicating due to my poor explanation.
I'm making a simple game where you bartend and talk to people. I was wondering how I should manage sequence of events like when you finish making a drink or once you talked to NPC 1 then NPC2 comes over and starts talking to NPC 1.
State machine? Like stay in that state until conditions are met then move on to the next state and repeat?
Or maybe an event system, like when something is done, tell some manager class and set something to true. Or a mix of both?
What would anyone recommend?
if it's intended as a scripted sequence of events, like a story narrative, a state machine that progresses through each step makes a lot of sense
trimmed of a lot of boilerplate to the point it's just an iterator, since likely it just needs to be in the form A -> B -> C -> D
Story narrative yep, and okay yes that feels right. Coroutine state machine that waits until conditions are met to move on. Then when it moves on the next state it runs all the stuff it needs (timeline cutscenes, other stuff,etc.) then awaits to move on til the next conditions are met (served X drinks, talked to NPC about X).
In my game players and enemies have a script to handle status effects. Status effects have indicators under the character to show the amount and all status effects have a sprite. What would be the best way to store the list of sprites? ChatGPT suggested a gameobject that isnt destroyed on load to store a list of the sprites.
Sorry thinking out loud - thank you
Scriptable Objects
GPT as useful as a sack of wet mice
how would i make it as scriptable objects? just have a sprite object for each status?
this sounds fine - there's a ton of abstractions and such you can inject into it. Some might be helpful to improve scalability, some just unnecessary fluff to overcomplicate, but you've got the core of the concept there that will work 👍
No just make an array of your sprites
any enemy or object that reference that SO has accesss to the sprites
no DDOL needed
// Calculate acceleration force
Vector3 velocityChange = wishVel - rb.velocity;
Vector3 accel = velocityChange * accelMultiplier;
accel = Vector3.ClampMagnitude(accel, maxGroundAccel);
// Accelerate towards desired velocity
rb.AddForce(accel, ForceMode.Acceleration);
Just a quick question -- do I need to account for Time.fixedDeltaTime for adding acceleration force?
not AddForce iirc
No, you shouldn't
You should never multiply any force by any deltaTime with AddForce
Alright cool just making sure 👍 thanks
@mental rover Although my communication was poor. It helped me to talk to somebody to understand few things that were missing.
Here is the normals generated.
nice one - that's looking a lot like a water surface 👍
Can't wait to switch from Phillips to JONSWAP spectrum to make it even more realistic. But I might spend left time for my bachelors work developing FFT (but this seems hard so don't know)
So it seems to be impossible to get Cinemachine to work in unity 5.6, is there a good alternative that works?
why are you using 5.6 anyway
There are specific builds for N3DS, which are not supported anymore
but its the only way to unity for n3ds
anyways,
cinemachine for 5.6 or alternatives?
Not sure I came into unity when cinemachine was already bought off, so never had to use anything else :\
Cinemachine was added in version 2018.1 it looks like (from the manual)
There isn't really an alternative afaik. Maybe you can see if early versions of the standalone cinemachine (pre-unity purchase) works
Might be something really old from the asset store, but I have no idea
playables
it uses playables back in 1.0, i just checked
there isnt a way to exactly use playables in five like in 2017 right
you can use 2017 for 3DS development
yeah but
its buggy as hell
afaik the lastest ever released n3ds was on five.six.six
sorry five and six keys are broken
some smart guy: it's better to keep on 5.6, 2017 is unstable because they haven't finish it, there is a lot of unknown issue and memory leak + the very last version of unity for 3ds released was on 5.6
i have a version from 2020 which is five.six so hes right
so you didn't personally tried it or for your use case ?
just word of mouth
hes some guy called ynox working on that sonic unleashed for 3ds, not sure if i should
I also love the whole "trustmebro" on the internet
i could try it though
just try it and test?
I can tell you he is wrong, I could screenshot the developers download page showing the SDK version but I won't (NDA)
aaaaaa i wish i had such an 3ds account
they dont allow nda 3ds anymore
so much stuff 'd be easier
just asking, but,
where can i even get this 2017
i only have 5.6.5 and 5.6.6
its not a public version
it was distributed on nintendo dev
but yeah its not downloadable anymore
you wont get that if you're not a reg. developer
weird question:
is it possible to write on the same line a <summary> of a var/function/... ?
something like c# /* <summary> is player on the ground </summary>*/ private bool _isGrounded = true;
i prefer in one line rather than above
same logic as
[Tooltip("Zipline")] [SerializeField] private LayerMask _ziplineLayerMask;
Hello, I´m having somme issues with the tilemap, when the player press a wall, it stick to it
Does anyone know how to fix the "collab service is depricated" error happening constantly? I just opened a new project and it is so annoying
are you using rigidbody ?
I have been able to fix the fact that pressing a wall would let you climb , but still happens that the player get stuck
In both, player and ground
remove the version control package
did you put composite collider
also you need player to be nofriction material then
or checkbox infront of you to see if its movable by the amount you pressed
did you bother googling it cause its quite common
I did and it's still doing it
I did, I can't figure it out
cant select nofriction material
yes
no you have to disable the option in Project Settings
Hello, I am trying to set the variable "questionItem" in line 47, but for some reason it gives me an error that basically says that questionObj is not set to an Instance of an Object (my guess is that it doesnt have a value). Can anyone help me fix this?
https://paste.ofcode.org/xuDAeTpdZutKm9fH2jgHsH
its not VC package the problem
you can
put it on the collider
had to be 2D physics material
ignore the "Answer.Instance", I am just trying to access a variable from another script.
In project settings it says version control not available when using collaboration
but I didn't check collaboration when I made the project
then you made the project at a time that unity had collab 🤷♂️
I am using 2021.3.15 but I haven't had this issue before, idk
did you make a 2Dphysics material
Rn im making it, 0 friction then?
Answer.Instance is null prob
Can you guys help me please?
#archived-code-general message
#archived-code-general message
show the full stack error
it isnt
also calm down and be patient
sorry im just in a hurry
well no reason to spam the channel for you personal problems
Thank you so much, I didn´t know about that
im not
Now its working fine
constantly reposting asking for help is sorta spammy yes
it hasn't been long..
give people time to read
and process the info..
alr alr
did you debug both of those ?
Debug.Log($"questionObj : {questionObj}");
Debug.Log($"Answerobj : {Answer.Instance}");
ill add that in OnNext() ?
Answer.Instance.questionItem = questionObj.gameObject;
3 options
Answer is null
Answer.Instance is null
questionObj is null
Debug which one or more it is
also never use GameObject.Find
why
cause its painfully slow , awful and error prone
it works fine?
how can I access a child of an obj then
did you look it up should be first result
alr
though you would want to use Components direclty with GetComponentInChildren
but theres still a problem, AnswerObj doesnt exist
you still haven't shown how you assign it
and is it attached on an object yes?
its value is that script
wat?
and yes the script is attached to an obj
and is the object Enabled ?
Answer.Instance
at some point yes
is it after you click this method then
gimme a sec
cause thats prob why its null
funny thing is that this error occurs when theres no answer, so I think yes
what does that mean
one other thing, is the error reffering to Answer.Instance.questionItem or questionObj?
error
i meant
just put this script Asnwers.cs on an object that never gets disabled and try again
make sure no other copeis are there
it would be easier making an if statement
no it would be easier if you just didn't disable the singleton gameobject 🤷♂️
its disabled at the beginning, i click a button and i create an answer (4 max)
but this error appears when i dont create an answer and i switch to the next question
so i cant put it on an object and dont disable it at all, would be even more messy
but i can check if that variable is not NULL, right?
it works
yes but thats only putting a small band aid on gash
i fixed it
but, what else could happen?!
why would it be messy putting Answers.cs on a gameobject that doesn't disable ?
its answer.cs, trust me it makes more sense because it runs on every answer
trust you how? you're the one who broke it in the first place .. wdym runs every answer
runs on multiple objects
why
the whole system is brittle
why are you even using Update() instead of events..
when you are making a quiz in kahoot dont you want your question to have multiple answers, correct or incorrect that you can choose from
any ideas?
I made plenty of quiz games, none of them rquired such brittle systems
also GetComponent in Update is mega cringe and inefficient
doesnt really have a high effect on performance since I mostly used events
fix?
cache them ?
but doing things Event based in probably smarter.
Learn about events
you're already using them for buttons, no reason to do all this in update
okay imma fix it.
idk how to fix, know about this also. also cant fix it since im running out of time
you have to fix it by not making it null.. fix the logic that prevents you to keep that AnswerInstance object active.
alr, but it works! it doesnt need to be entirely bug-free, its a school project after all
why is it so bad?
basically its just not setting a "parent" question for nonexistent answers
wdym its bade because there is no point of making a singleton if you try to use before its active..
also this goes in #💻┃code-beginner
alr
Anyone familiar with orthogonal projection? I have the fallowing code, and it isn't giving the values I would assume.
public static Vector2 ProjectOntoLine(this Vector2 v, Vector2 lineDirection) {
// Normalize the line direction
Vector2 normalizedLineDirection = lineDirection.normalized;
// Calculate the scalar projection
float scalarProjection = Vector2.Dot(v, normalizedLineDirection);
// Calculate the projection onto the line
Vector2 projection = scalarProjection * normalizedLineDirection;
return projection;
}
Ah it was fine, I just wanted the component orthoganal to it(or aka the vector to get from v to the projected value.
Hey when I have a question for the new inputsystem where do i have to ask ?
3 channels down
How can I prevent default scrolling behaviour of ScrollRect? I don't want mouse scroll input to move content of the scroll rect.
Okay I am confused on how that is working. I have this version which is what all the math places show how to do it, but my normalized value one works the same as far as I can tell and I was supper tired when I made it. Does anyone know if there will be any issues with it vs.
public static Vector2 ProjectOntoLine(this Vector2 y, Vector2 v) {
float top = Vector2.Dot(y, v);
float bottom = Vector2.Dot(v, v);
return top / bottom * v;
}
Ah normalized ends up doing the same calculations. interesting.
so put scrollsensitivity to 0 no?
also not a code question
Couldn't know this without an answer.
well usually ui questions go in #📲┃ui-ux
Ok, will ask there next time, thanks
Does anyone know how I can convert a vector3 containing the velocity of an object into a quaternion that will rotate the object to face the direction it is moving in?
Quaternion has methods to do this for you
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
how do i make my character fall fasterwith rigidbodys built in gravity
increase rigidbody mass
try to decrease drag
Do you want only the character to fall faster, or all rigisbodies?
If so you could adjust the global physics factor in Player settings
its at 0
that worked thanks
I want to move my player as realistically as possible by using physics, because I want to be able to accumulate momentum by wall jumping, hitting an enemy etc. but I don’t know what the right way to do that is? I tried using AddForce() but that makes the player very slippery, and I still want the game to feel snappy
Anyone know how to help?
Maybe try changing the velocity directly instead of adding force, or use ForceMode.Impulse when adding
Well the problem with changing the velocity directly is that, yes, it does feel nice to move the player, but I can’t add any forces to push the player
But doesn't changing the velocity push them anyways?
And using AddForce(), even with forceMode.Impulse seems a bit janky because If you move the player an opposite direction it would take time to actually start going full speed
Whta if you reset the velocity to V2.zero before adding force, that way they get immediate feedback ?
Well my code in the beginning was this
currentSpeed * Time. fixedDeltaTime * (transform.right * horizontalMovement + transform.forward * verticalMovement).normalized + new Vector3(0, playerRB.velocity.y, O);```
Sorry I’m not sure how to put it in a code block
If I add a force, it would push te player for a frame, and the recorder to that velocity that I set
Use three of these symbols " ` " at the start and three again at the end of the code block
And at the start add '''cs
(only the cs part, not the ' symbols)
!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.
Lmaoo you can't find the correct symbol lol
It should be in the extra symbols tab on youe phone keyboard
` this?
Yess that exactly
Alright finally done
So that is basically the movement code you use for the player?
Yeah
And what's that "recorder" thingy you're referring to in here?
Ohh I see
So when that runs again in the update, the force you added is basically removed completely
And not taken into account
If I were to use AddForces on a player controller, I would convert the entire movement logic to just be AddForce
That's the only solution I can think of
And then clamp the max velocity to whatever you want
But then you'd somehow have to manage not clamping the high wall jump velocity you just added so Idk
Yeah exactly
That was the question
Oh well I’ll try to find a way
Thanks for helping
Okay good luck mate
One more thing; you could also just disable the movement entirely for some duration after wall hopping for example, or you could have a seperate Vector3 that you add any extra velocities you want and use that in the movement calculations
The latter actually seems pretty reasonable to me
Then lerp it in Update towards 0 so it dissipates as time goes on
@smoky salmon
Is it possible to change the saturation of a volume in post processing in a script
The volume itself does not have "saturation", it has a "weight" you can adjust which lowers the visibility of all effects on it, but if you just want to modify a specific effect, you would have to get a reference to that effect, for example "Bloom", then you could modify the values of "Bloom" by script, or whichever effect(s) your trying to change, this link may help: https://forum.unity.com/threads/how-to-modify-post-processing-profiles-in-script.758375/#post-5622541
My rotation issue never got fixed.
public class GameParameters
{
public static float fallingCubesJumpForce = 6f;
async Task InitializeRemoteConfigAsync() {
fallingCubesJumpForce = RemoteConfigService.Instance.appConfig.GetFloat("fallingCubesJumpForce", fallingCubesJumpForce);
}
}
can someone tell me if putting fallingCubesJumpForce inside the default parameter fallback when grabbing data will grab the 6f that was declared when the variable is declared?
It will get the value at the time of the call.
If you want it to use the value from when the method was called, cache it in a local variable and use that.
ohh so if there isnt a present value, it wont just take whatever that value would haev been beforehand?
Not entirely sure we're on the same page. The value used would be the current value of fallingCubesJumpForce.
Okay.
so bassically that declaration is correctly using whatever value is declared at the top as the default value?
Syntactically, yeah. Otherwise, not sure... Depends on the intention here.
okay perf. thank you for your help @cosmic rain
Uhm.
Log.Info("result.x = {0}", result.x);
Log.Info("result.x = {0}", result.x == float.NaN);
.
.
.
result.x = NaN
result.x = false
I think you want the IsNaN method
What type is x?
result is a vector2
Well, add that to the ten billion other situational things I have to remember
Ideally, you shouldn't be getting to NaN in the first place.
Yea not really sure how u get that in the first place tbh
You probably divide by 0 somewhere or something.
"
In C#, comparing a floating-point value directly to float.NaN using the equality operator (==) will not work as expected. This is because NaN (Not a Number) is a special value, and comparing it directly with the equality operator is always false. This is due to the nature of floating-point arithmetic and the fact that NaN is not equal to any other value, including itself."
I know why it is there
I just need to check for it and set it to vector2.Zero
Not equal to itself is a funny way of writing something
There is always someone like you, who thinks they know better. Not waisting mine or your time. This has solved my problem
We're usually trying to provide an optimal solution here, which is why we might sound picky at times. But suit yourself.
how can i make it so rigidbody2d.addforce acts like modifying the velocity, as in, there's no acceleration time or deacceleration time, the moment you press and let go of the arrow keys you reach max speed and slow down immediately
mainly trying to use addforce for movement instead of just modifying the velocity directly because later i want to add knockback with addforce
but if i modify the velocity directly its going to be a pain later
hello, I´m using the Cinemachine2D camera to follow the player, but it keeps doing laggy glitch things with the sprites
Thats the both cameras config
trying changing the update method and see if it fixes the problem
had a similar issue
I changed it but still got the same glitchy effect in the bullets
are the bullets moving with force or are you adjusting the position in update?
Force
try setting the rigidbody to interpolate if its not set already
and the player movement is inside the update function?
the glitch might be because your player movement is in update but your camera updates in fixedupdate
If its on fixed update it bugs the player
not sure what it is then do you maybe have a pixel perfect camera attached?
how do I see that😭
Never used this camera before
it looks like this
camera settings are annoying it could be anything
Is there a way to get information on an animation state that isn't the current or next one?
Meh , it fixes the bug when you increase the projectile speed , so might use that
which forcemode are you using
Do you mean by true or false?
No, I mean the actual information like whether it loops or its length
Well, now seing the code it seems that force is the name of the var, so I migth not using it , however here is the object
wait that isnt
i mean the forcemode you set by code
with AddForce()
I just set the direction, I was wrong
I dont use AddForce
can you send the bullet scritp
shouldnt be the code that moves the bullet inside the bullet script?
!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.
ops , didnt knew that
It is the bullet script
i only saw the start method and an empty oncollisionenter2d method
The bullet itself gets the direction when you create it , dunno how to explain it
Don't explain it. Share the code.
*if you can't explain it, share the relevant code.
Probably a dumb question;
I want to make a game that's like a super simple top down 2D shooter (like Vampire Survivor but even simpler).
I want the enemy that kills you to activate certain events (like a cutscene)/be reported in the end (killed by X) and have the enemies have variety in whether they can shoot bullets/not, how fast they can move (or no movement which I assume would just be a variable = 0) and if they can be dodged through.
Would I use scriptable objects to make the various enemies here? I've honestly always had trouble figuring out what's the best way to handle different enemy types that share very similar codes/things.
ScriptableObjects are perfect for defining different values for enemy types.
That is one of their prime uses, is defining varieties of something
Hmm. Thank you!
Honestly even stuff like enemy spawn and accounting for each enemy with simple AI and health is kind of new for me. I'm coming back to unity after like 3~4 years and the last thing I worked on was 1 VS 1 lol.
Anyone here tried builiding an Application for UWP from Unity?/
UWP ? isnt that like dead
yeah but like I am developing an AR app with an external camera connected to it so that's why and no UWP is used to develop applications for Hololens
Does someone know how to fix this error, it comes up when removing items from a list and have that game object with the list selected in the inspector.
ObjectDisposedException: SerializedProperty Stock.Array.data[7] has disappeared!
UnityEditor.SerializedProperty.Verify (UnityEditor.SerializedProperty+VerifyFlags verifyFlags) (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <1b5a54bf0ae04c9abb7f7c64341a4384>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <1b5a54bf0ae04c9abb7f7c64341a4384>:0)
Show how you remove the items
📃 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.
Hi, i am kind of struggling with positioning my Gameobjects correctly, i am not sure why it will not respect the z position. i instantiate a car gameobject using this script.
public GameObject GetRandomCardFromCardSafe()
{
int randomIndex = UnityEngine.Random.Range(0, cardSafeCards.Count());
// Return a random card from playerDeck
GameObject randomCard = Instantiate(cardSafeCards[randomIndex], Vector3.zero, Quaternion.identity);
Debug.Log("Random Card From Card Safe: "+ randomCard.name);
return randomCard;
}```
and i further modify them for this specific scene cs instantiatedCard = deck.GetRandomCardFromCardSafe(); Debug.Log(instantiatedCard.name); instantiatedCard.SetActive(true); instantiatedCard.transform.SetParent(transform); instantiatedCard.GetComponent<CardMovementHandler>().enabled = false; instantiatedCard.AddComponent<Drag>(); instantiatedCard.GetComponent<RectTransform>().position = new Vector3(0,0,0);
but every object i instantiate this way ends up with z -935.3074 while i would love it to be 0. i have tried everything i could think of and google thought of.
these are the components of each card gameobject if it is any help
The Z position shown in the RectTransform component is anchoredPosition, not position
i did try using that and it didnt work either, sadly
if you just don't touch any of the position properties in the prefab it gets instantiated in the same position as in the prefab
manually changing it in the inspector to 0 works tho.
as its being instantiated out of a do not destroy object with completely different position values i think something weird is afoot here.
oh now that this stupid scene is working, i had another issue with Layout groups, i am using them to position my objects in a nice grid regardless of how many i want to present, but i have been struggling to get one to update when i add new objects, it will update only once a second object has been added. My google results usually brought me to deprecated docs.
i simply set the parent of the object i am moving to the new sorting group.
Do you have a ContentSizeFitter on your groups?
anyone here have any idea about how to configure multiple display for UWP build
i do not
Are thos scroll rects? If they are I highly recommend you to add those to your layouts
Then when a card is changed/added/removed use the static LayoutRebuilder class that Unity provides
Use a method like MarkLayoutForRebuild() with the layout root's rect transform as the parameter
ForceLayoutRebuildImmediate() also works but it is more expensive so use it only when you have a lot of nested groups
normal recttransforms, we have sized the content to fit the cards
i though ForceLayoutRebuildImmediate() was not in the current unity version anymore? 🤔
But can/should the content size be modified dynamically?
From the video it seems it should scale dynamically
wait, the card object or the layout groups?
It is, at least in 2022
The layout group needs to rebuild so use layout rebuilder in them
Or did you reply to the other question
this one, sorry
No, the cards' sizes should stay constant, only the layout groups' "content" objects should be scaling
So if you want them to scale, add the contentsizefitter to the Contents and config the appropriate fields
the text should remain readable so i am planning on making the group scrollable
This would also be more appropriate discussion in #📲┃ui-ux than in here I believe, but whatever
Then scale
~~ Hello, does testing steam achievement can be done directly from Unity? I already called Steamworks.SteamUserStats.SetAchievement(apiName) and Steamworks.SteamUserStats.StoreStats() but my account doesn't receive the achievement.~~
~~I also already added Achievement in steam works and publish the change. (they are hidden though) ~~
nvm it works. I need to restart steam first though.
it seems like its still in Unity, even though the docs kind of make it seem deprecated. Thank you.
Yeah, it could seem a bit deprecated because there's the newer and better UI toolkit Unity tries to feed to us so
Sorry I forgot to send it again
using UnityEngine;
using System.Collections;
using UnityEngine.UIElements;
public class Bullet : MonoBehaviour
{
public Vector3 mousePos;
private Camera mainCam;
private Rigidbody2D rb;
public float force;
void Start()
{
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
rb = GetComponent<Rigidbody2D>();
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos- transform.position;
//Rotate
Vector3 rotation = transform.position-mousePos;
rb.velocity = new Vector2(direction.x,direction.y).normalized *force;
float rot = Mathf.Atan2(rotation.y, rotation.x) *Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0,0,rot+90);
}
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.CompareTag ("Player"))
{
}
else
{
Destroy(this.gameObject);
}
}
}
Now explain it, because I don't remember what it was about...
It happens that the bullet lags, but its not a camera thing, i´m moving the bullet without force, just point A to point B
but the direction is the same once the player shoot
Is the bullet rb using interpolation?
Non
Try enabling it then
Physics updates the position of your rb every fixed update, however the game is rendered in the regular update which can happen more often. That's why objects moved by physics look jittery - they're not moving continuously. Interpolation fills the gaps by moving the rb in between fixed updates as well(interpolates between the current fixed frame and next fixed frame position in the regular update).
public class PlayerMovement : MonoBehaviour
{
private float horizontal;
private float speed = 8f;
private float jumpingPower = 16f;
private bool isFacingRight = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}
For some reason my jump is not working, is there anything I need to add or remove? Just to let you know I also added the Rigidbody to the Rb
Is using a lot of properties good or bad habit?
What's that script for? A manager of some sorts?
Yep, it's manager.
Not related to properties but what stands out to me are the factory machine part class names. I don't think it's common practice to use Prefix_ClassName, people often use namespaces to group classes instead
Like "namespace <game name>.Factories" at the top of the class
You're right! I will make it like that. Thanks for advice. So there's nothing wrong about using that much properties right?
Typically, if your game relies heavily on public properties, it couples your code to the manager and this is bad for maintenance/refactoring later
Is that for holding prefab instances for other scripts to instantiate?
But then again for example I'm using a static class for holding loaded data for other classes to reference & use like this
It's kinda like, i have machines in production setup. Each Production Setup contains five machine. So for creating multiple production setups, i use that way.
But that's like the only way in my case so
Hi, so I've got a mod for a unity game, and the error:
[Warning: Unity Log] The referenced script (UnityEngine.XR.Interaction.Toolkit.UI.TrackedDeviceGraphicRaycaster) on this Behaviour is missing!
occurs when trying to run the modded game, I don't get any errors building
UnityEngine.XR.Interaction.Toolkit is in the project references too, could I get some pointers in the right direction to look?
Then I think properties are fine for that case
Because they group them to the production step, which is quite necessary
we do not discuss modding games here
Thank you so much for your help.
well I suppose back to unity, maybe I need to install this package? How would I install it for use in visual studio?
I'm having issues initializing a jagged array
show code
chunks is declared elsewere but i added it here to not confuse
Chunk[][][] chunks = new Chunk[RealmSizeInChunks][][];
Debug.Log(chunks.Length);
for(int i = 0; i < chunks.Length; i++)
{
chunks[i] = new Chunk[RealmHeightInChunks][];
for(int j = 0; j < chunks[i].Length; j++)
{
chunks[i][j] = new Chunk[RealmSizeInChunks];
}
}
I mean, i did the same thing before i added a new array on top of it for 3D
And it worked
Maybe i broke something without noticing
what error are you getting?
IndexOutOfRangeException anytime i try doing anything with it
is Chunk a class or a struct?
it looks like that when i use a breakpoint
class
Tried making it a struct but caused issues i didn't want to have yet
you are using both Height and Size, is this correct?
yes
Debug both RealmHeightInChunks and RealmSizeInChunks
Oh its 0 somehow
can anyone help with mine?
I even set the values manually and it works
public variables?
private
