#archived-code-general
1 messages · Page 362 of 1
ah osteel said it perfectly
and push to git
yeah ignore the stackoverflow philosophizing and focus on your silly lines
wait wait
wanna show you the unreadable code
mhmh yes
my favorite, ternary operator
the design is very human
ok maybe i'm the only seeing it unreadable
Just moving the index into its own line would make it way more readable
The whole ternary thing I mean
is there any way to make a mesh collider deform to an armature? I need this for a game mechanic where a player can walk on the surface of another player that can move their body around (controlled by the armature)
You can parent the collider to a bone
Im not sure if this is the right channel, but my game cant work without a mesh colider that deforms around the armature like the mesh does, unless there is some other way to calculate collision with mesh surfaces, like using raycasts without a mesh collider to get the tri normals/verts
the armature?
I currently have this setup
Yeah
the armature doesnt appear as a mesh tho, and using the model as the mesh isnt deformed to the armature
One you mean’t deform vertices of the collider?
yea
thats what I want
I want the collider to deform/move with the armature
so that another player can walk on its surface
Not really an elegant way
not approximating using primitives btw, not an option for the precision needed
unless using a primitive teleported to the tri underneath the player
Why are you torturing yourself?
because this is the main game mechanic 😭
I thought unity had deforming mesh colliders, and now my game jam submission is screwed
as long as each limb has a collider and is a child of a bone the collider will not move with the armature
Fucking simplify it.
Pretty sure it bakes the collision data.
No, I need a player to be able to walk all over the surface, and its gonna be small enough that I would need about 1000+ primitives for it to be half decent
is there no way to re-bake the collision data on every frame?
idc if its really expensive
you only need 1 box collider for the torso of the elephant
Unity doesn't like dynamic mesh colliders
Not elegantly
and 2 capsule colliders for the legs
You could set a bunch of background async tasks to constantly bake it, like tie down a thread to constantly do it
is there a way nonetheless though?
What specifically are you trying to do?
you do not need a ton of primitives to get the desired effect
and unity colliders do not like being dynamicly changed
my game is a puzzle game, where you play as an ant that can walk on any surface, and an elephant, that can move their body and trunk to make bridges and stuff for the ant
can you not at least get the tri normals for a dynamic mesh
of a raycast intersection or something
I just need to find the exact collision of the dynamic mesh at 1 point
the rest doenst need precision
Your going to have to come up with your own solution if you don't want to bake the mesh--you can partition it using a BVH but that's really overkill. Probably best to stick to a solution with primitives
Primitives is fine for that
as stated before you do not need a ton of primitives to get your desired effect
not "thousands"
It is a game jam so no one will really care it doesn’t use realistic collision
?? how so?, the ant would phase thru the elephant multiple times
you are zoomed into the ant, I dont want it to look like its floating
one primitive for each limb
if it's really small you can dynamically generate the primitives only around the ant
yes, this is what Im asking for
but that requires mesh data
I can easily find the primitive positioning/rotation whatever if I can get at least one tri directly below the ant
I just want the positioning of one tri of the skinned mesh
detected by a raycast
or you can have a bunch of primitives already on the elephant and then turn them all off and only then turn them on if they are close enough to the ant
there are too many moving parts
is this really so impossibly hard to find?
it doesnt matter if they move or not
as a general question
Is this really a realistic goal for a gamejam if it's this difficult to implement already?
I might consider doing this as a seperate project, Idfc if it gets submitted or not, Im not asking for critisicm, just tell me whether or not you can get the fucking tri data for one tri of a dynamic mesh
its a yes or no question, enough with the primitives already
It's hard finding the triangle closest to the ant
You need a spatial data structure to find it efficiently
ok, good to know, but it is accessible?
yes, you can loop through all triangles to see if they intersect with your ray if you do not care about efficiency
good to know, thank you :)
what kind of method would I use to access the tris in the first place
keep in mind it will be extremely slow to go through all of the triangles and find one that matches
I have some code in hlsl to get intersection between ray and triangle--Unity probably has a lot of overloads for a lot of the math
I dont mind math haha, I just dont know how to access the triangle data in the first place to do the loop check
Like how would I get the deformed mesh tri data in the first place?
I'm not sure, I'm not very familiar with animator, but if the deformed data's on the GPU this'll be even harder because your going to constantly have to read it back
oh ok, thanks for your help, if I can only get it thru the gpu pipeline, will I have to check every tri in the scene?
If you want to complete this task quickly, otherwise you'd have to define a BVH, or R-Tree to sort through them, something similar to the underlying physics tree unity uses
ok, good to know, Ill find a way, my scene isnt that high poly and if Im accessing every tri in the scene then I might as well just use it as a generalizable method thanks :)
I appreciate your help!
At least do it in a job if you're gonna do that, glad I could help!
a job? what do you mean by that? btw I checked and there should be a way to access just SkinnedMeshRenderer data
It’s a system to speed up your code through parallelization and *heavier compiler optimizations(with burst)
Ill look into that as well, thanks for the tip
@unreal ingot This exists btw
https://docs.unity3d.com/ScriptReference/SkinnedMeshRenderer.BakeMesh.html
Lets you read the deformed mesh back into the CPU
Actually, it just does the skinning on the CPU
Performance will probably be ass though, especially on such a dense mesh
YAY
how to set prefs so that txt files don't open in rider but instead in the windows-default editor
In the External tools menu in unity change the tool from in the dropdown
(Note that Visual Studio is not windows default. You will have to install it if you have not already)
If you mean in windows itself, right click a text file and click open with... and select whatever you want. Should ask if you want a default
There is another way I would need to look up, but that is beyond what is on topic in a unity server. Googling "change default program" will get you many results
I am making a multiplayer game. When the player's camera moves the character's head, it goes inside the head and sees inside the character's head. I tried to make the camera a child of the character's head, but this broke the camera. Below is my camera code.
using UnityEngine;
namespace heist.Core {
public class PlayerCamera : MonoBehaviour {
private PlayerInput playerInput;
[Header("Camera Settings")]
[SerializeField] private float cameraSensitivity;
private float xRot;
[Header("Camera References")]
[SerializeField] private Transform playerBody;
private void Awake() {
playerInput = GetComponentInParent<PlayerInput>();
Cursor.lockState = CursorLockMode.Locked;
}
private void Update() {
Vector2 look = playerInput.lookInput * cameraSensitivity * Time.deltaTime;
xRot -= look.y;
xRot = Mathf.Clamp(xRot, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
playerBody.Rotate(Vector3.up * look.x);
}
}
}
Hey anyone have any ideas for simulating a crystal ball? I have a shader that renders the camera out put to the material and I have that applied to a ball, but as you can imagine its pretty flat. I have the camera rigged up to my head so I can simulate the parallax but it would be nice to have a sorta faked volumetric effect liek you would expect.
I have some platform assets that can be tiled together (so that I can make platforms of all different lengths). Is it better to make platforms a scriptable object or is it better to make several different sized prefabs of platforms?
public struct Range<T> where T : struct, IComparable<T>, IConvertible { }
I have a PropertyDrawer for this struct. Is it possible to make T be draggable with a mouse, as it's done with Unity's serialized float, int etc.?
i did that, still didn't work until i restarted the editor. thx
Here's some ideas, if you project the sphere's normal for every fragment onto the screen-space plane so that you get a 2D vector, you can have it so (0,0) is the center of your screen and (1,1) is the top right corner and (-1,-1) is the bottom left. You can then use those coordinates to sample from your texture for a spherical distortion effect.
For mist, you can just overlay a mist animation, or use the depth texture from your camera and multiply the albedo by the inverse linear depth. Then you displace the depth with a noise map to animate the fog somehow.
Hi guys Is there a way to make the render target of a Camera (so a Render Texture) to be pixel perfect when using a perspective camera?
Probably not possible.
Hi all, quick question. Does anyone happen to know, if i alter a prefab programmatically during runtime, will it alter that prefab for all other objects that reference that prefab? Or do all objects carry their own instance of the prefab? Also will those changes be reverted aftere exiting play mode?
all changes made in runtime will be reverted when back in play mode, also alter it in what way?
like for instance
some_prefab.transform.position = Vector3.zero
i.e. just altering any one of its components
if you modify one object in a prefab like changing components in an object and not its children, only that object will get changed. if you are moving a parent object obviously the children will follow respectively
if you have any more questions about prefabs please consult the docs
im double checking rq
ah then yes every object in a prefab is an instance
Why does adding this function to my detection cause unity to crash?
private void OnMouseOver() { if (Input.GetMouseButton(1) && hasntChanged) { grid.PlacePlayerSpawn(x, z); } }
It works almost always for placing the spawn points, but clicking to remove them will sometimes work, sometimes do nothing, and sometimes freeze unity.
doesn't seem anything in code would crash
If it crashes the issue is probably in the PlacePlayerSpawn.
maybe if it were recursive or something
I just rewrote the entire thing and now it mostly works
it dosent crash, although its sometimes unresponsive
Sounds like an temporary infinite loop or a recursion or something. Hard to say without seeing your code.
the left click one (OnMouseDown and OnMouseEnter) work perfectly
!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.
using UnityEngine;
public class GridSquare : MonoBehaviour
{
private Grid grid;
private int x;
private int z;
public bool hasntChanged = true;
public bool hoveredOnSquare = false;
private void Update()
{
if (!hasntChanged)
{
if (Input.GetMouseButtonUp(0))
{
hasntChanged = true;
}
if (Input.GetMouseButtonUp(1))
{
hasntChanged = true;
}
}
}
public void Initialize(Grid grid, int x, int z)
{
this.grid = grid;
this.x = x;
this.z = z;
}
private void OnMouseDown()
{
// Change the grid square when the mouse is first clicked
grid.ChangeGridSquare(x, z);
}
private void OnMouseEnter()
{
// Check if the mouse button is still held down
if (Input.GetMouseButton(0) && hasntChanged)
{
// Change the grid square
grid.ChangeGridSquare(x, z);
}
}
private void OnMouseUp()
{
hasntChanged = true;
}
private void OnMouseOver()
{
if (Input.GetMouseButton(1) && hasntChanged && hoveredOnSquare)
{
hoveredOnSquare = false;
grid.PlacePlayerSpawn(x, z);
}
if(!Input.GetMouseButton(1))
{
hoveredOnSquare = true;
}
}
}
I see. Seems to be calling all kinds of API as well as instantiating new objects. Might want to profile the hangs with the profiler.
not really sure what to look for
but I dont see any obvious spikes or anything
it just dosent register the click
Ah, so it's not a performance issue..?
I might be crazy but it seems more responsive if i wiggle the mouse around a little
no its at around 1000fps, and even the biggest spikes are still 200+
Add some logs at the very start of the callbacks to see if they are called at all.
like to the onMouseOver calls?
Yeah, whichever you think don't register.
private void OnMouseOver()
{
if (Input.GetMouseButton(1) && hasntChanged && hoveredOnSquare)
{
UnityEngine.Debug.Log("RMB Clicked");
hoveredOnSquare = false;
grid.PlacePlayerSpawn(x, z);
}
if(!Input.GetMouseButton(1))
{
hoveredOnSquare = true;
}
}
Okay so on the clicks its not registering, I dont see the "RMB Clicked" message
mightve found the issue
private void OnMouseOver()
{
UnityEngine.Debug.Log("MouseOver");
if (Input.GetMouseButton(1) && hasntChanged && hoveredOnSquare)
{
UnityEngine.Debug.Log("RMB Clicked");
hoveredOnSquare = false;
grid.PlacePlayerSpawn(x, z);
}
if(!Input.GetMouseButton(1))
{
hoveredOnSquare = true;
}
}
this entire function dosent get called when it dosent register
so the OnMouseOver call isnt always working
You should log at the very start of the callback.
wdym
Was referring to the first snippet, where you put it under the if statement
ah
yeah
did that, its not getting called
that seems like probably a more annoying issue than i was hoping
If it doesn't get called, when it should, something is probably obstructing the object. Might want to have a look at the event system debug info.
ah
figured it out
this little white dot on the green object dosent count as part of the object for some reason
even though the edges do
oh yeah lol it still had a collider
problem solved
thx
i am using NavMeshSurface for my game, since i have randomly generated dungeons and i need the navmesh to build at runtime, but after a while the navmesh is building too high and weirdly, and it is very hard to recreate the bug, i just use:
surface.RemoveData();
surface.BuildNavMesh();
to build the navmesh, does anyone happen to know what is causing this and how to fix it?
doing what?
autocomplete doesn't say anything too
Then you have declared your own class called Input and that's conflicting with built-in
This is not the correct type
what is it supposed to be
remove this import
When you type can you not select the namespace without thinking? Double check that it's valid before forging ahead
no yeah I know
but that's the only 'input'
it worked for me earlier
on a diff project then I made a new Class Library on Net6.0
and this is happening
same code and everything
different project
No, it would not have
I am not familiar with how referencing engine code from class libraries works
well it literally did
Show that code with the Windows namespace
Or just... try using the right one here (UnityEngine)
See how they are the same?
I don't believe you can use .NET 6.0 with Unity at all?
What's the difference? The .NET version?
Honestly, so blurry I cant read. I see that the usings go to 13 on the second but 12 on the first
But yeah, likely what vertx is saying because I don't see the windows namespace like shown above
Well Unity doesn't use .NET 6.0, so if you "made a new Class Library on Net6.0" then I can understand why it wouldn't be able to work with Unity's code. But I'm not familiar with this setup enough to know where the problem is
https://docs.unity3d.com/Manual/dotnetProfileSupport.html
Is this for modding?
how can i make an event listen to
component.enabled = true;```?
apparently event cannot directly + this
Put an event in OnEnable and invoke it. Listen to THAT
.enabled is not an event, so yeah you cannot subscribe to it. It is a property
ok i gotta explain it more i guess
Also, events don't listen to things. Things listen to events. Not trying to be a pedant. That is an important thing to keep in mind
as part of our app features, we allow users to watch videos, were doing this with unity built in video players
however, we noticed that if users devices are weak, if the app got a hiccup, or somehow these component got disabled, or users out of focus for an extended time
even when this component get enabled again, the video will not play anymore
ofc gameobject is always active
so , to handle this, i need "video player" to be enabled, and call video.play() everytime when the component is enabled
ofc gameobject is needed as well, but who knows if only the component get disabled but not gameobject
i need two situations call play() as well
or one
aight looks like void update is the only way to go
Hello, I have code in a 2D game where I want the character to search an object for scrap. I want to scavenge enemies, and sometimes when you kill them they overlap which leads to both enemies being searched at the same time. To stop this I have a list of GameObjects when I enter the collider with the search area to add the searchable object to the list and when I exit the collider to remove the object from the list. I want to also remove the object from the list once it's been searched. I think I have all this in there right, but for some reason every time I search the object, it says out of bounds, I only want to search list[0] and when I'm searching it I pause the editor and the object is in the list, I don't understand
Without showing your code who knows
does ontriggerenter2d require the gameobject w/ the script to have the trigger collider, or the collider that it hits?
It works for both
There also needs to be a Rigidbody2D on the one that's moving
To add to that, it gets sent to both colliders involved in the collision (as long as they HAVE OnTrigger methods in a script attached to them of course)
Ohh, alright, thank you so much
guys does anyone use prometeo car controller? I am using that + wheel colliders and I've got the physics right for everything except when I reverse. While reversing at high speed, if I change the direction even a bit, the whole car starts spinning
I dont understand what I should change
Anyone know if their is a way to stop automatic tile refresh for a tile map?
figured it out, create a new scriptable tile and override its refresh method to do nothing.
Great solution
Thanks!
What is the best way to check whether the code is being compiled in Unity on any device? If code appears in normal C#, it should not be compiled
Simply #if UNITY?
Can someone tell me why this script that is supposed to work every time a key is released works only sometimes?
void Update()
{
if (Input.GetKeyUp(KeyCode.D))
{
rb.AddForce(new Vector2(FrictionFactor * -MoveSpeed, 0), ForceMode2D.Force);
print("Worked");
}
else if (Input.GetKeyUp(KeyCode.A))
{
rb.AddForce(new Vector2(FrictionFactor * MoveSpeed, 0), ForceMode2D.Force);
print("Worked");
}
}
i figured that before it didnt work because it was in FixedUpdate and not Update which made it work more often but still not every time it is released
the easiest thing to check first: currently with how you have it set up, you wont be able to register the A input if you release D on the Same frame. is that desired behavior?
Let me check
the thing is that even when i release only A for example, it doesnt work
i dont get a message printed
wait
Debug.Log not print
print wont go to the console
or at least not the unity console
weird
but let me try
oh yeah it works like a charm now
i knew it wasnt print but im coming back after years and didnt remember
If UNITY keyword is not defines, then code inside would not compile.
Yeah, I just discovered it
Any ideas on the best way to check it, both for the editor and build?
MonoBehaviour.print calls Debug.Log and is exactly the same. Can be used only by MonoBehaviours
Out of curiosty, are you trying to compile code from a build?
I didn't know that, handy!
I am trying to make a struct, useable in both normal C# and Unity
namespace System
{
#if UNITY
using UnityEngine;
#endif
[Serializable]
public struct Range<T> where T : struct, IComparable<T>, IConvertible
{
#if UNITY
[SerializeField]
#endif
private T _min;
#if UNITY
[SerializeField]
#endif
private T _max;
// ...
}
}
But it doesn't compile now
oh thats a cool idea!
This seems to work, but I don't know whether all platforms are included
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_ANDROID || UNITY_IOS
[SerializeField]
#endif
might be wrong as I have only messed with macros in c before, but could you define your own as the conjunction of the huge list of editor macros?
not the best for longevity but might work?
You could define your own keyword in the unity project settings. Unity would make sure to include it when it builds the project.
C# directives allow you to selectively include or exclude code from compilation, based on whether certain scripting symbols are defined or not defined
I have added a custom symbol, but how do I define it?
having that means it's defined by the compiler when it compiles your code. you've taken the necessary action
How do I and my compiler know what MY_SYMBOL does?
Is there a way to only display a variable in the inspector? Like [SerializeField] also allows you to change it, but I only want to be able to see it and not change it
Unity passes it to the C# compiler when it compiles project sources. Source code itself declares conditionals wherever. You're the one who defined the symbol, so ideally you know what it's going to be used for.
Yes, create a custom attribute and in it's OnGUI method, don't apply modified properties on end change check
If I want it to be true when the code runs inside of the Unity's editor, how do I do it?
you've taken the necessary action
Does it compile only inside of Unity, and is ignored outside of it?
if you don't define it in your C# csproj or pass it in with DefineConstants, then yes
I see, thanks a lot
Inspector: the rotation is set to -80 euler degrees
transform.eulerAngles: 
Is there supposed to be a question with this? Theres no memes in this server.
You also arent supposed to rely on the values you see in inspector, or the values from eulerAngles. Rotation is stored as a quaternion. Converting it back to euler has no guarantee that itll be the same euler angles you gave it. It'll be the equal rotation though
ok gotta shut up
Hi, im trying to install this package but im getting this error, how can i fix it?
I suggest you click on the link publisher support and ask them
Hello, I am trying to create a scene masking animation that covers camera on scene change. I am using Addressables to load a new scene and the .complete function to detect when the load is complete and when is the right time to unmask the screen. However, I'm having the problem that everything invokes fine, but loading the FPS drop causes the unmasking animation to not display or display in a small amount of time. Do you have any idea how to make this work? Thank you. 🙂
- the animation is created so that objects come from the side of the camera and cover it, and then uncover it by going to the side
- maskig is done via ui toolkit
depends on how it's set up but if you start the animation on the frame the scene loads that may be a long frame if you have a lot of stuff happening in Start methods so maybe you could just delay it a frame or more? probably worth checking the profiler to see what exactly is taking up the time on that frame though
First of all thank you very much, that you are trying to help me! 🙂 I already looked into profiler and you can saw it in the picture below, "Removeee" is the function that calls screen unmasking. My first idea was, as you wrote, to delay the unmasking by e.g. 1 second, but then I thought, what if it would not be enough for some device and the animation would not be shown anyway? But that's probably a small chance.
that 1.5 second frame you're on includes scene integration so i guess the callback must be happening at the end of the frame the scene finishes loading - so if the following frames after loading aren't particularly long, maybe you only need to delay a single frame to ensure the first update of the animation has a sensible delta time?
right now if I am changing scenes I have three spikes (each spike has own screenshot)
- first spike is caused by editor loop (first image)
- second spike is caused mainly by loading scenes, in that you can see where is right now called "removee function to clear screen) (second image)
- third spike is caused by playerloop etc.
- The editor loop is not gonna be present in a build, so you could probably ignore it.
- In the second screenshot there's a lot to unpack. We can't see a lot of the stuff(you should use the hierarchy mode sorted by cpu time instead of the timeline). But at the very least 900ms are taken by object's Awake/OnEnable and garbage collection. All of these you can optimize or spread over several frames.
To investigate the third one, you'll need to profile with the hierarchy mode and look through the relevant code.
if you can identify any expensive Awake or OnEnable methods there's also the option of just waiting until they're done somehow (maybe have an event or something at the end of them to notify the loading animation)
Thank you very much, I will look into it! 🙂 If I may ask, I'm trying to mask the screen using the UI animation toolkit, where I have several leaves that cover the screen. Then addressables.LoadSceneAsync is called to load a new scene. But I can't seem to find the ideal "time/place" to call back the animation when the leaves leave the screen. Currently I used addressables.LoadScene.Async.Complete or start function of script in newly loaded scene, to call remove leaves animation. But thanks to spikes animation is not visible or is visible on end for "millisecond". I will try to remove this spikes, but from my experiences some "loading spike" will appear anyway. So would you try to delay it by some general time/ single frame or use some another way? Thank you! 🙂
Call it when you know that the scene is fully loaded and done initializing
You can be sure that by the next frame after awake is called, the initialization is complete and there wouldn't be spikes anymore(unless you initialize of several frames)
This is not exactly a coding related issue, but I am unable to build my game for either Windows or Web. I get this error "UnityEditor.dll assembly is referenced by user code, but this is not allowed.", but I'm quite sure that I'm not doing that (anymore). This is in the latest Unity 6. Does anyone have any ideas why this might be, or how I can resolve it?
@thick terrace thank you both, you really helped me ❤️ I am going to look into it! Have a nice day and happy and successful developing 🙂 ❤️
You'll need to share some actual error details.
anyone has any advice regarding Popup window management?
I have a scene manager, but I can't find anything to manage popups properly.
I tried making them their own subscenes but it was really hard to open and close, With prefabs it's easier but I couldn't find a nice way of managing them.
Any advice/libraries arround? 🤔
Have some kind of DDOL popup manager that has all the required objects underneath. That's it basically. The rest is up to how you want to implement it.
so the objects are always alive? 🤔
you don't instantiate nor destroy them?
it depends what's in them, if they're simple you might find that easier, but if they have images or anything like that you might not want to keep them in memory...
i've found some kind of state stack system usually works pretty well for managing UI states, so you can push/pop popups on top of the normal UI state and handle animating them in/out with events when you enter/exit states
Yep.
I like that kind of state stack, I will see if I can code something up 🤔
So I ended up figuring out a solution to this entire conversation from 3 days ago. For context, I noticed that with 10 Agents (Just 10.) We were dipping below 50FPS in some cases. Another developer mentioned that having more than 10 agents is something he may want in the future so I wanted to address that.
I ended up making the AI both dumber, and smarter at the same time.
- First I check to see if the AI can shoot the player from where its at. If it can, its in a "Combat" state.
- I then check to see if it can reach the player from where its at. If it can, its in a "Combat" state.
- If its unable to do either of those things, it wanders.
(Thats the point where its dumber. If there is somewhere where it can reach the player to shoot the player, it wont move there anymore. However, 9/10, if the player can shoot it, it can shoot you.)
In Combat State, its now a bit smarter.
- It will first figure out if it can reach the player. This will return one of two things, either a Partial Path (EG: Stops at a gap/wall.) or the players position.
- I then grab a random point in a radius around the end of that path. (Donut shape to be specific.)
- From there, I then do a Navmesh Raycast from the player to that point.
- I then set the destination to where that Raycast hit.
The reason for the Raycast is so that if the player is standing next to say, a wall in a tight hallway, the AI doesn't try to walk to the otherside of the wall.
Overall, seems to be a good approach and seems to be giving me somewhat expected results. But more importantly: I can now handle 100 Agents in combat state with around 90FPS (I'll never have 100 on screen at once.) and 144 (Vsync Capped) in Wander State. (Wander was even worse previously down around 10 FPS.)
can you exclude certain components when using GetComponent in any way?
It's sadly very sparse, it's a linking error, but there's no actual code references. I've stripped out most of the imported code, and made sure to move my Editor component to the Editor folder, but the error persists.
what does the stack trace on the error show?
there isn't any. Because it's a linker error. I've stripped out some more imported assets and scripts, to see if that helps. I'll know in a few minutes.
Unity still builds faster than Unreal at least 😜
did you check the !logs?
It gives you whatever specific component you're asking for, so just don't ask for the component you don't want
im asking it for an interface, which both the script im using it on and the kind of thing im after, both implement
Ask for a different interface which only the thing you want has
I guess I have to make a parent class for everything that implements this interface apart from this one thing then
Why not just another interface
You can have an interface without any methods
Or better yet, use composition instead of inheritance in general!
But that's another conversation
i mean, ive got enough scripts to keep track of as it is without having to follow more
im well aware of composition vs inheritance, ive been taught it a couple times at uni already,
Sadly I'm still getting it, I've stripped all code with a reference to UnityEditor not in an Editor folder.
C:\Program Files\Unity\Hub\Editor\6000.0.15f1\Editor\Data\il2cpp\build\deploy\UnityLinker.exe @Library\Bee\artifacts\rsp\16431234100024594567.rsp
Fatal error in Unity CIL Linker
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
at Unity.Linker.UnityAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
at Unity.IL2CPP.Common.AssemblyDependenciesComponent.CollectAssemblyDependencies(AssemblyDefinition assembly, Boolean throwOnUnresolved)
at Unity.IL2CPP.Common.AssemblyDependenciesComponent.GetReferencedAssembliesFor(AssemblyDefinition assembly)
at Unity.Linker.UnityLinkContext.ResolveReferences(AssemblyDefinition assembly)
at Mono.Linker.Steps.LoadReferencesStep.ProcessReferences(AssemblyDefinition assembly)
at Mono.Linker.Steps.BaseStep.Process(LinkContext context)
at Unity.Linker.UnityPipeline.ProcessStep(LinkContext context, IStep step)
at Mono.Linker.Pipeline.Process(LinkContext context)
at Unity.Linker.UnityDriver.UnityRun(UnityLinkContext context, UnityPipeline p, LinkRequest linkerOptions, TinyProfiler2 tinyProfiler, ILogger customLogger)
at Unity.Linker.UnityDriver.RunDriverWithoutErrorHandling(TinyProfiler2 tinyProfiler, ILogger customLogger)
at Unity.Linker.UnityDriver.RunDriverWithoutErrorHandling()
at Unity.Linker.UnityDriver.RunDriver()
*** Tundra build failed (4.80 seconds), 35 items updated, 73 evaluated
UnityEditor.dll assembly is referenced by user code, but this is not allowed.
might not be in your code, what about installed packages
Also Unity 6? Not for the faint hearted
Less Unity question more an IDE question. To anyone who uses VS is it possible to hide the .meta files in the solution explorer
.meta files should not appear in Solution Explorer, screenshot your IDE
Sorry that's probably not helpful I have no idea what I was thinking
I'll screenshot the whole thing lmao
Oh wait
I see
Yeah my bad I didn't enter the .sln it's all fine now
Whoops lol
How do I reference this in a script? AnimatorController is from the UnityEditor namespace so I can't use it for builds
iirc you need RuntimeAnimatorController
It's an experimental project, so wanted to grab the latest HDRP versions etc. Other than this, it's been remarkably stable, but again, the project is relatively small.
unity 6 stable ? 😅
I've stripped any other imported code as well, but there may be another DLL that's the culprit.
ok dll's can be set per platform in their inspector
Can you point me at where to look for this? I'm in meetings for the next couple of hours, but I can check it out when the day calms to a mild brushfire 🔥
Sure, Normally you will find them In a Plugins folder
Select them in the project view and the inspector will show this where you can select to include or exclude specific platforms
awesome, thank you!
So this is the Inspector of one of my own Editor dll's
Awesome, thank you! I've only got 1 plugin enabled, so I've disabled it from the runtime. Let's see 🙂
You sir, are a LEGEND. Thank you, that fixed it! I learned a new trick, thanks! 🙂
excellent
I used your screenshots on the Unity Forums to add to a topic related to this error. Hopefully it helps someone in the future. 🙂 Thanks again!
Really someone screwed up because that dll should have been in an Editor/Plugins folder (like mine) then the inspector settings are set automatically
Yeah, I was deleting samples and code all over the place. I'll now test with my own Editor component re-enabled. 🙂
Question. So I have a sphere with a texture of Earth on it. I'd like to be able to zoom down all the way to the scale of streets. How is this typically done on apps like Google Earth? How easy would it be to replicate in Unity?
They have a database with massive amounts of data in it. Doable in Unity, sure, Easy, not so much
Like I get I'd need to stream in the images and patch them together as I'm zooming in.
But like, obviously I can't just take some high poly sphere and zoom in on it.
way before you even get that far you need the long and lat of where you are looking at
I imagine I'd need to slowly unwrap the sphere to account for the changing curvature.
I mean that's simple. It's just rotation.
I love it when people say 'just'
google earth like steve said take thousands of picture of the earth and when you zoom in, new zoomed in pictures take place instead of the zoomed out ones. so its not one big picture
I know, they’re patched together and dynamically swapped out as the zoom increases/decreases.
this wont be a simple project just so you know
I don’t need the texture streaming in yet. Right now I’m just concerned about the curvature and making sure I’m placing things on the plane properly.
As accurately as I can.
Why dont you 'just' use the Google Maps or Open Map API's?
if you need a detailed version of latitude and longitude i can give you a site i had to use to understand them
or what steve said (which is probably easier)
I’d appreciate it. I’m already able to convert from lat/long values to some spherical position.
😛
https://www.faa.gov/sites/faa.gov/files/18_phak_ch16.pdf
the "Latitude and Longitude (Meridians and Parallels)" section it talks about what it is throughout but mainly in the first section.
skip plane stuff
theres also this https://www.britannica.com/science/latitude
Latitude and longitude, coordinate system by means of which the position or location of any place on Earth’s surface can be determined and described. Latitude is a measurement of location north or south of the Equator. Longitude is a similar measurement east or west of the Greenwich meridian.
Plane as in like a geomtric plane or plane as in flying machine.
aircraft
got it
I think my main question here though is that when it comes to the actual mesh, I can't just scale up a sphere. I ASSUME that I'm going to need to morph some plane to a sphere and back depending on the zoom levels?
Is that correct?
Hello, is there a function that optimize by merging faces and vertices ?
Example:
Basic Cube (Initial case) :
After Extrude operation :
i applied some selection process on a closet face but the faces are soo slim and small :
My request : i prefer to have a wide chunk of face that merge and simplify the game object instead of handle large amount of small faces
There is a Combine Mesh operation, perhaps that is what you are looking for
?where i can find it? in which class
it seems that Mesh.Combine is a method for two different mesh objects while i do only have 1 game object with varities of faces (check image for more clarification)
This seems more like a job for your modeling software than Unity
an intersection function for faces is exactly what i am refering to
Doing this in blender is done in like 2 seconds.
It's such a simple object you could recreate it even. Or just use unitys default cube and scale it. Looks like someone extruded or made a bunch of edge loops for no reason
sadly it is a project i must extrude operations and manipulate game objects in runtime
There is the probuilder API. Havent used much of it myself but maybe itll suit your needs
To combine the faces
what's a good site for pasting code, I never know anymore
ok thanks
in doubt you !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.
can someone take time out of their day to help me out, theres a piece of code that only works inside the editor and I literally tried everything I can and it still doesnt work
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Just ask
I can't really.. like I dont know how to explain this
Maybe youre using ScriptableObjects for saving data or some other editor-only feature
Then I doubt we can help you mate
Just show the code and tell us what doesn't work
I would have to actually show but I can try to get it into text
Show GetSpawnPosition method
You can show a video if you want
so im using additive scene loading, level is an objecct on a level that has the transform for the spawn, works for first level doesnt work for more but works in editor
!code
Show the whole thing
📃 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.
alr its just a getter
does it work on playmode?
not in build tough
Read the bot for large code
I would have to put it in website i just did this but I can put it in a paste if its easier
Yes, always a paste site
That is the rules on this server, which is why the bot says that
ill record @grizzled ferry
@grizzled ferry also checked the debugger using the dev build but found nothing abnormal in the logic for the level start and the player teleporting there
it grabs the correct positions, it just doesnt teleport
it doesnt change position
for why
It would be helpful to see where the code in your first screenshot is. Is it in a callback? Awake? Is the script ddol (SOMETHING is ddol)?
Really hard to say without the code being shared
Onlevelloaded is a callback
it waits for scene to load and calls
I restarted pc, unity, reimported assets im sure its none of those
On cool. So, is the issue in every place? I couldn't really tell what was correct and what wasn't from the video
Alright, and you said you verified it is grabbing the right place? How? With the debugger or debug log?
I recommend adding this at the end of OnLevelLoad
Debug.Log($"Tried to move player to {_currentLevel.GetSpawnPosition()}, and actually moved to {_playerController.transform.position}");
so I put code in Hatebin but I don't see a way to share it
There should be a save button. After which just copy paste the url.
Then it doesn't save. Try a different site.
what's another one
can I check these out from the build somehow
!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.
other than setting up textmesh
Thanks!
here we go
So I have an issue where I have a player search robot enemies for scrap, so to prevent searching multiple at once I made a list on the player to add the object when the player enters the trigger, and removes from the list when they exit the trigger. I also remove the object from the list when the object is searched, but for some reason when i remove the object after searching I keep getting an out of bounds error
Is there a more efficient way to do this
Every debugging session should start with reading and investigating the error.
If you're asking for help, you should share the error details as well.
Yes, from build logs when are shown in the logs documentation page under player
public class NetworkPlayerBase : NetworkBehaviour
{
public NetworkPlayerBase LocalPlayer => GetLocalPlayer<NetworkPlayerBase>();
public T GetLocalPlayer<T>() where T : NetworkPlayerBase
{
return GameNetworkManager.Instance.LocalPlayer as T;
}
}
public class NetworkPlayerDerived : NetworkPlayerBase
{
public new NetworkPlayerDerived LocalPlayer => GetLocalPlayer<NetworkPlayerDerived>();
}
If I'm doing a reference like this (or a singleton instance for example) is this roughly the best kinda way to handle getting the "upcasted" reference on derived versions of it? was trying to think on if theres anyway i could cast it implicitly but pretty sure i very much cannot
fine doing this just wanted a vibe check
its weird I got a friend to play it and its fine for them, is unity making a cache or something thats preventing me from making the level work correctly on my end?
using new to hide base class members is always very questionable. I wouldnt call this the best way but honestly i dont even know what you're trying to do. This code would imply the GameNetworkManager.Instance.LocalPlayer can be something other than NetworkPlayerDerived, which doesnt make a ton of sense given the context. You could make use of generic classes here
the idea is that NetworkPlayerBase always has a reference to the localplayer but in a way where if your using a derived version of NetworkPlayerBase you can easily get the derived version of said reference
(hence the hiding)
i think a generic class here would just do what you want and not require more lines redefining the property.
too bad unity doesn't support covariant return types yet otherwise this would just need an override
if Im adding a script that's not connected to a game object what's the easiest way to make it so a update and awake function work for it
I can call functions to it but I want to use Update and Awake
if it isn't a component then there will be no Awake or Update messages sent to it, so whatever object is instantiating it would need to call methods on it
Crap
is there a specific reason you don't just make it a component? if it needs to receive unity messages like Update then it would need to be one
Im adding a script to a project that is loaded outside the game
is this project even related to the unity game? really not sure what you're doing here. Usually you could just call your own awake or update method from whatever monobehaviour you want.
🤷♂️ if its so obvious then whats your actual situation
Hi, I am modifying the vertices of a simple mesh in unity. I am stretching a small 3x3 grid with a hole in the middle to be much larger and the hole and the center is disproportionate now. When I apply a material, the rectangle sections of the second grid have a stretched material. How do I fix this in code? Is it something with UVs? I do have a triplanar shader that fixes it, but it doesn't give me all the options I want.
Here is the mesh manipulation code currently. The verticies are just moved, not added or removed.
meshCopy.SetVertices(vertices);
meshCopy.RecalculateNormals();
meshCopy.RecalculateTangents();
meshCopy.RecalculateBounds();
meshCopy.RecalculateUVDistributionMetrics();
Thanks!
I did more research, I think I can just modify the UV array.
is there a way for me to use 2d objects on a 3d project?
Yes
Same way you would use them in a 2d project
2d projects are still 3d in unity btw
but how do i add them to the project
The exact same way 🤷♂️
With the create menu
i cant find it
do you have to fix it in code or could you fix it in 3d?
Sorry, you do need the 2d packages from the package manager
2d sprite, 2d animation, etc
oh yeah thanks
What part are you struggling with?
Also if you want a spreadsheet why would you want a txt file, use CSV or something
yeah, i considered it, its just easier for me to manage with a txt file
personal preference
i just wanna make a new line for each generation i just dont know how lol
What do you mean? Just write a new line in your file
Have you looked into any file IO stuff? This is pretty much built in for you
yes, i dont remember the line i wrote but its the one that uses /n for a new like right?
new line*
if you're using StreamWriter, theres no need
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-8.0 look at examples and the WriteLine method
you really didnt read the docs very well, there are built in methods for this
alright thanks
also stuff like that is very easily googleable
Hello, I am trying to create transition between scenes. Animations should look like this -> leaves will move to cover entire space, after that is new scene loaded via Addressables. Uncover is done via moving leaves to side. I found, that when loading of scene is taking too long, the animation is either not visible at all or only small end part, because uncover function is called inside/before spike. I tried to call uncover function after is scene loaded (Addressables.LoadSceneAsync.complete), one frame after Start function but in more complex scene it is not helped. Do you have any ideas how to solve it? Thank you! 🙂
From profiller I found, that in scene swapping I have three spikes:
- first and second one is related mainly on Addressables loading (Integrating assets in background, preload single step, loadlevel async integrate etc.)
- third one is caused by PreLateUpdate.ScriptBehaviourLateUpdate, DelayedActionManager.LateUpdate etc.
Start, .complete function and even one frame after start is called before third spike.
you should be able to expand PreLateUpdate.ScriptBehaviourLateUpdate in the profiler hierarchy and see whats specifically causing a issue. Might have to turn on deep profile if you want it to tell more details.
Hello, first of all, thank you that you are trying to help me! 🙂 I looked into it and found this:
mono jit should mean this is the first time that code is running. is there anything under that if you expand it? Maybe you're doing something that can be optimized. I do find it somewhat concerning still that its taking 50ms but otherwise you could also try just delaying the animation a little more. I do have to go now though so i wont be able to help much.
How can I set this property from code?
could you send a full screenshot on the thing?
in code make a variable camera
Assuming it's the hdrp volume it'd be this https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@10.0/manual/Volumes-API.html
or just do that
URP
Access the Universal Additional Camera Data component (it's on your camera - although not visible from the inspector unless you've got debug mode enabled)
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.2/manual/universal-additional-camera-data.html
Then modify the necessary property
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.2/api/UnityEngine.Rendering.Universal.UniversalAdditionalCameraData.html
yep, just found it as well
thanks
I am doing an animation state controller, where I want to set some values for my transitions in the controller. The issue I am having is that I'm not sure if I should separate the logic in a seperate script file or make it inside the playerMovement script where I already have values for my velocity, isGround and stuff like that. Any suggestions?
Any character moving will likely use animations anyways so itll be fine to put it in the movement script as long as it isnt limited to only working with one model.
If you separate the logic, there should be some reasoning otherwise you're just moving 1 code elsewhere. Even then your player movement script will either need to interact with this new script, or provide public values for it to use
Does anyone know why it could be that I cant detect the collider with raycast even if its rendering properly? I doubt the problem is with the raycast as it works fine with sprite colliders. Also depending on the position of points of the line this error shows up. I've got a slight idea on where the problem is but I feel like it's gonna take a long time if i need to manually check all points, is there another way to work around this problem, as theres no rendering issues with the mesh.
Where's that error coming from? Seems like you have an invalid point in your collider/ mesh however this collider is created.
Maybe show your code and the full stack trace
How to post !code
Use the inline guide for small bits of code and the large code blocks for large pieces of 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.
Sounds like you're trying to do a 2D Raycast against a 3D collider?
(from your comment before about sprite colliders)
oh ok that could make sense
I don't recall if unity throws an error for divide by zero or just blows up when using it. Are there any other errors?
If you are using 2D you should use PolygonCollider2D not a mesh
its just the same error on different indexes
ok thanks
!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.
then I need to convert all vertices in the mesh to the polygon collider 2d points?
Yes. Though I wouldn't bother using a mesh as an intermediary
but what about the rendering side
¿Any idea how to fix Visual Studio freezing and closing when debugging? I get "Debugger: Getting dataTip text...", and only happens in Unity
Hey, I have a problem regarding 2D tilemap own tiling rules and I still didn't get anyone to reply to my post (https://discussions.unity.com/t/unity-tilemap-own-specific-rule-tile/1506643). Maybe somebody here could check it out and maybe know the answer. Thanks
LineRenderer? It depends what you're doing
SpriteShape is maybe an option too
Well what are you trying to do
its drawing lines but I need full control on them, so curves, witdh and some more stuff
You can do that with LineRenderer
Otherwise, you can certainly use a MeshRenderer
If you already have that working
I already tried it and it didnt work properly
But the collider needs to be a PolygonCollider2D
i could just mesh collider
but atleast i wouldnt have to rewrite all point for rendering and collisions
and i could just use the same mesh
But then you have to redo all your other physics
there's no other physics
You don't have to rewrite much. You're just putting the same points into the polygon collider as you put in the mesh.
the sprite i mentioned earlier were just testing
It's like, one for loop to copy them over
it did work but it looks like some math is off
and its deletng the entirity of the upper line of the mesh
Well presumably you have a bug or error somewhere, hard to say without any details
yeah its probably that
Note for polygon collider you don't need to do the triangulation yourself
You just provide a list of points around the perimeter in order
yeah it could work
i think it wasnt working because some triangles in the mesh were swapped
well it seems to be working with the mesh collider
the only problem is that this error wont go away
the line rendering works without problem
but the mesh wont load in what it seems random positions
Well it seems to be pretty straightforward. Why not debug what value you're putting in that vertex
gonna try that right now
Anyone here use BehaviourTrees? I started using TheKiwiCoders free implementation, and I wonder if there's something wrong with it or my understanding of how bt's are supposed to work. In the image setup, I'd like the waitnode to run through, and after that the getup node to run through, but with this code:
protected override State OnUpdate() {
for (int i = 0; i < children.Count; ++i) {
var childStatus = children[i].Update();
if (childStatus == State.Running) {
return State.Running;
} else if (childStatus == State.Failure) {
return State.Failure;
}
}
return State.Success;
}
the first run of the ragdoll get up node works correctly returning State.Running, but on the next "Tick()"/Update() of the tree the wait node restarts because it's first run finished, marks it as not running, so next time around it restarts.
I don't know if this is a short coming of this particular implementation, or is this how behaviour tree's are supposed to work?
(I think it would be fairly easy to change this to run so it's "intuitive for me" - meaning: add a firstrun flag, run each node ONCE until it's first success, and on failure reset all children's 'firstrun' flags) but I wonder it I'm just thinking about it wrong - more like a state machine)
ok so it seems my math was off
and a bunch of vertices dont need to be there
It only took one extra int lastNodeFinished on the sequence node, a if(i <= lastNodeFinished) continue and setting lastNodeFinished = i on the child node success, but I'm still curious if I'm using behaviour trees wrong.
Hi all, I started learning about coding patterns hoping to improve my codes. I've came across two patterns that's fairly interesting to me: singleton and observer
Now my question is what's the main difference? From what I can see, If I want to call and trigger an effect/function globally from any script, I can do that via both patterns, am I missing something that observer pattern does better than singleton? (Benefit of singleton also includes only having one of the instance etc)
the two have no relationship at all.. One is based on events, the other just means there will only be 1 instance ever
they are both used together or sometimes not
so yeah You CAN have events to sub to from a singleton, or it doesnt have to be. Doesn't mean you can't use observer otherwise
I think Im trying to place those patterns into how I would use them (which could and probably is totally wrong) so I can understand them better
I could have
Unityevent1.invoke()
Or
EffectManager.Instance.PlayEffect1()
Which both would achieve "triggering an event of sorts"
Please correct me if Im way off the mark
I would say observing an eventm is different than "triggering an event"
what you describe is simply running a method not event
Ahh so observer would come in handy with ui events like OnMouseClick or mouse up or something like that?
not just UI
its a good way to have other scripts do something when something happens in another script. without that original script with event knowing anything about the "subscriber" scripts
I think I've seen
public static Action xyz...
Is that like a way of creating an custom event almost?
you would do public static event Action
Action is a delegate type for events
cause its static, you could say that event is technically a "singleton" though its not singleton pattern
So we can have observers subscribe to this event, and whenever this event is invoked, it will trigger all the observers' functions
correct
not the event triggers them, the observes handles them on their oown
I think this made it a bit clearer haha
Yep makes sense, so technically the event do not care who is subscribed
the key part to remember is that the Invoker never cares about the subscrivers
exactly
Which is kinda decoupling the code (which equals good i hope)
though if you have no subscribers it throws a null ref, so we use a null check when invoking usually
I'll keep that in mind
eg
MyEvent?.Invoke()
same as
if(MyEvent != null)
MyEvent.Invoke()
I think to kinda make sense of both patterns, I could use
A singleton manager that host a few common events, which means that random scripts can subscribe to those events without direct reference to anything
I heard somewhere the ?. Modifier doesn't work in mono?
(Sorry Idk what's the proper term for that thing)
So like rigidbody2d for example?
quick thing, Singleton also can be useful without event , if you want some other script running a function on a GameManager or a SoundManager
hope thats clear that you don't have to use either one together
yeah a bit ,I would sometimes just put them in a real life context. think like Youtube channel vs subscribers, etc
or a Radio Broadcast antenna vs Receivers
oh an C# events use +=to subscribe
Unity's UnityEvent/UnityAction use AddListener (good example is OnClick from UI Button)
also very important, its good practice to cleanup and unsubscribe -= / RemoveListener when object is destroyed, event no longer needed, etc.
Hey, I have a problem regarding 2D tilemap own tiling rules and I still didn't get anyone to reply to my post (https://discussions.unity.com/t/unity-tilemap-own-specific-rule-tile/1506643). Maybe somebody here could check it out and maybe know the answer. Thanks
Hey, I have a Image and it has x child objects.
I want to move the Image on the Y axis so that the selected child object will be at the initial center of that Image.
_craftingOptionsTargetPos = (CraftingOptionsParent.rect.top + CraftingOptionsParent.rect.bottom) / 2;
....
_selectedCraftingOption = CraftingOptionsParent.transform.GetChild(_selectedCraftingOptionIndex).GetComponent<CraftingOption>();
float selectedChildPos = _selectedCraftingOption.Rect.position.y;
float distance = CraftingOptionsParent.position.y + selectedChildPos;
float target = selectedChildPos - distance;
DOTween.Kill(CraftingOptionsParent);
CraftingOptionsParent.DOAnchorPosY(CraftingOptionsParent.position.y - target, 1f);
I can't do the math here
wouldn't you want distance = selectedChildPos - CraftingOptionsParent.position.y; ?
wait
float _craftingOptionsTargetPos = (CraftingOptionsParent.rect.top + CraftingOptionsParent.rect.bottom) / 2;
_selectedCraftingOption = CraftingOptionsParent.transform.GetChild(_selectedCraftingOptionIndex).GetComponent<CraftingOption>();
float selectedChildPos = _selectedCraftingOption.Rect.position.y;
float distance = selectedChildPos - CraftingOptionsParent.position.y;
float target = _craftingOptionsTargetPos - selectedChildPos;
DOTween.Kill(CraftingOptionsParent);
CraftingOptionsParent.DOAnchorPosY(CraftingOptionsParent.position.y + target, 1f);```
yep, it works almost perfectly now, thanks :D
math.
haha yeah, if it works leave it as it, this might work too
float parentCenterY = (CraftingOptionsParent.rect.top + CraftingOptionsParent.rect.bottom) / 2;
_selectedCraftingOption = CraftingOptionsParent.transform.GetChild(_selectedCraftingOptionIndex).GetComponent<CraftingOption>();
float selectedChildPosY = _selectedCraftingOption.Rect.position.y;
float offset = selectedChildPosY - parentCenterY;
DOTween.Kill(CraftingOptionsParent);
CraftingOptionsParent.DOAnchorPosY(CraftingOptionsParent.anchoredPosition.y - offset, 1f);```
its harder when I can't directly test it with the same setup lol
yeah
well, for some reason it moves the objects to the bottom of that parent and not the center
but thats something I can figure out
might have to do with using world vs local pos
yeah most likely
RectTransform.position is world pos
almost there ;p
_craftingOptionsTargetPos = CraftingOptionsParent.rect.height / 10;
Wondering if anyone knows a good method to temporarily lock a Cinemachine Free Look Camera?
There seems to be a few different ways to accomplish this, and I wonder if anyone knows what's considered best practice?
// One method seem to be to blank out the input name, this seems janky and requires storing of the input names, so it can later be unlocked.
public void LockCameraRotation() { CinemachineFreeLookCam.m_XAxis.m_InputAxisName = ""; CinemachineFreeLookCam.m_YAxis.m_InputAxisName = ""; }
// Another is to disable the component itself
public void LockCameraRotation() { CinemachineFreeLookCam.enabled = false; }
// Another is to override the maxSpeed
public void LockCameraRotation() { CinemachineFreeLookCam.m_XAxis.m_MaxSpeed = 0; CinemachineFreeLookCam.m_YAxis.m_MaxSpeed = 0; }
edit: corrected markdown for displaying codeblocks
disable the component / gameobject
Hey, I have a problem regarding 2D tilemap own tiling rules and I still didn't get anyone to reply to my post (https://discussions.unity.com/t/unity-tilemap-own-specific-rule-tile/1506643). Maybe somebody here could check it out and maybe know the answer. Thanks
Hey!
I have a player using an dynamic RigidBody2D wich gets pushed around by the enemies. So basically I want to make the player kinematic, however I am currently struggeling with the accelleration, as it is not as smooth as with an dynamic rigidbody2d.
Does anyone know how I can reach the same effect of
rb.AddForce(movementVector, ForceMode2D.Force);
with an Kinematic Rigidbody2D?
All this line of code does is add to the velocity
You can disable it, but I'd personally zero the max speed.
rb.velocity += movementVector * Time.fixedDeltaTime / rb.mass;
Is equivalent
thank you ^^
Is there a reason to make your own delegates? Like why would we when we can just use Action<T>, Func<T> and UnityAction<T>
One minor benefit is that you can name the parameters 🙈
But at the cost of using two lines to define it.
Yeah theres that I guess
No real reason to make your own delegates...it's just that delegates predate the Action and Func classes
Since those got added, it's not really necessary
Can I make a player prefab go into a specific animation when editing it in Scene view? I need to place my weapon into it's hands but it stays in T pose default right now
i want to track objects with a certain script attached, if they are visible on screen with ui images as icons, what would be the most efficient way? just loop with foreach through the objects? if i track/update the icons every frame that will cause lag, wouldn't it? (it's a strategy game, so there can be 100s of objects)
best bet is a for loop but dont check each object every frame, stagger them across multiple frames to smooth out the overhead
Lately I've been unable to rename class files in Visual Studio (Community 2022) by using CTRL+R, CTRL+R. The Rename dialog appears, I enter the new name and hit enter, and an "Updating files..." message is shown for a moment. But when it's finished, the class and file name aren't changed. The only noticeable result is that the file's indentation sometimes gets reformatted.
Renaming from the Solution Explorer / F2 still works fine, though. Is this a known issue?
I'm trying to load an asset into a script that I have created, but it keeps returning null. The asset is visible in the project view and the path is as set in the code, so I don't really understand why it can't find it
private SteamAudioMaterial currentMaterial;
private void Awake()
{
if (bundler == null)
{
ImportBundler();
}
currentMaterial = gameObject.GetComponent<SteamAudioGeometry>().material;
}
[MenuItem("AssetDatabase/LoadBundler")]
private static void ImportBundler()
{
bundler = (WallBundler)AssetDatabase.LoadAssetAtPath("Assets/Program Files/Scripts/WallBundler.asset", typeof(WallBundler));
}```
Strangely enough, it used to work without all this extra code, but suddenly broke today
{
bundler = AssetDatabase.LoadAssetAtPath<WallBundler>("Assets/Program Files/Scripts/WallBundler.cs");
currentMaterial = gameObject.GetComponent<SteamAudioGeometry>().material;
}```
This is what I had before, which somehow worked but then broke. I'm aware now that I was somehow loading a Script into an Asset which I don't really understand how it could have even worked.
scripts are assets too, is WallBundler.asset a c# script or an asset of type WallBundler? it's in your scripts folder so it's not clear...
Yes, I haven't gotten to move it to a seperate folder yet, but you got that right
Does anyone have some advice for how I could fix this?
not at all sure what you think this
bundler = AssetDatabase.LoadAssetAtPath<WallBundler>("Assets/Program Files/Scripts/WallBundler.cs");
is actually doing
I've stated in the post, I'm trying to load the asset into my script so I can access the values I'm storing in it within the script
for (int i = 0; i < collision.contactCount; i++)
{
var contact = collision.GetContact(i);
var contactNormal = contact.normal;
for (var j = 0; j < collision.contactCount; j++)
{
if (i == j) continue;
var otherContact = collision.GetContact(j);
var otherContactNormal = otherContact.normal;
print(Vector2.Dot(contactNormal, otherContactNormal));
if (!(Vector2.Dot(contactNormal, otherContactNormal) < 0.9f)) continue;
var otherRb = otherContact.collider.attachedRigidbody;
if (otherRb == null) continue;
var relativeVelocity = rb.velocity - otherRb.velocity;
var relativeSpeed = relativeVelocity.magnitude;
var contactForce = relativeSpeed * rb.mass;
if (contactForce > crushingForceThreshold)
{
TriggerStateReset();
}
}
}``` Trying to create a crushing mechanic. having some issues with clipping when the object is thin. any suggestions are appreciated
Is there a better way to order UI elements on z axis(layers) in a script?
By better I mean, anything that doesn't require keeping track of child index and reordering them.
are they UGUI elements? or in-world (diagetic) elements
If you're doing UI through UGUI then... sort your elements by putting them into containers, ordered by the Z order you want..
hey guys, does anyone know if there is a native way of doing webauthn built into unity it self
i know there are specific libs outside of unity but i am wondering if anyone knows of a unity specific lib that builds to anything
Hello! Struggling with navmeshes rn... As you can see in the first pic, it regenerates around the placed walls correctly, but the character refuses to move when i click somewhere. My code gives the character object a list of coordinates to move through and you can see the corresponding tiles light up in green, yet the character (the gray plane) won't move an inch... What am i doing wrong?
{
Vector3 targetPosition = GetComponent<LevelGrid>().GetRelativeWorldCoordinates(hexCoordinates);
movementWaypoints.Add(targetPosition);
Debug.Log($"Added {hexCoordinates} into the waypoint list");
}
public void MoveThroughList(List<HexCoordinates> hexCoordinatesList)
{
if(hexCoordinatesList.Count<=_movementDistance)
{
movementWaypoints = new List<Vector3>();
currentWaypointId = 0;
foreach (HexCoordinates hexCoordinates in hexCoordinatesList)
{
Move(hexCoordinates);
}
isMoving = true;
if (navMeshAgent.SetDestination(movementWaypoints[0]))
{
Debug.Log("Success");
}
}
else
{
Debug.Log("Can't reach that");
}
}```
Here's the update method in the character's script
{
if (!isMoving)
{
return;
}
Vector3 waypoint = movementWaypoints[currentWaypointId];
/*Vector3 targetDirection = (waypoint - transform.position).normalized;*/
if(Vector3.Distance(transform.position, waypoint) <= stoppingDistance)
{
currentWaypointId++;
if (currentWaypointId >= movementWaypoints.Count)
{
movementWaypoints = new List<Vector3>();
_hexPosition = GetComponent<LevelGrid>().GetRelativeHexCoordinates(transform.position);
isMoving = false;
OnMovementEnd?.Invoke(this, EventArgs.Empty);
transform.position = _centerPosition;
}
else
{
navMeshAgent.SetDestination(movementWaypoints[currentWaypointId]);
}
}```
Seems like just install the .NET lib and away you go..?
Whenever i click for a character to move, it returns true from the navMeshAgent.SetDestination, so i have no idea what's wrong...
Whats UGUI? What if I have infinite amout of z indexes?
Is your game 3d or 2d?
Read up on the docs (https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.SetDestination.html). Setting the destination returns true instantly if the destination was requested successfully. You'll need to check for when the path becomes available in your update method - this doesn't happen instantly, but may take a few frames
Is there a way to detect in OnValidate() if the object is in the scene or a prefab in the assets folder? I only want to change the name if it's in the scene.
couldnt find that on the internet, have you got a name by any chance of this lib?
yep was going to say i found it, ok cheers Fido2.AspNet
but i wonder if i build to androir or webgl do you think thats going to still work or would they have to be implemented separatly?
I just want UI to be positioned on z axis somehow, UI is 2D right?
Its not worldspace canvas.
android will work fine, webgl "it might" - depends on where the auth is going (same domain as your game? no problem, elsewhere? problem)
mhmhm ok i will look into it thanks dude have a nice day
How do i check for that?
UI if you're using UGUI (which it sounds like you are) is drawn in each canvas in the order of the game objects in the hierarchy
so if you have some canvas, with 3 gameobjects underneath it (1, 2, 3); and under game object 1 you have three more (A, B, C) then your canvas will render the objects in the following order: 1, A, B, C, 2, 3
You can customize this however you want
I understand, but that means I have to create those game objects for each potential z index I might ever need.
I guess that sorting game objects on a list might work
I'm not sure what you mean.. you have to create them anyway..?
No, I create them from script based on an input from a file
Then just instantiate them in the proper layers
layers?
or if they're sorted in your file already, instantiate them in that order (later ones will draw over the older ones)
yeah sorry, I shouldn't use the word "layer" here, I mean.. game objects
Lemme open up one of my projects and snap a screenshot, sec
Currently I am doing them in order from a file, which is fine for now, but not ideal in the future.
This is a inky game(text based), if I draw images in order they appear, I will force inky dev to "clear" the screen if they want to reorder anything which is not ideal
I might just let them pass z index and sort them on my side.
"Game Renderer" is the main game object.. then all those objects with "Z" in the title are various containers for things that need to be displayed
Z5: Grid Renderer, for example, has many many objects that are instantiated at runtime, but don't overlap each other.. I spawn items into that "container" (which I called "layer" above)
I see, that does make sense, It might work if I assume a limited amount of z indexes(it's not like we need more than 10 or 20)
Why don't Unity events allow multiple parameters?
In Z6 - there's a "combo coins" dialog that appears over everything in Z5, so when activated, I just turn it on (and then I don't need to like, sort anything.. it's just naturally above Z5)
item highlighed in the hierarchy, along with a screenshot - that blue thing appears above the game surface - it comes with its own 50% alpha background to cover up the game surface, but I ... wouldn't get into sorting shit because that would be a nightmare
they just don't 🙂 that's the API surface they've provided.. if you need parameters or more robust events and don't need unity's event system, just use C# events or actions and subscribe/unsubscribe to those in various game objects OnEnable and OnDisable()
You can pass an object right? like a struct
I did that for item drop in my game
struct ItemDrop
Ah. That's frustrating. I wanted to trying and use it for scriptable objects, hence why I couldn't use c# events.
Yep, that's the other solution, but then you can't see the serialized value of it (easily). I might not use a struct, but that's fine too:
public class MyEventArgs
{
public int MaxHP;
public int CurrentHP;
}
public class HpChangedEvent : UnityEvent<MyEventArgs> {}
Whats the issue in using them for SOs?
the values aren't serialized
Well, I want to have functions with multiple parameters.
(so they wouldn't show up in the inspector)
What are you trying to solve? maybe there's a better solution than unity events here
I tried structs, but even with System.Serializable they don't show up
You can pass 1 object that will act as a container for those parameters
oh
Do you want to show them in the inspector together with the Event?
yeah, unity doesn't know how to make a struct an inspector gui item.. there's solutions to this but they aren't trivial.. you'd have to write your on inspector drawer thing
I have a scriptable object with a list of commands to preform. I am currently using a pattern where I make all the commands as objects inheriting from the same interface, and calling a function in that, but having all the parameters as fields within the object.
I forgot those are issues, but I can recommend Odin Inspector on asset store, it lets you serialize everything(or almost everything)
that is what I am now lol
You are using Odin inspector?
Commands being.. what..? Like game actions?
Did you set your ScriptableObject to Odin version of SOs?
Yes.
I think its called SerializedScriptableObject or something
The one that holds it yeah. And then I just put a interface parameter.
It works. A little hacky but it'll hold
hey why is there no CommandBuffer.CopyBuffer for computebuffers/graphicsbuffers that accepts ranges? I needed a faster way to copy graphicsbuffers into a larger graphicsbuffer thats faster than just using compute shaders...
im having a bunch of problems with my android app project, which channel would i want to ask for help in?
specifically with the imported packages
Are unset elements of an int[] 0 or null?
Hmm, not sure. I guess the only option is to use a native graphics plugin to submit the copy command yourself.
0 int is a value type, so it can never be null.
I thought so but im getting an error that made me think otherwise
It's more likely that the array has not been created.
It is, im doing smt else wrong
so would a foreach loop ignore ints of 0?
No. No element of an array will ever be ignored by a foreach. It will always iterate as many times as there are elements in the array.
Even when you have an array of a reference type, like GameObject, and all the elements are null, a foreach will still iterate over all of them.
because they simply do not exist
For the future, you should really show the code/error for what's confusing you instead of asking about your assumptions. Null doesnt apply here at all, since you mentioned it's an int array, ints cannot be null. So it's possible we cant see what your actual issue was
What are predefined symbols for Unity 6? (example: UNITY_2024)
6000 maybe
ah yes work UNITY_6000 xd
I don’t see the need to post a whole chunk of code when I can verbally ask. My issue isn’t about my code anyways, I just had this impression that it has been coded in such a way that foreach loops ignore null elements
Or 0’s for ints
The null doesn't exist,but the elements in your array do. They're pointing to a specific point in memory. That memory is what contains the null.
Also, it's not correct to say that null doesn't exist. It's a very specific value defining that the reference doesn't point to anything
And if for each was to ignore 0s, that would be a terrible design. What if I want to specifically look for elements that have a value of 0??
Or if you wanted specifically to check for null elements
hopefully it's clear what I'm trying to do but I'm pretty sure I'm coming at this all wrong
Explain the issue in text first. Or whatever question you have.
Yea ur right on that
In my case, I want to ignore the ‘0’s. Maybe thats what influenced by stance on this
Just added a simple check in my foreach loop
MeleeBehavior is supposed to be a general framework that governs melee enemies, just move at the player until they're in range to attack. I want to have more than one type of melee enemy though. They would share the same MeleeBehavior logic but have different modules that extend Attack() in MeleeBehavior. The problem to me is that I can't just add FieldOnSelfAttack as a component and have the MeleeBehavior implicitly implemented since it needs EnemyData data assigned from somewhere.. So I think the entire premise of how I've structured it is wrong but I'm not sure what I'm supposed to do instead
Not gonna say anything about whether what you're doing is a good solution or not, since I don't know the whole context.
But if the problem is just the EnemyData, you can probably assign it from whatever does have it.
Sounds like a use for an Interface. An interface allows you to have multiple versions of code with the same structure, and then use each one as if it is one type. Ie. MeleeType1 : IMeleeEnemy. You create the interface as the structure of these classes. Say it has a Move function, but each has different characteristics. But when you are wanting the enemy to move you can use IMeleeEnemy meleeEnemy; which can hold MeleeType1 or 2 or 3 etc, and then say meleeEnemy.Move()
Heyo. Anyone have experience with UniTask? I'm trying to get a WhenAll await to refresh when I add something to the list of tasks. I got it working with a hacky workaround when I was using unity's async/await functionality, but I was hoping someone here knew a cleaner way with UniTask.
That’s not how it’s supposed to be used.
if you need to monitor threads dynamically you should maybe just implement your own monitor or Rx-pattern.
Hey lads. I'm in the process of creating a quest system for my game, been looking online for solutions, but thought I might as well ask here if anyone has done one before, and if so how they did it? I don't need anything advanced, and could probably get it working my own way, but would be nice to hear some other methods people have implemented!
a lot of this would just be up to your game design. At the end of the day you just need an instance which stores something like quest title, description, rewards, and whatever else you want. Use scriptable objects to create the individual quests if you can.
Yeah, it's very case-specific definitely. I've planned on using SO's, but find it a bit difficult when quests become more specific. For example; Go to this location, craft this item, find this item, get to this point of the game, etc. Of course I can specify these SO's with a enumerator representing the type of quest, which I believe will be the solution.
Was just interested in hearing and/or seeing other developers' work!
its just a matter of having that action notify the quest that its been completed. Like for a location, one easy way is just putting a trigger collider in an area. A script on the same object as the collider can store a reference to the quest SO that you want to notify it is completed. Or even just make some static class to manage this but then you'll have to reference it via ID rather than drag and dropping the SO instance in.
Yeah 'course, going to places and such is the easy part. And I have a general idea of what to do, just interesting to see what others have done
SO's with a manager class, SO's with individual responsibility, doing it without SO's, etc.
Just trying to flood my brain with ideas basically
hi, i have a trouble, i'm making a light system y use a bidimensional array y make spheres and more inside of the chunk and it works fine, but when i try to manipule inside of block this happens
i dont nkow how to fix it
i dont know what i am doing wrong
I remember unity had some attributes I could put above Methods to make them invokeable from the inspector, either through the inspector context menu, or a button. But this was back in 2019 and I don't remember if it was a package I imported, something I created myself, or if it was built in to unity
If it's not built into unity, is there a package that does it?
I have MoreMountains, but I can't seem to find a button method invoker
Really blanking out and google is not helping
Odin (paid) or NaughtyAttributes (free) can make inspector buttons. Always handy.
Thank you so much for this. I used to use Odin but it feels a bit heavy handed? Naughty attributes is it a bit leaner?
Odin is a lot more robust for sure, but NaughtyAttributes is nice. You can check their Git page for everything it can do. It will probably cover your needs.
Hey, I have a problem regarding 2D tilemap own tiling rules and I still didn't get anyone to reply to my post (https://discussions.unity.com/t/unity-tilemap-own-specific-rule-tile/1506643). Maybe somebody here could check it out and maybe know the answer. Thanks
ah I see now thanks
How do you even want your Tiles to be spawned relatively to each other?
I will make a script do spawn the tile around the player character, but I firstly want to make the generation better, now I am using the brush, later it will be automatic by script
I have a custom rule tile
This wasn't my question
How should the tiles be spawned?
What do you mean
Could you, perhaps, draw it manually in your Tilemap?
For example, the right tile is always near the left one etc.
The tiles are like a room with wall on left/right/top/bottom, now it's random - and it doesn't look that bad, but there are some situations where it looks weird - I wanna fix that
and check the post which I linked, there is a lot about it
By setting the right neighbors, you can achieve tiles being spawned properly
I know that, I dont want that
Why?
check my post which I linked
I've already checked it.
I explained what I want
I know basic rule tile, I wanna make my own
Instead of there "is" or "isnt" tile next to it, I wanna make it like if "room with right wall" is there, you got me?
rule tile has even yes or no tile next to it, I wanna check if there is specific tile next to it (from an array)
So, "only spawn the left tile, if there is a right tile on the right"
I think you should show the pattern you want to achieve, and I'll tell you whether it's achievable with the normal rule tile
it's more like "if there is "only spawn the left tile" if there is SPECIFIC tile on the right (one of the tiles from an array)
It's not achievable with normal rule tile, it's in the post
I am trying to make own script for it
I am making custom rule tile script
If your left tile says it needs a tile on the right, and the right tile says it needs a tile on the left, they are fine. If your left tile says it needs a tile on the right, and the top tile says it cannot have a tile on the left, they cannot coexist
I understand normal rule tile
What I am doing can't be achieved by normal rule tile
you need custom
Alright, the only problem is that you have different types "right", "left" etc. tiles
As far as I know, normal rule tile doesn't support that. And different rule tiles don't care about each other's rules
But I'm not sure how you're going to choose the "top" or "bottom" tile spawned from the array
Randomly?
Then they won't look fine together
I know that normal rule tile doesn't support it, that's why I am making my own. I don't need that to care about each other, just 1 rule tile will have the custom rule
Yeah, randomly. It actually looks nice, except specific situations, which I wanna fix with the custom rule tile
Just had a look in the RuleTile class, so I would suggest the following:
In your Neighbor class, consider having the following constants:
public class Neighbor : RuleTile.TilingRule.Neighbor
{
public const int Top = 3;
public const int Bottom = 4;
public const int Left = 5;
public const int Right = 6;
public const int NotRight = 7;
public const int NotBottom = 8;
public const int NotRight = 9;
public const int NotLeft = 10;
}
Since This is already Anything and NotThis is already Nothing.
Remove the Lists for Top, Bottom, Left and Right walls.
Create an enum with Top, Bottom, Left and Right as its items.
Make your TilingRule contain this enum, and create a TilingRule for every of your corners. Since you won't be able to choose one, when there is nothing, also consider creating an all-NotThis, and, maybe an all-This.
Also make it contain Sprites, which are the ones to be chosen randomly.
Override the method GetTileData to assign the randomly chosen Sprite from the matching TilingRule to the global variable, if you need it somewhere. If not, don't. You still have to save your TilingRule's enum, since you may not care about the Sprite as long as it's the suitable direction.
The overridden RuleMatch method should check for this == tile is This, this != tile is NotThis, as in the virtual one. Created by you directions should be checked as following, where direction is the created enum:
=> neighbor switch
{
Neighbor.Top => HasDirection(tile, Direction.Top, true),
// ...
Neighbor.NotTop => HasDirection(tile, Direction.Top, false),
// ...
}
private bool HasDirection(TileBase tile, Direction direction, bool value)
{
if (tile is AdvancedRuleTile ruleTile)
return ruleTile.direction == direction == value;
return false;
}
Thanks, I will check it out
So am I supposed to make the entire advanced rule tile 4 times and set the direction in every one if it? and put the sprites which corresponds the direction or all of them?
This is how I made the code: https://pastebin.com/J589X4Hd (with a little help of AI)
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.
public class LevelSO : ScriptableObject
{
public string levelName;
public float bestTime;
public string nextLevel;
public List<float> allTimes = new List<float>();
public List<float> campaignTimes = new List<float>();
// Load the level data explicitly
public void LoadLevelData()
{
LevelSO levelData = SaveSO.LoadLevelData(this);
if (levelData != null)
{
levelName = levelData.levelName;
bestTime = levelData.bestTime;
nextLevel = levelData.nextLevel;
Debug.Log("LevelData.AllTimes Before Clear:" + levelData.allTimes.Count);
allTimes.Clear();
Debug.Log("LevelData.AllTimes After Clear:" + levelData.allTimes.Count);
if (levelData.allTimes != null)
{
allTimes = new List<float>(levelData.allTimes);
}
}
else
{
Debug.LogWarning("No save data found for level: " + levelName);
}
}
}
This is a script for my scriptable object which updates the data of the SO based on the saved data JSON.
As you can see the debugs before and after the clear Im clearing allTimes not levelData.allTimes but its clearing both and idk why
any help appreciated
📃 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.
Does anyone have an issue with the last 2 updates to visual studio ce. It knocked my intellisense out and it keeps breaking. It’s so frustrating. If I dare make a mistake it just breaks until I restart vs
Presumably SaveSO.LoadLevelData is doing this.allTimes = <parameter name>.allTimes which assigns a reference to the same list. If you want to separate the lists then do this.allTimes = new List<float>(<parameter name>.allTimes)
the same way this script does
Thanks so much! Saved my life lol
When using line renderer with points with tight angles, I get this funky early curlves, and inconsistent widths.
Is there a way to to make it display EXACTLY the points and widths without this strange lerping at the corners? If not is there another easy alternative that does this?
Hey guys. I've just ran into probably one of the weirdest bugs.
In my inspector i've a set a scriptable object field.
this is my onClick function
public void OnToggle(bool value)
{
print(skill);
if (value)
{
onSelected?.Invoke(this);
}
else onDeselected?.Invoke(this);
Debug.Log("Toggle is " + value);
}
]
the weirdest thing is that it is magically changing the which skill is there. I've checked references and everything SHOULD be fine, but for whatever reason Unity doesnt really want to open the correct skill
it event prints the wrong skill for some reason
events and assignment
public event Action onSkillUpgraded;
public static event Action<SkillTreeSlot> onSelected;
public static event Action<SkillTreeSlot> onDeselected;
[field: SerializeField] public SkillSO skill { get; private set; }
not as far as I'm aware. If Corner Vertices/End Vertices do not suit your needs, you might wanna get into shader-based drawings.
What is this sorry?
Corner Vertices/End Vertices are settings on your Line Renderer component
Looks like it still creates funky widths.
Any alternatives then?
Or should I just make a new component for each line lol?
there are often hiccups with the serialization system. Try making the skill a public field instead of what you have (to reset it)
often this requires deleting the object's meta (or the object itself in extreme cases) and remaking it
yeah that sounds like a decent solution if you don't wanna mess with shaders
Is that reaslitic for 50 lines?
mind though Unity implemented it like they did because it looks weird without any normalization/tweaks for the edges
yeah Line Renderer is not performance heavy at all
akright ty
np
Can somebody invite me to the Kinematic Character Controller discord ? From Philippe Saint aamand
im on some evil wizard code rn
how can I return a reference to a struct within a list of structs such that I can edit the values theirin?
Assign it to a variable, modify, assign back to the list. This is a code beginner question.
you can do it with an array AFAIK but not an actual List
oh
thats a good idea
like ref var element = ref array[0]
sorry, I didnt think of that
I think this is the kind of question where I was missing a step and because I was missing that step it looked really hard
slight complication
I dont know which of three lists it will be in
I don't know why you mentioned AI helping you, since I have already described pretty much everything you were supposed to do.
No, you are not supposed to make the entire advanced rule tile 4 times. You are supposed to derive from RuleTile.TilingRule and add the variables I've mentioned.
Also, why don't you do this in UnityEngine nemespace, and add the suitable static using?
namespace UnityEngine
{
using static RuleTile;
// public class
}
screw it
im doing this the evil way
if I have a constructor for a struct, is that also called when I run the game, or only when I use it via code
Constructor is only called when the struct is created
If you create the struct in OnEnable, Start etc., it's going to be called
but if I create it manually in the editor then no
ok
cool
or its like called when I create it in the editor
If you mean Inspector, it is called if a constructor is accessed
It's gonna be called in the editor.
yeah, thats was it. thanks!
I am sorry, I am new to unity and I have no idea what you mean. This is what I have now https://pastebin.com/J589X4Hd
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.
How is this different from the one you've sent earlier?
I assumed you had an idea what I meant, since you were strongly convinced the normal RuleTile is not suitable for implementing your desired behavior, and were creating your own RuleTile, which might appear complicated for intermediate users
If you don't understand what I mean, you may consider backing down from what you're doing now, since it wouldn't make too much sense, and returning to it after gaining some experience
is this the way to get the gameobject layer number from Layermask ?
int layer = (int)Mathf.Log(pickedUpObjectMask.value, 2);
Are there any drawbacks ?
from what I'm reading ofc it wont work with multiple layers (fine with me) Didn't want to use names, they may change and doesn't seem as clean. LayerMask should have a LayerMask to gameobject Layer method :\
i think they don't provide one exactly because it only works with masks containing single layers
public static int[] IdsFromMask(LayerMask mask)
{
List<int> ids = new List<int>();
for (int i=0;i<31;i++)
{
int and = 1 << i;
if (((int)mask & and) == and) ids.Add(i);
}
return ids.ToArray();
}
I will keep this as extension method then ty.
I have a complete library of Layer methods if you want
there is more that can be done?
sure, wait one
just needed to put my pickedup objects in a diff layer. Didn't want to use LayerMask.NameToLayer 😅
very much thank you 
i still find struggles in bitshift 😅
np, hope it helps
!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.
IMO they should add a LineRenderer2D that wouldn't have this inconsistent width issue
Its seems really silly it does this, do you know why it does? Seems to be useless when it functions like this - what is the use-case for it?
I guess it's alright for 3D when you don't need consistent widths
In 2D they could make it better because you can assume that each face/segment's normal is facing the same way (towards the camera)
I bet you can find something better on the asset store though
Could make the ones returning arrays just return an ienumerable so you don't need to allocate a list + array every time you want to check 🤔 Would then let you use LINQ afterward to make an array if needed. (yours also misses the 31's bit since your max is bit 30)
public static IEnumerable<int> IdsFromMask(LayerMask mask) {
var maskValue = (int)mask;
for (int i = 0; i < 32; i++) {
var value = 1 << i;
if ((mask & value) == value) {
yield return i;
}
}
}
public static IEnumerable<string> NamesFromMask(LayerMask mask) {
foreach (var id in IdsFromMask(mask)) {
yield return NameFromId(id);
}
// or
return IdsFromMask().Select(NameFromId);
}
Use w/e obviously, just a suggestion 👍
Having a look though I can't seem to find anything.
good point, iirc the original use case for these was for serializing the data so I needed the arrays. Good catch on the missing bit though, thanks
Say I have a script that translates a gameobject along the x axis in a sin wave pattern using just the initial cached position(cached when script is initially added to object) + offset
How can I detect if I am trying to move the object manually with the basic unity translation handle things so I can actually change the position by updating the cached position?
I cant just do that normally since I just offset from the cached position and set the transform position to that every update
Sine wave local position, put object in a parent container, move the parent container.
I dont want to have seperate children for the object, I would prefer object/script be in the same gameobject
is ther e a decent way to do this?
Easiest by far is to use a child object.
There's no good way really to detect movement via the Editor move tool
It's not worth it
awww man ok
is there a way to make it only seem like a single object then from the hierarchy/inspector view then?
Just collapse the hierarchy
alright
is there any way to instantiate a material and keep the properties ? when i instantiate an instance from a material all the values are back to default its very annoying
Tbh I thought it would
me too
var newMaterial = new Material(originalMaterial);
_material = Instantiate(_testMaterial);
is what i did
Yeah that doesn't copy properties lol, although I feel like it should 🤔
gah
at least its a simple edit thankfully
meshes copy perfectly and and game objects and scriptables but i guess shaders are different
Hi I want to use structs to define values for different enemies in my game. One of the structs for movement goals needs to be compared to the pathfinding nodes with the same value names. I can do this with reflection but I know this is bad. I think I should make them both arrays. Is there a way I could set up the code to be easy to edit by still having names like that so it could be friendly to non programmers?
Why not:
- reuse the same struct in both places
OR - just write an equality function between them?
I didnt mean to say compare. One is for weights the other is heuristic for A*. I need to loop through them for a calculation on each value
Then I don't understand the question
You probably just want an interface to be honest
If you're just wanting to use strings (names) to access elements of the collection rather than integers, you could probably try using a dictionary.
Anyone have any clue on why addressable.LoadSceneAsync works in the editor but in the build executable it gives:
Scene 'Assets/Scenes/UIs.unity' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
I even call "Addressables.DownloadDependenciesAsync" before
Looks like your scene hasn't been added to your build settings
I dont want it in the build settings
Its an addressable
Its supposed to be downloaded remotely and not included in the build
Maybe im doing something wrong :\
I tried to ask in #📦┃addressables but got nothing 😭
Btw when it downloads and i restart the game.exe
It works
lol
Its like im missing a call to add the scene into the game and it does it automatically on startup
@swift falcon just out of curiosity, what file type doaddressable assets have?
they are encrypted at least to some extent right?
Why does it need to be encrypted
Its served over https
for my case they would ideally need to be
If you want to protect your models sure, but the decryption method is going to be on the client anyway
I don't want users modifying these bundles
and someone can decompile it easily
One other reason i used addressables:
Lets say i have this script:
public class AUnityScript : MonoBehaviour {
[SerializeField]
private AnimationClip _animation;
}
Now if i assign _animation on Unity editor even though AUnityScript is disabled in the scene it will still load the AnimationClip in memory
What we've done to fix this is use Unity's Addressable API so we can control whats being loaded in memory and not
My game was running with 8gb of ram without addressable
Now it runs on 200mb
im planning to use addressables for my mmo game
so that I can create new items and such
its defo needed cause the default unity behavior isn't good enough for huge games
without rebuilding the whole thing
so the server would send the addressables to the user once on patch update
then they wouldn't need to download it again
my last bit im stuck on is scene loading
Note how i only got 1 scene
All my other scenes are addressables and downloaded from the asset loader
yea I watched the official unity video
So the user dont download a huge file for initial
they did it like this
better doing it earlier than having a bunch of code written btw
Made me change some stuff to coroutines
To use Addressable.LoadAssetAsync method and wait for it
Hey guys, just having some troubles with Unity localization. I've just opened a new thread on the forum here. Could somebody give me a help?
hi, i was trying to play animations by code using:
Target.Play(AnimationName, Layer, 0f);
Target.Update(0);
It works but when the animation starts, some variables and components in the prefab, reset their state to the original value, for example if a child of the prefab had active = false at the start and i play the animation, even if the animation doesnt change that variable, the active will be false, even if at some point another animation changed that to true.
I would like to avoid this behaviour and the animation only affects variables that are on the animation, nothing else. how can i do that?
Try unticking "Write defaults" in the animation state
ill try that, give me a moment
uhm nope, didnt work.
Target.writeDefaultValuesOnDisable = false;
target is the animator
Pretty sure this is not what Osmal was talking about