#archived-code-general
1 messages · Page 456 of 1
It works flawless for close waypoints. The problem arises when waypoints are very far: as you can read from the code I forced the Y of the waypoints to be the Y of the player (the camera is above the player, it's a top-down with a 45° angle camera), to be sure that the object is never under the camera. But with far away objects, the object can still be behind the camera, even with the same Y... Has anyone got any solutions?
When the object is very far the arrow points on the other side
For reference, that's a screen of the game with the tracking arrow in the upper left edge (a bit hard to notice when it's not moving). It's tracking a very far away waypoint: the arrow should be in the bottom right edge.
My camera renders UI even when it's disabled in the culling mask
Im trying to do a camera stack, but the main camera doesnt stop rendering the ui
it happens when the stack is empty too
All of my ui is on the correct layer, and is on a canvas
here's how it looks when it set to render nothing
what could be the problem
canvas is using overlay render mode or screen space with no camera assigned
set it screen space and assign a camera
Ooo thanks!
I just opened a project and it already says that I have a problem with VS code, would this effect my code in unity?
Impossible to say. It's not a good idea to have non-normal characters in directories anyway.
You may find later down the track issues with building
I'm not sure what else you have but . should be reserved for file names, not in directories
Well my file name is TCG ; Card gam anything unusual with it?
; is not a normal character to have in paths either
I see i'll remove it immediately then, btw don't i need to delete the project entirely or just change the name of the folder?
You should just be able to close Unity and rename the directory
alr, thx man much appreciate your help!
Its best to just use short path names and no space at the end though I typically use no spaces at all.
Not sure what OS youre on, but if you create a file on Linux for example, windows might have issues with that naming and others could have trouble using version control with your project
I had similar issues at work where someone on another OS had a space at end, or a 260+ character path and I just couldn't interact with it
No worries, my OS is Windows 11, I didn't k now before that we should not include spaces in the folder's name, thx for the advice i'll take it into account
I'm happy to use A-Z a-z _ - and spaces (as separators only)
I actually think I was mistaken and . would also be fine, it's probably complaining about the semicolon but best to be safe and avoid it too
Yea spaces are allowed, just not as the last character I believe. The only reason I avoid spaces is habits from the past
is it possible to change vfx graph props that cant be exposed from code? like shape volume/surface
!publisher
✒️ If you're an Asset Store publisher looking to apply for that role, please DM <@&502880774467354641> with an image of your publisher dashboard to be added. It may take a week or so to get to your request, please be patient.
Can we access the parent of a cloned gameobject from nested children without referencing it in the inspector explicitly?
Yes (via transform.parent) but it's almost always avoidable and might be a sign that your approaching something in a non-preferable way
You did not get my point
I said nested child, maybe it is immediate child or not
you can traverse the "tree" in both directions
I know I can check transform.parent iteratively to find
you can get components in children or get the transforms children
once the object is instansiated, there is no information unity retains for the child to figure out what parent is the prefab parent specificially
but it is not ideal, so the answer we are not able to access the root of cloned gameobject directly in the code
we are
but the root isn't always going to be the prefab object
eg. if you instansiate something as a child of another object
it's on you to determine which parent you care about
Example:
Cloned gameobject (root)
child
child
child
child
child
sure but
Parent you spawned the prefab under
Cloned gameobject (root)
child
child
child
child
child
if this happens what do you want to find
No, I just spawn a gameobject in the scene and I wanna access the root of gameobject from codes assigned to some children, easy
i pointed out this is possible, what is the confusion?
You said transform.parent
you can use transform.root but this will not work if the object is spawned under any sort of other gameobject
transform.GetChild(), transform.parent. you can do this all from any transform
you can walk up/down as you desire
Thanks, yes it is OK transform.root
sometimes it is
but maybe buggy because the spawned gameobjects are in another gameobject, I mean when spawning, pass a parent to them!
correct (that its sometimes): https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Transform-root.html
If you have a component on the "prefab root" you can locate this
I would strongly recomend considering doing whatever your doing in a way where the parent object is doing this work, not the children
this can include the parent object informing the children that it exists
eg. dont make the children find the parent make the parent find the children (and perhaps tell the children where it lives)
Is it possible to construct a color from hex code ?
html = hex ? 🤔
yes, read the damn page 😆
I'm really confused because it's a editor script 🤔
its just their example
You can use it anywhere:
if (ColorUtility.TryParseHtmlString("#FF0000", out var newCol))
{
//Do thing
}
else
{
Debug.LogError("Parse failed!");
}
But here I need it to be inside an array and apparently I need the "out var newCol" part so I don't know how to properly put it directly inside an array 😬
You cant, you will need to write the result into the array post array creation.
If you check the doc page again for the function, it gives the result with an out variable. it returns bool which is the parse success result
You could also make your own function that wraps this and returns the colour as you desire
argh 😬
Isnt there also a Parse without the "Try", which should return the color without a out? Assuming that you are certain your providing valid data to the function
Ah
public static Color ParseHex(string hex) => ColorUtility.TryParseHtmlString(hex, out Color col) ? col : Color.white;
tada
col may already be "white" as it should be default if parsing fails
Dude, it is about colliders. The children have colliders
but the code to do some logic is on the root
yup
hence why the children shouldn't be looking for anything
sounds like a great job for the parent
😆 this really isnt hard to solve
Currently, I assign the root to the script in the children through inspector
ok
This would really not be the preferred way of doing it tbh (undefined/unexpected behaviour)
public static Color ParseHexOrDefault(string hex) => ColorUtility.TryParseHtmlString(hex, out Color col) ? col : default;
public static Color ParseHex(string hex)
{
if (ColorUtility.TryParseHtmlString(hex, out Color col))
return col;
// Could also be a FormatException
throw new ArgumentException($"The given hex value '{hex}' could not be converted to a valid hex.", nameof(hex));
}
☝️
Why this doesn't already exist, idk. Unity does everything only halfway so you kind of get used to doing this.
Why does it say that color is never null ? 🤔
it isn't a nullable type
use the result of TryParse... instead
Color is a struct. Structs can’t be null.
like so ? 🙂
made it better 👍
though as rob and Fused have mentioned if your not interested in using the check to throw an error or log that tryparse function probably returns white if it fails anyway so you could just do
public static Color ParseHex(string hex)
{
ColorUtility.TryParseHtmlString(hex, out Color color);
return (color);
}
not anything really different just mentioning for the sake of mentioning
It doesn't return white
does it return white? i would assume not lol
most likely it returns default(Color)
It returns black with 0 opacity
ah black?
If you read up I already gave a proper solution
You can return Color.White, but this just leads to confusion as to why it's suddenly white in the future
Better to just use a proper check and return either defualt or throw an exception if you want better behaviour (I'd argue returning default is also bad). Just make sure the hex color is always valid
Thanks 🙏
hey, if i have some query where do i ask
Not sure what you mean with some query
If you have a question regarding code, this is the place
Then #💻┃unity-talk is also fine
oops didn't see this thanks
trying to debug an issue with my game
public void HideAndUnhide()
{
HidyHole hidyHoleScript = hidyHole.GetComponent<HidyHole>();
BoxCollider playerCollider = gameObject.GetComponent<BoxCollider>();
BoxCollider hidyHoleCollider = hidyHole.GetComponent<BoxCollider>();
if (isHiding)
{
Vector3 outPosition = hidyHole.transform.position + hidyHole.transform.forward * pushDistance;
outPosition.y = 0;
transform.position = outPosition;
isHiding = false;
hidyHoleScript.HidingPlayer = null;
Physics.IgnoreCollision(playerCollider, hidyHoleCollider, false);
}
else
{
Physics.IgnoreCollision(playerCollider, hidyHoleCollider, true);
GameObject hidingPlayer = hidyHoleScript.HidingPlayer;
if (hidingPlayer != null && hidingPlayer != gameObject)
{
PlayerController hidingPlayerController = hidingPlayer.GetComponent<PlayerController>();
hidingPlayerController.HideAndUnhide();
hidingPlayerController.StunPlayer();
}
hidyHoleScript.HidingPlayer = this.gameObject;
transform.position = new Vector3(hidyHole.transform.position.x, 0, hidyHole.transform.position.z);
isHiding = true;
}
}
I am trying to move the player to the side of the hiding place when the player unhides, but i am getting inconsistent behavior. sometimes it moves to the side, but sometimes, it remains in the center of the hiding place. I tried multiple things but not able to figure out what I am doing wrong
lol why'd you highlight your code as python
what debugging steps have you taken?
oops, generally i code in python hence accidently did that
anyways first step here would likely be to just start debugging, adding logs and such to make sure values are as expected and the right branches are reached
just to figure out what's happening - you can move on to the why and how from there
I tried printing out the positions, so after changing the transform.position, the position of the character is printed correctly, but when i print the position at the start of update, it shows it as the position of the center of the hiding place
you should generally not be modifying the Transform of your player directly if it is using a Rigidbody
that issue may be coming from the Rigidbody, or it may be coming from some other code you have.
I also tried doing controller.Move, but that was not moving it at all
wait you have a CharacterController?
you have a charactercontroller and a rigidbody?
HUGE info you should have shared lol
- If you have a CC, the player should not have other colliders (such as a BoxCollider)
- If you have a CC, you cannot move the object via transform.position without first disabling the CC
you need rigidbody for collisions right? I am not using physics so i have set it to kinematic
A rigidbody is for physically simulating an object
you don't need a Rigidbody if you are using a CharacterControler
uh #🏃┃animation? this is a code channel
oops, my bad! moving this there
Very thorough question though. Almost makes me wish I knew the answer just so I can encourage that kind of full on description in the future but I am not an animator
but the collider for cc is a cylinder right? i need a box for my character shape
not cylinder, capsule i mean
you can have an rb or a cc, but not both controlling the character. both components control the transform (hence the "don't modify the transform" thing) so they will end up fighting
if the cc's cylinder is a dealbreaker, you could use an rb with a box collider instead
i tried doing Vector3 move = outPosition - transform.position and then controller.Move(move) but that is not moving it at all
Isn't it possible to create a dictionnary and add values directly like in an array using {} and "key" for the key ?
or something like this ["key"] ?
is something wrong with my Move?
Then you can't use a CC
CC is a capsule, no choice
removed that and adjusted capsule in similar shape as my box, but the move thing doesnt work
what move thing
this
wdym "adjusted capsule"?
show the code that you are trying now? Did you remove the CC, or you disabled it?
adjusted radius and height
so the CC is still there
that disable is unrelated, i was typing something else and accidently sent
in my case I don't have a class so I don't have fields to attribute those colors too. So that links doesn't help that much except if I'm missing something 🤔
you need to disable the CC to move it via teh Transform
I replaced transform with controller.Move
You are definitely missing something. The link shows you exactly how to initialize a Dictionary. IDK what you mean about not having fields.
that's not going to help you when your other code is calling CC.Move already
the correct answer here is to disable the CC and then move the object via the Transform
oh, I thought disabling it would be not a proper thing to do
Like in the example he has a StudentName class having multiple fields like FirstName, LastName and ID, which in my case isn't the same as I don't have a class and don't want to create a class with each color key being a field of that class. Here I want the key to just be a string not a field from a class 😬
disbaling it and then reneabling does work
The code in the link is just an example to show you the syntax
obviously you would use whatever objects you actually need for your Dictionary
you're focusing in on the StudentName class which is not important
I added curly braces around each entry but still complains about they key
you're not following the syntax from the example code
var students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
{ 112, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } },
{ 113, new StudentName { FirstName="Andy", LastName="Ruth", ID=198 } }
};```
They are not using = like you are
for you each row would be:
{"DARK_GREEN", Utilities.ParseHex("#0F9D58")} for example
{key, value}
just like the example
thanks 👍
= symbol is the thing that confused me
new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } }
you can ignore everything inside here
it's irrelevant to the dictionary initializer
it's just value basically
they were just combining an object initializer with the dictionary initializer to show how you can use them in conjunction
they should put a simpler example
probably
Hello! Im using the Animation rigging package for ik animation during gameplay. I want to be able to change weight of the target during gameplay. In editor i assign 0 rotation / position weight, and when i tell it to, set target rotation weight / position weight to 1.
However, it just, doesnt set the weight in code. The debug.log gets called, the line before gets called, but the target rotation weight / position is still 0 when looking at the component after. How do you set the target rotation / position weight?
rightHandIK.data.target.SetPositionAndRotation(RightHandWrist.position, RightHandWrist.rotation);
Debug.Log("OnStateEnterWateringCan called, setting target position and rotation for right hand IK.");
rightHandIK.data.targetRotationWeight = 1f;
rightHandIK.data.targetPositionWeight = 1f;
``` (If this is better in animation just lmk, chose this bc its code)
TwoBoneIKConstraintData is a struct so pretty sure you need to do this:
TwoBoneIKConstraintData data = rightHandIK.data;
data.targetRotationWeight = 1;
data.targetPositionWeight = 1;
rightHandIK.data = data;```
OH its a struct! thats, a dumb mistake on my part. thank you for the info.
Wait, that didnt seem to work either. gonna try a more thourough google.
TwoBoneIKConstraintData rightHandIKData = rightHandIK.data;
rightHandIKData.targetRotationWeight = 1f;
rightHandIK.data = rightHandIKData;
(found something talking about it in case anyone else needs it. https://discussions.unity.com/t/animation-rigging-package-unable-to-change-weight-at-runtime/804724/9)
answer to my question is probably this:
looks like doing rig weight changes during animation transitions is illegal. i’ve wrap code with weight changes into coroutine with animator.IsInTransion check and now all works like a charm
Is there a proper way to not have these dropdowns on serialized classes without a custom editor?
I would like the settings just displayed in the feature without it being under a dropdown
This is that class.
[Serializable]
internal class SharpenSettings
{
[SerializeField] internal float sharpness = 0.0f;
}
public class Sharpen : ScriptableRendererFeature
{
[SerializeField] private SharpenSettings m_Settings = new SharpenSettings();
private SharpenPass m_SharpenPass = default;
private Shader m_Shader;
private Material m_Material;
Not without some editor scripting of some kind or a plugin, no.
A PropertyDrawer is the most straightforward approach
Ok, will do it with editor scripting then
I was thinking, what's the best way to handle attribute modifiers (like items giving + speed)? A list of the modifiers, that are all sumed/multiplied when getting the final value (and are removed when the item is unequiped), or just a simple variable that is modified on equip and on unequip?
I prefer to use the list of modifiers, especially if you have multiplicative and additive multipliers separately.
Otherwise it's hard or impossible to recalculate the value when an arbitrary modifier is removed or expires
Hello guys, one question about virtual properties, Imagine that I have a virtual property with its respective field, in a child class I want to override the Set method to add a small validation, but of course, to access the original field of the parent class it must be public, which will allow it to be accessed from the child class, enabling access without using the set method, allowing them to bypass the validation. Is there any way to avoid this? I was thinking about having each child class define its own field, but I'm not sure if that is the best way to solve this.
it must be public
no it doesn't
access levels aren't limited to public and private
sounds like you'd wantprotectedhere
Hey, Thank you!, This is exactly what I needed! this solved my issue
If I want to exclude a specific collider from a raycast is there any better way than storing its old layer, setting it to a layer that the raycast will ignore, then setting it back? Ideally, I'd like to have them all on different layers so I wouldn't need this switcheroo, but for Render Feature purposes I need them all to be on the same layer
Not sure if you can specifically exclude a collider without layers, but maybe what you could do is use a non-alloc raycast, which means it will be included but you can then loop through and filter out the specific collider after with a second "exclusion" list?
That might work. I dunno what's lighter, that or the layer switcheroos. I'll need to check
does anyone know whats the best way to procedurally spawn objects in a maze, like if i want to spawn a cabinet that like hugs the wall whats teh best way to do that
is maze premade ?
no
is procedurally generated too
do you want the code
could probably get all surfaces that have a specific normal direction then shoot some rays and casts and figure out placement
hmm, im not sure how to do that though
break down each part, learn them separately then combine them into your final usecase
procedual anything can be tricky, if the walls are prefabs you could potentially get away with placing some premade gameobject as empty points to potential spawns, then you can put them in array and pick random one when generation is done
do you think if is easier to just create a bunch of rooms and spawn those instead, or procedurally create a maze, and randomly spawns the object in with rules
or I thought of a new idea
I'm thinking of using a hybrid system for the game, like the maze walls will be procedurally generated using my current algorithm, but instead of randomly placing objects, each floor tile will have several possible preset variations, and I will setup rules for how these floor should spawn, like when there is a deadend have a floor tile that contains chests etc
depends on the situation, I found rooms/sections easier sometimes, cause they can have their own local rules for specific props
Can't you just use a separate gameobject for the colliders instead of having them on the renderer gameobject
is this a thing now or is rider just bullshitting me? InitializeOnLoad should be enough no?
that's for when you have Domain Reload disabled when entering play mode. static members do not get reset with domain reload disabled and since that is not readonly it's possible to change the object stored in it. so you'd want to reset it inside of a method called with RuntimeInitializeOnLoadMethodAttribute
even if you haven't touched the setting you've got analyzers that check for it.
ah
this appears to be from the Project Auditor package's included analyzers
that would make sense as to why I haven't seen it before, i did just install it
except I haven't checked off 'Use Roslyn Analyzers' so maybe Rider is just using them anyway
https://paste.mod.gg/zsyiyjglepmv/0
Does anyone know how to make this spawned rotated the right way, because currently is rotating based on the closese wall, but i dont want to do that as you can see here
A tool for sharing your source code with the world!
i want it spawned like this
i have absolutely no clue what you're trying to show with the screenshots. What is object is "this"
you coded it to work with the closest wall. Dont do that if thats not what you want
Im guessing AI code?
so basiclly is a
maze generator right
and i want to have different object on the floor,
so i figured I should just randomly generated different like "presets" of the floor, and spawn it on the floor
one issue im having right now is I want the object to have a whole wall on the back
so i tried using a point to trying to figure out the closes wall
but if the wall spawns vertically
it will rotate the wrong way
so something like this
you can type in one message instead of 10 different ones.
also part of this is still unclear like what you mean by "if the wall spawns vertically" or really what your end result should look like. did you write this code? Parts of it are very questionable. If all you're doing is spawning the door in this location, then rotating it, that isn't going to move them closer to the other wall which is what it seems like you want.
stuff like this is probably easiest if you step through with the debugger and see whats happening line by line so you can see where your algorithm is going wrong. Also reconsider that logic around line 35. you seem to be calculating the direction of the raycast, when you just used the direction in the raycast.
Or maybe it seems like obj is the floor in this case? In that case then its still a bit odd what you're doing with this orientation object. Maybe some of your values there aren't aligning to what you think it may be. I notice you also have Debug.DrawRay in there. Id suggest drawing it as green or red conditionally if it actually hit an object.
sorry bad habit, anyways what i meant by if the wall spawns vertically is like if you looked at the maze from the perspective, and I did use ai for only the object rotation part of the code, which I just follow the direction the ai gaved and it kind of worked i guess
yeah the obj is the floor in this case, i have another idea, which i dont think is the best but probably would work
so basiclly instead of raycasting one time, i just have a list of empty object that raycast the back of the drawer or whatever, and if lets say all 3 of them hits a object with a wall tag, it sets its rotation there
what do you think of this possable implementation
sure, that is something you can do. Thats seemingly what you were already trying with that orientation object.
you should really learn to debug rather than just copy pasting AI, especially if you dont understand what the code is doing
since this is maze generation, itd probably be better if this floor already knew where walls are in regards to it. though im not sure what kind of data structure or algorithm you're working with there
I was surprised to find yesterday, that assigning a value to a property was 4x slower than assigning to a field - at least when using a Stopwatch to benchmark.
I had thought JIT compilers basically give properties and fields near identical IL. Can anyone explain why assigning a property could be so much slower?
jus tnoticed I am not seeing the debug visuals for wheel colliders in 6.x
the overhead of calling a function, probably
I would have thought the JIT compiler would inline the property’s method body, eliminating the need for a separate function call. head scratch
i mean compiler optimization is kinda fickle isn't it
maybe it does in specific cases?
You’re probably right
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
They are identical, at least with an auto-backing field: https://sharplab.io/#v2:C4LghgzgtgPgAgJgIwFgBQcDMACR2DC2A3utmdgA4BOAlgG5jACm2NAdsJVQPYXHYBzJsADc2CMLEBfUuWr1GLdpwBmNJgBsAJiNlk9uHHAAs2ALIAKAJTED5Lr2wBebEl1p79tZq3PX7+xk0KSA
Stopwatch isn't reliable for micro-benchmarks
also debug and release builds are different
Ah, in this case it’s not an auto backing field. But it is just a getter and setter to an explicit backing field.
Thanks for this info. Is there a better tool to use than Stopwatch for testing something like this?
Very different results with .net framework and mono though
Looks like I need to learn more about benchmarking code
What happens if you apply MethodImpl(MethodImplOptions.AggressiveInlining)?
Between a field and property?
Yes
Unless you did something wrong
Even calling a function takes no time at all. Especially aggressive inlining considering it gets rid of it altogether (AFAIK - not sure)
Must be a testing methodology issue. :/ I’m literally getting more that a 4x slowdown with a property.
Testing approach:
-
just a float variable, with a property that has getters and setters to that same float.
-
first test: iterating 100,000,000 times over a line that just assigns the float.
-
second test (in a separate run): doing the same thing, but assigning the property.
Assigning the field: ~972ms
Assigning the property: ~4200ms
What build are you testing in?
Hard to figure out how JIT, cache misses, or the GC could be interfering with the results. But I hadn’t accounted for:
- the difference between editor/debug/release build timing.
- the difference between .Net and Mono
Editor - probably stupidly
Debug, Development, release?
Probably.
oh thanks
Hello,
I am using unity 6000 and terrain trees and infinite terrain.
I want to be able to add monobehaviors to my trees to be able to keep track of the tree's type, hp, state, make it fall, add rigidbody etc.
I know terrain tree's can't have monobehaviours, so what can I do?
My current thought is I need to have a tree manager that subscribes to OnTileGenerated, OnTileEnabled, OnTileDisabled and keep track of every tree instance based on location. I also need to switch terrain trees with prefab trees close to the player (5 meters - ish). Is this doable? WHat are better alternatives?
No idea, but there is some API that suggest that you can get the Tree from the Terrain.
https://docs.unity3d.com/560/Documentation/ScriptReference/TreePrototype.html
https://docs.unity3d.com/ScriptReference/TreeInstance.html
yeah you can get the instances: cs var trees = terrain.terrainData.treeInstances
which means you likely want some sort of "tree manager" per terrain. You'd keep track of all the treeInstances in a big list, you can get the position (0-1 a percentage of the terrain size, so some calculation needed to convert to world pos). From there, you can:
- loop through the list and use Physics.OverlapSphereNonAlloc at the tree position or similar for checking whether the player is near/chopping the tree down
- keep track of hp for each treeInstance
- spawn a "falling tree" prefab at the tree position when the hp is 0
Can I efficiently remove a tree from the terrain using the API (without obvious stutters)?
you'll need to make a new treeInstances array without the tree you want in it, which likely will have a bit of a stutter because it'll be a big array 🤔
you might be able to replace it with a tree that has zero scale though, which would mean replacing the one treeInstance instead of the whole array
which would be much faster
yeah it looks like you can do that - you'll want to test it though!
So it seems that the key of a tree is its position (the link between a colider and the data associated with it).
I am also assuming since a tile can have 1000s of trees, it would be better to break a tile up into quadrants and only check trees that are in quadrants near a player?
They don't use terrain trees. Or Unity terrain.
DOTS ECS would be my choice for such a large amount of interactable objects. It's not impossible with GameObjects but the engine will hate you.
Thanks!@
Valheim is also not the epitome of technology but it predates DOTS so we won't hold that against it 😏
It uses some type of voxel terrain. Trees, I think, are just GameObjects. It uses a low draw distance to get away with it all.
the ideal answer is probably never the one the game your thinking of uses 😛
what is DOTS used for exactly?
ECS is a replacement for GameObjects / components that handles large amounts of objects better
So when you're talking "infinite terrain with trees you can cut down", it starts to sound like an attractive solution
Dots is not just ecs. Jobs system and burst compiler are all considered parts of dots and you can use these without ecs.
For my game there will be a bunch of buildings throughoit the map. The player will enter these buildings (through a prompt on the door) and collect loot, then leave. There is going to be several large (premade) buildings.
How could I make so many buildings in one scene, or would I load a new scene. I'm not sure how I would transfer data about the player throughout scenes. Plus, if there are a bunch of these buildings, how do I save the scenes and .make new ones when the player leaves and goes into a building of the same structure?
I was thinking I might be able to somehow load the buildings under the map and teleport the player in. I might be able to load buildings, then when the player searches a building and leaves I could block off the door so I don't need to save it to storage.
But I don't know how practical that would be. Any advice?
ECS and subscenes would be a better/ modern way to do this
ECS?
Unity's entity system
google -> unity entities / unity sub scenes
you can load a sub scene pretty much instantly -> tele port in / out
It'd be perfect for open world games if only it had a functioning terrain system like the one they canceled
Depending on what's in them, are you quite sure you can't just brute force it?
Unity truly doesn't mind having 100,000 objects in memory
"large premade buildings" is a very unclear scale ye
My game is inspired by lethal company and repo. The buildings will be somewhat mansion sized and they won't be procedurally generated.
Wrong message to reply to mb.
I get it
i have some pretty good experience with lethals dungeon generation 😄
Do you mind if there's a hiccup / loading screen?
the game uses this plugin if your interested in learning more about that specific approach
https://assetstore.unity.com/packages/tools/level-design/dungen-15682
right, this sounds like just loading between different scenes and learning how to pass data around would be the better solution
I don't mind if there's a loading screen, no. Although my main goal for this project is immersion, "The Complex" level immersion.
LoadLevelAdditive is probably a good bet.
how do I save the scenes and .make new ones when the player leaves and goes into a building of the same structure?
and they won't be procedurally generated.
little confused on what exactly you want saved here? the looting/exploration state?
There will be limited building types, but several of those types. So the player might stumble across one building, and find the same building with different loot at a different door.
Basically the positions of doors in the world is procedural, but the buildings appear more than once.
I'm not very good at explaining things.
There will be multiple instances of buildings.
But few types of buildings.
Does that make sense?
That seems super useful and I'm upset I didn't know about it sooner.
Thank you.
Also I'll look into this, it seems interesting.
Thank you
I currently pass settings data across the main menu and main scene using a class to store the settings and a class to save/load the settings in each scene.
But LoadLevelAdditive would make this process so much easier.
(For more comparable contexts, lethal uses additive loading where the ship is in a scene that never unloads and the moon is in a scene loaded and unloaded additively)
Im working on making a fighting game right now, and im using Physics2D.OverlapBox to damage each collider after a attack is called, but once a collider is hit, the attack function is called ~20 times per second until the physics box is no longer overlapping. I'm having trouble figuring out why this is, would it be possible to get some help?
Please view lines 87, 1667, 1743, 1938, and 3043 for relevant code
that's a terrifying file
holy shit why is this script 3k lines

jesus christ that attack method alone is over 1000 lines
That’s not even the whole thing
Oh I see, my phone gave up and didn't load everything
i don't mean to pile on with the previous comments and point out something unrelated but maybe dont do this one
private void OnDrawGizmos()
{
GameObject point = GameObject.Find("StandWestPoint");
}
Do you know how to use a debugger?
Like I'm not gonna debug this just by looking at it 😄
This is... wow
true thats pretty heavy esp in Gizmos function.. tha'd be the last of my problems if this were my script how can anyone debug anything in this mess lol
pointed it out because its big severe : easy to fix ratio
It also does nothing
(does stuff i just removed following said stuff)
Oh
Not through unity, but is that what I should learn to do right now?
Yeah that'd be your best bet at making sense of that.
Cleaning up the code would also help
Sounds good
The FindWithTag at the start of update is also pretty rough
Most of it is commented because I’m figuring out the best place to put everything by the way
there's also a lot of repeated code here
seems like a few dicts would help
or perhaps a list of your lists
Hey, so I've been working on a procedural chunk generation script. Currently, it uses wave function collapse with a few randomly placed water and grass chunks to generate the land mass and water mass, then finds any grass bordering water and replaces it with beach. I'm now trying to think of strategies to spawn forest chunks, and I'm wondering what kind of generation techniques are usually used for this. I've considered choosing a random grass block, spawning forest, moving in a random direction until it finds grass, then replace that, go back to the root chunk, repeat until a random amount of trees have been spawned for that forest. This causes issues however if the total number of trees it tries to spawn is less than the total landmass it's on, it fails. So I considered creating a list of all grass chunks that don't border a beach, then randomly changing half into forest but I feel like it would look too chaotic. Am I on the right track here?
I should mention this was the previous version which used just one generation cycle with adjacency rules to spawn water, grass beach and forest chunks but as much as it is more dynamic, it's not very realistic / doesn't make much logical sense
Hmm, bit of perlin noise as a first step maybe?
what is the best way to check if an object is visible by the camera?
Renderer.isVisible can give true even if it is not in view i believe
visible period, or more specific checks like within the frustrum or has line of sight to the camera
in sight, like if player is playing, they can see it
WorldToViewportPoint and the check if it is within bound?
You have if (sprinting = true) at line 178. You want == to compare instead. = will set sprinting to true
well that wouldn't check if it was behind anything or not
you could use that along with a raycast to if there's something in the way, i guess?
actually no that would just check for a specific part being visible or not
i dont care if it is behind something, just should be within the rectangle of the camera
in my game it cannot be behind things anyways
When i click on a scriptable object, is there a way i can get a callback for when that scriptable object is shown in the inspector? Or even when it is hidden (ie: something else is selected)
Hey,
Why do I have a null reference exception even tho my tiles 2D array contains something please ? 🤔
it contains a null value 😄
😐
how ?
the tiles array itself may not be null, but it contains null elements because it's filled with whatever is the default for the type when initialized and the default for a reference type is, of course, null
is there a way to check if there's a null value in that array without looping on all of them or is it mendatory to loop on all of them and check first if they're null ?
you don't have to loop separately, just null check it right there in your loop you already have and create an instance if one does not exist already
var thing = myArray[x, y];
if(thing != null)
{
//Do stuff
}
The instantiation is done in another method but I see, thanks 👍 🙂
If its not a monobehaviour you can also do: array[x,y]?.DoThingy();
but in this instance id not recommend that if this confused you
in this specific case though that isn't useful because you can't use the null conditional operator on the left side of the assignment operator until c# 14
wait what ? Why does it work only with "Monobehaviours" ?
It does NOT WORK with monobehaviours
I doesn't, I'm familiar with that syntax 🙂
? is not safe to use with unity objects because of unity weirdness relating to doing == null comparisons
here's why it does not work with UnityEngine.Objects https://unity.huh.how/unity-null
So it's a bug or it's intended ?
for stuff deriving UnityEntity.Object, == null and is null are different.
you usually want == null.
the ?. syntax uses is null, so it's not that it doesn't work, it just works differently and is most likely not what you want
just dont use ? right now 😆
It feels like the IsValid() method in unreal where it checks both if the reference is not null and not in the process of being destroyed
Yea its similar but its too late to change things
stick with
var thing = myArray[x, y];
if(thing != null)
{
//Do stuff
}
late for unity ?
i think its too late to change. You could only really replace == null safely with an extension method that checks for null and valid state.
they should add an IsValid() method because it makes more sense than what there's currently 😬
there is also just a bool cast/conversion
Rider nowadays recommends checking for "Unity null" with the bool conversion instead
does this seem good ?
why would this run before your initialization anyways
that seems like something you should look into
Tell me more
same as you did there
the double access will probably be optimised away but tis a tad lazy
is it actually recommending that? or is it just not giving the same warning that it gives for the explicit == null check? because the implicit cast to bool does do the exact same thing, and they have previously admit in the past that they overlooked that when making their analyzer
x != null and x in conditions are equivalent - same for x == null and !x
for any x that derives UnityEngine.Object
wait what, isn't x equivalent to x != null rather ? 🤔
yes, i messed that up
phew 😄
not sure fully I understood what you said, but it's recommending to use the bool cast for explicit check
either that or use is null if I'm not checking for "Unity null"
a bool check is not explicit, no
if anything it's more implicit
the actually explicit checks are either private or internal, unfortunately
ah, looks like they finally updated their suggestions there. and they suggest the implicit cast to bool because it shows intent to check the lifetime of the UnityEngine.Object rather than the possible intention of a pure null check
I don't really like this suggestion too much either, but it is the only way to make the check explicit
I'm working in a game with a similar mining-building mechanic to that of terraria. I have a Tile struct and a custom grid class and I'm trying to think of the best way to store different types of blocks which will have different textures, different break resistance, different things they might do on place... What would you recommend?
data like the textures or break resistance are pretty easy to store on scriptable objects. different things to do on place you could code through inheritance or composition, whatever way you find fits your flow better.
Thanks, what would be the best way to have a looot of block types, though? I think having a inherited class for each block seems inefficient and scales pretty bad, I don't know, maybe it's how other games do it?
definitely not separate classes, no
Good afternoon everyone! I'm trying to get a character to look at specific objects in a scene. Right now I'm just trying to get the function working in general. I managed to get the normal rotation working but now I want to clamp the X and Y(?) axis to prevent the rotation from looking unnatural and I'm at a loss of how to approach this.
Here is how my code is set up. There are no references to other scripts.
https://paste.mod.gg/hvtmxbhcmesz/0
A tool for sharing your source code with the world!
thinking of terraria, i dont think you need an inherited class for each block type at all. The inheritance or composition would only apply when you need different functionality. Been awhile since i played so i dont remember exactly what blocks are there, but iirc you can toggle stuff like switches? That would be different functionality.
if you just had 2 blocks where the functionality is the exact same, whatever the base block can do, the only difference being the texture, the only difference would be creating 2 SO assets and providing different textures.
Overview of my steps are:
- Get a
Transformreference to the head. - Store the initial rotation values (this is for later when I want the character to rotate it's head back to it's original position once it hits it's rotation limit.)
- gain direct access to the head's x and y, rotation value so I can use the mathf.Clamp function limit the rotation.
- Put that information back into my head reference and use Slerp to have it gradually look at a target.
What currently happens is that it...kinda doesn't work. It looks towards the initial target object but vibrates and place.
have you tried using the IK package? Im pretty sure this is already built in
or sorry it mightve been "animation rigging"
I have! Bone Rigging right? I was testing this out with a downloaded asset but...I think the OP did not correctly orient the animation skeleton from Blender to Unity so when I tried multi-aim constraints it just has a broken neck and I don't know what combination of up/forward vectors to use to get it to work properly.
So I figured it wouldn't hurt trying to do it the code way just to see. This is the asset pack in question https://assetstore.unity.com/packages/3d/characters/lowpoly-character-chibi-315595
If anyone has used it and knows what settings to put for the multi-aim I'm all ears but in the mean time I'm just using a simple 3D cube gameobject (with no rigging)
The end goal is to eventually have the character be able to look at anything under a specific list then after X amount of seconds it looks somewhere else. Like how Animal Crossing characters walk around in their homes.
Does anyone know why my visual studio intellisense isnt working, I have tried everything, retarting my pc, reinstalling vs, restarting unity, reinstalling the unity package
why tf was my Visual Studio Editor package deleted wtf
that fixed it thanks
didn't you just say you reinstalled the package?
then are you sure you didn't just forget to install it again after the last time you uninstalled it? that's really the only way i can see it having been deleted if you had been explicitly installing it multiple times
I meant the package
in the
visual studio installer
that's the workload
oh
Yea I think it was the multi aim constraint. I haven't tested around with it in some time but it should be customizable enough to make work as you want.
with your code, im not positive as to why its vibrating in place but it could be because of the headBone.rotation.eulerAngles part. When you read the rotation as euler angles, its converting it from the quaternion. The conversion could give you any set of euler angles that equal the same rotation
Yea I think it was the multi aim constraint. I haven't tested around with it in some time but it should be customizable enough to make work as you want.
In this case the component worked fine ( I tested it out on some dummy gameobjects) the problem is the placeholder asset itself. I could techincally say "Yeah I know this works" and leave it broken for when I put the new stuff in but seeing it not work annoys me so here I am lol.
im not positive as to why its vibrating in place but it could be because of the
headBone.rotation.eulerAnglespart. When you read the rotation as euler angles, its converting it from the quaternion. The conversion could give you any set of euler angles that equal the same rotation
what do you suggest I replace it with? The reason I did that is because I'm trying to restrict how far the head can move left/right, up/down using mathF.Clamp
But everything I've searched for deals with active inputs and this character is just moving around autonomously. I feel like I'm close but I'm not familiar enough with rotations to know how to get the current rotation of an object the same way you would get the specific position. transform.rotation.x/y/z always turns up an error for me.
Okay I got the Slerp to work normally again.
But I need to test if the rotation limit is actually happening.
i would probably start with comparing where the character is facing and the direction to the object to get the angle. Like through Vector3.Angle or even just compare the quaternions with Quaternion.Angle.
theres a few quaternion methods you could probably use like Quaternion.RotateTowards or AngleAxis to construct the final desired rotation
reading euler angles here at any point will be questionable
I'll see what AngleAxis does. I already have the code working that it looks towards a specific object. What I'm trying to do is have it not turn pass a min/max angle limitation.
where is the code question ?
There is no channel for animator help
you mean the one named #🏃┃animation ?
With a 2d chunk map, what kind of pathfinding algorithm would be used to find, for example, all grass blocks in one land mass? The idea is to figure out how many grass blocks there are per land mass so that I can make sure the forest generation doesn't try to replace more grass blocks with forest than there even are available to change
Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly colored areas with a different color, and in games such as Go and Minesweeper for d...
Interaction.onInteract = new UnityEvent();
Interaction.onInteract.AddListener(() =>
{
Logger.LogInfo("interacted!");
});
Interaction.onInteract.Invoke();
For some reason, this doesnt log
I know that Interaction.onInteract is a valid unityevent slot
if the unity event is serialized it already has a value
otherwise, dont use a unity event (and use a real event instead)
have you confirmed the code is actually running?
or that the logger itself works as you expect it to
Could you elaborate
[SerializedField]
UnityEvent unityEvent;
^ this is given a value by unity, no need to = new();
public event Action MyCoolEvent; <- normal event
unity events replicate event functionality and allow serialized subscriptions but these are slow
Hey, I have another question please :
For some reason my code colors properly the revealed tiles but not the not revealed tiles. So the code should :
- color the revealed tiles in BEIGE and LIGHT_BEIGE in a checker pattern [WORKS] ✅
- color the non revealed tiles in LIME and LIGHT_LIME in a checker pattern [DOES'NT WORK] ❌
You can get your answer by hovering over the underlined else
See what your IDE says about it
it says the else is redundant but after removing it the issue remains
the issue might be elsewhere then, not within these 3 lines of code. This should work as is
yeah the issue could simply be that the colors dictionary has the same color for two of the keys
Ah, my bad I thought there was a return statement outside the brackets. You should probably use some logs or the debugger to find out what's happening here
nope
someone needs an enum
for the keys ?
yea
Perfect, thank you
can you stop posting screenshots of code? i'm sure by now you've seen how to correctly share your code dozens of times.
but don't enums return an int value making the key work both with MyEnum.value and an int 1 ?
my bad
So, if it's an even cell, you want it to be beige if revealed, otherwise red.
And if it's an odd cell, you want it to be light beige if revealed, otherwise lime.
It looks like the "Red" isn't working, so either that color is wrong, or it's never both even and unrevealed. Try some logs to see
er no, you can cast enums to and from int but thats explicit
enums are backed by an int and can be cast to and from them, yes. but there is no implicit cast
You'd need to cast it, but yeah, if you wanted to
the council has spoken
my bad not red, I put red for the test just to see if I was blind with colors or not, but the proper colors should be LIME and LIGHT_LIME
(for unrevealed ones)
just a sidenote, you should group by isRevealed first rather than the parity
Well but that should print shouldnt it?
from those 3 lines alone and if Logger works as expected, i believe it should. thats why i say the issue might be elsewhere.
like whats the context here, where are you running this code?
Its not steralized
why ?
then it can have children!
use event instead
you can use Action to define one easily:
public event Action event1;
public event Action<int, string> eventWithArgs;
I cant change the code for defining the event
while i also prefer to use c# events, its not like UnityEvent is impossible to use here. the performance aspect really doesnt matter
if its not serialized there isnt a good reason to use it
if its on a monobehaviour/scriptable object and serialized then it has some benefit
I personally avoid them where possible as i dislike how hard it can be to check subscribers later
Interaction is a instance of the class interactable, which holds a definition for a unsteralized public UnityEvent (onInteract)
And I cannot change that
then wack who designed it and stop setting it to a new instance?
its not a monobehaviour or SO ?
the only thing id suggest to check around is if you new onInteract or set it to null at any point. the basic idea of newing a unity event, adding a listener, and invoking the event works.
im puzzled at what this thing is
Its a plugin
can you say what?
its confusing to me as i presume the plugin object invokes the event but why would they not even give it a value on construction?
just for better grouping - LIME beside LIGHT_LIME, BEIGE beside LIGHT_BEIGE
wha
As a persistent event
in the inspector?
What
you said "in the editor"
so it is serialized 😐
🤷♂️ if you both wanna focus on the plugin or c# event/unity event thats fine but none of this is actually solving your problem.
im trying to figure out what they are doing wrong
if you can see a GUI thing for it in the editor YES
thus you should not do = new() as you may break functionality
All I know is that the events for other instances of the Interactable class are assigned in the editor
whats wrong is that we aren't looking at the context surrounding the object. it literally doesnt matter if its serialized if all that code is running sequentially. Which is why im trying to get context surrounding the code
ah so a mod?
Yes
i want my time back
But its still a unity problem though
Shame.
are you like modding a game or have modded unity?
Cmon nobody responds in the bepinex server this is like my last hope
A game
very interesting rule...
Welp.
so I finished coding my very small college project and when I went to build the game, I got this error for the script I've pasted to this message:
"The type or namespace name 'ShaderKeywordFilter' does not exist in the namespace 'UnityEditor'"
I searched up a solution for this and it told me to put "#if UNITY_EDITOR" at the very top of my program and "#endif" at the bottom of the "using" section at the top of the program. This didn't seem to fix anything, since I now get another error when I go to build, which is the following:
"The type or namespace name 'MonoBehaviour' could not be found (are you missing a using directive or an assembly reference?)"
Do you know how I can fix this? I am completely lost https://hastebin.com/share/ugezikejab.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you want to do this instead:
#if UNITY_EDITOR
using UnityEditor.ShaderKeywordFilter;
#endif
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
oh
and also surround your editor only code
just remove the preprocessor directives and line 4, you don't appear to be using that namespace anywhere anyway
What you've done here is make your entire using block only exist in the editor. So when you build, UnityEngine no longer exists
oops, I probably misread that solution, I'll try it now
I think box has the idea. You're not even using that namespace anywhere. Just remove it
alright, those lines automatically put themselves there when I made the script so I had no idea if I needed them or not
that one would not have been added automatically when creating the script. you probably auto completed something and either weren't paying attention to the namespace it said it was using (and therefore it added the incorrect namespace) or later removed whatever was using that namespace
I logged and I have 50 that should be LIME and 50 that should be LIGHT_LIME so it doesn't make sense why everything has the same color 🤔
public Color GetTileColor(int i, int j, bool isRevealed)
{
//print($"[{i}][{j} - {isRevealed} - {(i + j) % 2 == 0}]");
if (isRevealed) {
if ((i + j) % 2 == 0) {
return colors["LIGHT_BEIGE"];
}
return colors["BEIGE"];
}
else {
if ((i + j) % 2 == 0) {
print("Light_Lime");
return colors["LIGHT_LIME"];
}
print("Lime");
return colors["LIME"];
}
}
log the actual color too
Well, then either colors["LIGHT_LIME"] isn't what you think it is, or something else is recoloring it after this runs
I could switch it to red just to be sure
maybe it was OnGUI? Wait no, I think I remember accidentally autofilling something. Anyway, it seems like it's building successfully, thank you guys!
like print(colors["LIGHT_LIME"]); ?
sure, or maybe add more than just a single piece of data per log
where in my code ?
where do you think
at the top of that method ?
no wait
I can't do that
so I have to put a print in each place where I return that color
public Color GetTileColor(int i, int j, bool isRevealed)
{
//print($"[{i}][{j} - {isRevealed} - {(i + j) % 2 == 0}]");
if (isRevealed) {
if ((i + j) % 2 == 0) {
print(colors["LIGHT_BEIGE"]);
return colors["LIGHT_BEIGE"];
}
print(colors["BEIGE"]);
return colors["BEIGE"];
}
else {
if ((i + j) % 2 == 0) {
print(colors["RED"]);
return colors["RED"];
}
print(colors["LIME"]);
return colors["LIME"];
}
}
so you've now confirmed that it is in fact returning a 50/50 mix of two separate colors which clearly indicates the issue is elsewhere
Okay, so then these are returning the correct colors. That means most likely something else is changing them after the fact
but again, you should print more information in your logs. instead of a single cryptic piece of data you can include that data as part of a string containing more context
I don't understand what that means and what other infos to print 🤔
I suspect this method as the culprit :
private void OnMouseDown()
{
if (Revealed) return;
// Make the first tile never be a mine
if (!firstClick) {
firstClick = true;
if (Value == -1) {
Value = 0;
}
OnFirstTileClicked?.Invoke();
}
Revealed = true;
spriteRenderer.color = GetTileColor(Coords.x, Coords.y, Revealed);
textComp.color = GetTextColor(Value);
textComp.enabled = true;
}
i'm not saying you need to print more info here now since we've already determined this is not the issue. i'm just saying you should provide more context in your logs just in general so instead of just seeing random pieces of data in your console and then needing to already know what that data is supposed to be, you can instead provide words and other context
Literally everything. Whenever you have to print stuff, print absolutely everything you can so you don't need to go back in and add more later
Your new best friend: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
But I promise you here I don't see what else should I print 🥲
that's why I'm kinda confused 😄
Yes, now you're fine. But it took like three iterations to get all the info
If you had printed the object, the indices, the isRevealed, and the color all at once you could have saved yourself a bunch of reloads
oh ok 😄
So could the issue be here as I don't know if that method is called every frame or not 😬 ☝️
did you know that you can look at the docs to find that out? https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
https://paste.mod.gg/xbvuzcpciqcg/0 here's the full code
A tool for sharing your source code with the world!
I think they mean stuff like $"color chosen for cell at {cell location} is now {color chosen}" so that you know what that color is coming from
why do you reset before generating
this is unrelated to the current issue, but that's exactly what i meant here #archived-code-general message
Because later I want to have a reset button but without opening the scene again
that doesn't matter
i'm talking about what you have right now in StartGame
anyways, the issue is you never set the color when you generate the tiles
in GameManager:166, you just get the color, you never actually do anything with the color
Okay now show us where you use the return value from GetTileColor
nowhere
so what does that tell you?
I have to use it, I'm doing that right now, thanks 👍
Let's go 😄
anyways, about this - think about what StartGame does
it's saying to reset the grid before you even create it
as I said it's there once we finished the first game, that's why I added that first condition to make sure "tiles" isn't null before executing the code below. But I think this will still create an issue as you (or someone else) explained to me above where "tiles" could be not null but the values in it are null 🤔
that literally just is not a concern right now
there's also literally 0 reason to call ResetGrid in StartGame considering it only does something that GenerateGrid already does
you can call just ResetGrid and not GenerateGrid when you restart
you're trying to think ahead but you're skipping all the logical steps lmao
But the instantiation happens in GenerateGrid
I know why I made that mistake
and do you need to instantiate all the tiles again if you don't reload the scene?
they all still exist
because at first I thought about destroying all the tiles in the grid and instantiating new ones when the game restarts
the entire point of not reloading the scene is to avoid having to generate new tiles, no?
even then you wouldn't have a Reset before you generate
Yeah, but I'm thinking about giving the player the choice to change the grid size between games, so in that case I will need to clear the tiles and instantiate new ones to the new grid size
yeah
and you can call generategrid then, not every time you restart
you're stuck in this right now lol
yes that's my main issue that I have in everything in my life 😄
yeah you need to slow down and actually think through these systems
my brain can't do that 🤣
my brain is already thinking about creating the next Windows 🤣
Why is there these black / dark lines around each square plz ? 🤔
what sprite are you using? the 2d elements square?
I imported an image square
does it have a border
if you have the 2d feature, yeah
2D feature ? What's that ?
did you create your project with the 2d template?
I don't remember 😬
if so, you'll have the 2d feature installed
you can check in the package manager
2D Sprite specifically comes with some sprites
It says "unlock" 🤔
since it's not in Assets, you'll have to click the "hidden" eye thing then search for "square"
...ok? that's in a button
not sure what you're expecting
thanks, that's working 😄
I'm confused on why it's "locked"
it's part of the 2D feature
can you change the position of gameobject with NavMeshAgent with transform.position? I have an object which goes to another object and when it is near, it should go inside the other object, I am doing agent.isStopped = true before that, but transform.position is not changing the position
you have to disable it first iirc
or there are methods to use
You can but there are some scenarios in which you could have issues, for that reason the NavMeshAgent have a warp method that allows you to move the agent in a "correct" way
ah yeah thats the method I forgot about..Warp
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent.Warp.html
Hello guys, I have a question about properties and herency, Please check the following code:
This is being overriden in a child class with the following code:
it works but something is telling me that this is a bad practice, basically if I forgot the "base" in my set method I could cause an infinite loop, what do you think?
is this a common practice? or am I writing poor code?
poor code imo. Your property doesn't look like it has side effects, but it does for subclasses. It would be better to make it a private field and expose a public method to change it explicitly, which would then be specialized by subclasses if needed. What does your parent class do with this property? The fact that subclasses are implementing logic when its value changes and the parent apparently does not is smelly
even wrap does the same
i am not update the position anywhere else in the code
Basically the parent class contains the basics fields and methods that a controller/player must have(move, jump, grab something, etc), Then I have two child classes that works in a different way since the two controllers are a different, one is for VR and the other one for non-VR, the non-VR controller was written by me so is checking the field to do some action, but the VR (The one from the image) uses a few components that were not written by me, those components are checking their own variables so I need to modify their own variables using my own variable , in this way I can make my field affect those other scripts, What I try to do is not to have to modify variables from those other scripts in a different way; this way, by simply modifying a field in my code, I can change what is needed in those third-party components.I hope this is clear.
foudn the issue, the other object is not part of mesh. so I had to disable agent and then use transform.position, and now it works
It took you a paragraph to explain a half-dozen lines of code, so no I wouldn't say it's clear. You cannot edit this common class at all? I don't see any reason you can't refactor this to be nicer. But you don't need to change anything if you don't want to
Might be better as abstract instead of virtual. Then every child class would be forced to make its own backing field, so you still keep the polymorphism but don't have a chance at a stack overflow
If I find myself in need of an abstract static field, which C# does not support, am I better off manually adding a static field to each child class or using a "template instance" to replicate that kind of behavior
what are you even trying to do with an "abstract static field" in the first place?
something like string StateName = "dash"; would be nice to be static because it represents the name of the state associated with this class and it doesnt chane per instance
and itd be abstract because the parent class would force each child to implement it
this whole setup seems pretty bad. How do you plan to reference a derived class by Type in the first place to access a static value when your setup is using an abstract class. You should likely be using that abstract class in every case possible.
Just make a regular abstract method that returns a string if you really want
im not sure i understand your question. I have an abstract MovementCommand parent class and then for example a derived SlideCommand class. If I wanted to access some static field from the dervied class, why couldn't I?
Its less of a question and more of a point. you'd have to actually reference the SlideCommand.Something field. There's no point of using inheritance if you're going to be manually handling logic for each derived class
Anything that handles commands should do it purely through MovementCommand
yeah your right in general, but sometimes there are things you specifically would have to do manually. For example, state trees
which are internal to the system itself
I dont know what youre specifically referring to as a state tree, but no you dont have to do it manually. That's literally the point of inheritance.
I'm with bawsi, your architecture makes no sense
Either way just an abstract method returning a string already solves your issue
You cant have an abstract static thing
got it; trying to learn tho; when you say manually do you mean like manually writing code for each derrived class instead of using the parent class
this is what i mean https://dotnetfiddle.net/OLBxxR
plus also you'd be hiding objects if using static which just isnt a good idea
Thank you for taking time to write that for me. I def understand your point now, although weren't you assuming that i was going to need the static field for some kind of polymorphic thing?
Perhaps this is just bad design, but in this class I have, in the BuildStateTree() method, it would be useful to have a static reference to the state name of other movement commands instead of having to manually inject the correct string name: https://hastebin.com/share/jidexezoqu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you cant use abstract on it so there is no polymorphism on it. static fields belong to the type
I get why you cant technically have them but I don't neccessarily get why they imply bad design
Something is creating these commands based on the constructor, and that thing knows what all the commands are. Why isn't that thing building the state tree? It has the knowledge of what they are and that's probably a better place to describe how the states are supposed to interact with each other
im not entirely sure what im looking at with this state tree tbh so im not sure what these values are even being used for.
good point. I was thinking it might be good to just have each movement command describes its own "state capabilites" for encapsulation sake though?
You mean convenience? You have tightly (and in a brittle way by using magic strings) coupled states together this way
why use a magic string at all? You could be referencing the types directly
yeah i def could i dont know what i was thinkin
However, I don't see the issue with tightly coupling states with their command. To elaborate a little, the BuildStateTree() method is creating a DAG that evaluates whether or not the movementCommand can be executed based on current state. Anyways I think I get your points so don't feel like you need to continue this convo unless you want to (if u have more to say and want to I'd love to hear it)
There isn't anything necessarily wrong with doing things that way (personal style), but since the states are already tightly coupled, you don't really need magic strings here.You're doing something similar for the transition key. Why isn't that an enum, for example? You actually have a comment to explain what the values mean instead of just making the values tell you what they are
Your right, I've actually been meaning to do that I just haven't gotten around to it: a bit of cleanup is due. My novice logic for tightly coupling the state logic to the command itself is just that I'm pretty sure the state logic wont have to change at all at runtime so why not "build it in". I think that makes sense, anyways.
Thanks for the help guys
quick question anyone knows web tools or extensions for creating UML diagrams from my code?
Rider has a built in feature for that. Generally those end up so complex that they are effectively useless.
This also can convert/generate from c# and is an allround great tool for UML et al https://staruml.io/
Astro description
Thanks so much, I'll check it out
bool HasLineOfSight()
{
Vector3 origin = transform.position + Vector3.up * 1.5f;
Vector3 direction = transform.forward;
if (Physics.Raycast(origin, direction, out RaycastHit hit, 100f, wallMask))
{
return false;
}
return true;
}
hey guys how would i go about checking if there's a wall between the enemy and the player then go around that wall?
you probably need to have the walls in a layerMask, and check if the raycast hits that laymusk then return nothing, else return true
exactly what i did
fixed it already
added 4 emptyGameobjects around my player
enemy chooses one, goes there tries to shoot, if cant hit then choose another random one, repeat
Instead of that, You can get a direction by subtracting two positions.
var direction = (Enemy.position - Player.position)
This would be the of the Raycast, which allows you to check for walls more efficiently.
Unless I am misinterpreting your questions/statements
i want the enemy to feel a bit smarter than just "walk straight towards player"
since the enemy can shoot with a pistol, dodge and run away
Well that's for the eyesight of the enemy.
And for walking behaviors, you can use NavMesh for the pathfinding, which means finding the shortest path to the destination without running into obstacles. (Unity handles that for you if you use their built-in NavMesh)
And to actually figure out the destinations your enemy should choose, there's no single way, it depends on what you want
A good starting point for some simple logic is by setting the destination to the player, and then offsetting it with a large Random.insideUnitSphere , this would make the enemy approach the player seemingly indirectly.
i already got some logic going so its harder to make this raycast work
i'll probably add a coroutine to my HasLineOfSight()
I might be able to help you improve it if you send the script
its quite big
You can use a website
which one was it again?
I use https://paste.myst.rs
Yeah something like that, theres a lot of them
a powerful website for storing and sharing text and code snippets. completely free and open source.
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 you see it?
a powerful website for storing and sharing text and code snippets. completely free and open source.
those are the two scripts
dont mind the shit fest xD
Goddamn, I recommend splitting it into multiple scripts because there's too much unrelated logic in there.
I don't completely know where to start to be honest with you
yeaaaa
my workflow is to vomit code first
then separate it when the enemy is behaving well
Its gonna be faster to seperate it from the beginning
also its easier if you actually see it in game
Hello everyone, im currently facing an issue for my Fade in Fade out script I made, each time the player presses E a fade in fade out anim plays out and switches the player from normal to his combat varient
everytime I click E the player just stands still and my movement doesn't work and he doesn't switch to his combat variant
The error im getting:
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory+<PlaySwordCutscene>d__5.MoveNext () (at Assets/Scripts/PlayerInventory.cs:28)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <bc88c87c01184d1499d92d3b79a10ce6>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
PlayerInventory:PickupSword() (at Assets/Scripts/PlayerInventory.cs:15)
SwordPickup:Update() (at Assets/Scripts/SwordPickup.cs:13)
And here are the 3 scripts I used(The Sword Pickup, Player Inventory and CutsceneFade): https://paste.mod.gg/hudraoorcybu/0, https://paste.mod.gg/kramgwerzivm/0, https://paste.mod.gg/gagdusapzhou/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
playerWithoutSword doesn't have a PlayerCombat component.
line 28 is playerWithoutSword.GetComponent<PlayerCombat>().inputEnabled = false;
there's 2 things that could be null there, playerWithoutSword and playerWithoutSword.GetComponent<PlayerCombat>().
if playerWithoutSword were null, it'd error on line 27, so it's the latter
I fixed it, thanks for the help
turns out I didn't realise that I gave playerWithoutSword both the combat and movement scripts when it was only supposed to get the movement part only
do they need to be separated though?
could just have them be the same object that switches modes and sprites and such
eh I wrote all that code, i won't put it to waste for now
I may update it later on
Hey,
For my Minesweeper game, I need to figure out all the adjacent "0" tiles and the adjacent "0" to those tiles, etc...
How can I do it ? I'm thinking about the floodfill algorithm, but is it the right approach or is there a better way please ? 🙂
sure, that one works
but is it the best way ?
thats usually what is used no?
i think the original used floodfill
I have no clue, that's why I'm asking 🙂
I'm thinking about the floodfill algorithm, but is it the right approach or is there a better way please ?
Is there a problem with flood fill?
nope, just asking if there's a better way 😄
/ is that the conventional way
What problem with flood fill are you looking to improve upon
what could be made better
🤷♂️
so then just use it
you have a problem, you have an algorithm that solves that problem. End of consideration.
I have this tendency of overcomplexificating things, that's why I always ask 😄
this question is part of that tendency
yes
floodfill is pretty basic, it's just depth-first search except you aren't searching for anything
Okay, so, here's the situation: I have a whole bunch of royalty free vehicle meshes from a bunch of different sources, so there's a whole bunch of different ways they're constructed. Some of them have every individual submesh as a separate GameObject, some of them are a single GameObject with a dozen materials.
What I need to do is to recolor certain materials with a "Team" color. Currently, I have a script on the parent of the meshes that has a list of Renderers to recolor to the team colors, and it goes to each renderer and loops through its materials, changing the _BaseColor of the material to tint it to the team.
The problem with that is the ones where it's a single renderer with multiple materials. Some of these materials need to be tinted, but some don't. Imagine a vehicle where the chassis, hood, and windows are all sub-meshes on the same renderer with their own materials. I want to tint the chassis and hood, but not the windows.
I'm expecting to put a script on all of these renderer objects to determine which materials to tint, but what would be the best way to do that? If I have another component and drag in materials, they're going to be different instances than the ones the mesh uses when it's spawned in, so I can't just loop through those and change the color. Should I just make a list of "Excluded materials" and loop through the renderers materials, and skip the ones that share a name? That feels kinda... code-smelly. I hate using the name of something for a functional purpose.
I've gone through the exact same bullshit before and it def is code smelly. I ended up having a water tower turn blue cuz of it's name 😛
Depending on what you need and dont need to mess with, any chance you could identify the type of material and/or shader properties?
eg. you could figure out what "glass" is
For the most part, I'm just letting every mesh keep its materials however they are and just kinda eyeballing which ones need to change. I suppose I could try to make a sort of unifying shader they all share and having a property on that one for "Team-Tintable"
I can think of two options:
- Make it index based. Each material corresponds to a specific submesh, which has a specific index.
- Store a property on the materials you want to change. Such as a
_UsesTeamColorinteger property which is set to 1. It will be ignored by the shader since it has no corresponding property, but it will still be saved on the material and can be fetched withMaterial.HasIntegerorMaterial.GetInteger.
As long as the original material has it, it will get duplicated to instantiated copies. To add the property to the material, you either have to do it from editor script, Material.SetInteger, or use the Debug inspector mode to edit the property list directly.
Can I just... add a property to an arbitrary material?
I... never even considered that as an option...
Yes, it's just a serialized key-value pair list.
There's also Material.SetOverrideTag and Material.GetTag, but I haven't used it for custom tags and that's not really its purpose, but it might work.
unity doesnt consider parent class of a script class as the component of an object?
i have a parent class that implements common stuff and then 2 child classes that are used by different objects. but if i try to get the parent class using getcomponent it doesnt return it
classes don't have parents or children, that's something the Transform class specifically deals with. do you mean inheritance?
nvm the issue was something else. i was talking about inheritance
You'd probably need to show some code. How you're defining the inheritance and how your attempting to get the component
i figured out the issue, i was accidently using a child class in the GetComponent instead of the parent, hence it was returning null
Hey
inheritance commonly does use parent/child terminology though?
https://nohello.net please don't spam across multiple channels
Where is the Unity 6 app binary exe?
- downloads are available on the website
- you should use the hub to install stuff instead though, rather than downloading the editor directly
- not a code question, this would be more appropriate in #💻┃unity-talk
I see it generated the exe after putting a new folder, however it didnt generate it in the existing folder where Unity generated files lay
are you referring to your build exe? because that goes into the folder you tell it to
Yes, however it did not generate it. It only worked with a clean build folder
well this is still not a code issue so if you need further help then take it to #💻┃unity-talk and actually provide details instead of expecting people to immediately know wtf you are talking about
Hi, we're getting this error when starting Unity suddenly. We can't isolate it to a specific change, and it's not saying what file it is... it's just this message. Any ideas how to get more information? Has any got this recently?
Parser Failure at line 2: Expected closing '}'
yeah same here, it's not your fault no wrry bro
Yeah, just found the messages from others getting it
same lol, 1 hour fighting against nothing
same same... what a waste of time that was 😄
I think it's probably related to the cloud outage
yeah, cause can't create more project related to cloud
Honestly that is new to me, apologies.
I've just started using the Newtonsoft.Json package and parsing a json file via TextAsset and also having this issue. I was pretty sure I somehow parse the json in a wrong way, but maybe that's not the case.
Glad I checked the discord!
I'm seeing HitObj receiving the result from GetRaycastObject(). How exactly do I get that object from the Raycast and pass it to HitObj?
How exactly do I get that object from the Raycast and pass it to HitObj
what do you mean by that? HitObj is the object hit by the raycast because that is what you return in the GetRaycastObject method
You're already doing so. If you're getting null instead, it's because your raycast in the method that you made did not hit anything and returned null as you've told it to do so.
hey this is more so a general question rather than a coding specific one
but is there any way for me to change the colour theme for visual studio to github dark default?
I have this theme installed for visual studio code (blue one) but not visual studio, and when I search up downloads for visual studio, it only comes up with results for visual studio code
its not one of the default themes I looked through them all
this is not unity related. nor is it code related.
but you can search the available extensions inside of visual studio
oh sorry
if the theme exists it can be found there
so since the method returns hitbj gets what is returned?
So, the concept for my 2D building system uses a grid-based system to place start and end points for walls, but then uses a spline to create a curve if the start and end point aren't in line with each other. What concept best fits this / what unity methods should I learn about in order to be able to accomplish this?
Here is a diagram of how it would work, green being start and end points and yellow being the center of the curve
Bezier curves
It looks like no one is using 'partial' in unity, Do u guys use it ?
i use source generators, so yes i do create partial types.
whether people use them for defining types across multiple files is an entirely different story. it's really just a personal preference if you want to do that or not
How should i name script files of a partial class ? I have InputManager that includes singleton logic and core logic
use a convention that makes sense to you
It sounds to me like these should be separate classes then. Or use the unity singleton implementation.
Not partial classes.
I don't get it, Managers should be applied singleton
public partial class InputManager
{
private static InputManager instance;
public static InputManager Instance
{
get {
if (instance == null)
{
}
return instance;
}
}
private void Awake()
{
}
private void OnDestroy()
{
}
}
Inherit from a generic singleton class. Unity already implements one.
wait does it really?
I can't make it work, can u provide an example ?
Hmm... Must be a fake memory. There's an editor ScriptableSingleton, but you can't use it at runtime indeed.
You'll need a base generic class with generic static instance field. then inherit it with your manager and use it's type as a generic parameter.
Then put all the singleton related logic in that base class.
I already have 1 and tested it a lots, it created many bugs so from now on i will only put static variables inside its class, AI also recommends to not using singleton inheritance
Typically when handling thousands (or at least a thousand) AIs in 3d space that, while don't need complex decision making, do need to be checking for hundreds of potential targets
Is something like DOTS practically required? Or are there solutions efficient enough to stick with the OG format
I understand using nav mesh agents is beyond impractical but even when you have to have non agent AI determine distance and targets when they're tightly bunched up
You lose grids/partitioning and it becomes a mess where 20,000 checks are ran on a single frame
mono + job + burst+3d grid is quite enough in most cases
Considerations on if theres any potential checks you can re-use or avoid in certain contexts would assist heavily in bringing down whats necessary there too i'd imagine
If I have two tri’s (two sets of 3 world space positions) is there any suggested way on checking if they intersect?
The best AI optimisation is understanding that your AI logic and decision making do not need to run every frame. For example in our fast paced fps game we run the complex utility functions once every 0.5 to a 1s depending on the type of brain. Data collection for potential targets and world state can be the same.
I would be running it every 3 seconds
Alright thanks, that gives me a bit more confidence
Because dots is well above my knowledge lol
Every 3 frames for thousands of agents just means that every 3rd frame of your game would be heavy. What I’m suggesting is each agent having it’s own timer and update frequency based on realtime rather than frame count. That way each frame you are running ai logic for less agents
I can't use agents regardless as that's far too much performance hit
They're mostly just simple home made state machines that use local movement
For example we also put our ai in a priority queue based on their engagement and proximity to the player
This would be top down
Thats an agent in my terminology
I did not mean nav mesh agents
Ahh ok
Any piece of software capable of “making a decision and acting on it” is an agent
Technically
This for example means we prioritise updating the context and utility weights of enemies currently engaged in a firefight with the player rather than some dude 500 meters back behind 3 walls trying to path find.
That dude can wait
Do you have any suggestions on how to handle this when a large amount of agents are in big clumps?
I would need more context for your game. What I shared as an example works for us because we are making an fps
You seem to be making an rts
What about the clumps is concerning you ?
Mount and blade would probably be the ideal example,
I handle it very messy at the moment but having the two "squads" that become interlocked (upwards of 40 agents each) run through each other's list of agents within the opposing squad to determine the closest unit
But that causes issues where if there are say a thousand agents, then we can have scenarios where 50,000 magnitude checks happen within seconds (obviously not ideal)
Because there's no restriction on a squad being say, in a single straight line and able to access every target in the scene
Or in tiny groups that don't typically need to run that many checks
At best I've split ranged up from melee so melee units only check the squad they're engaged with
Well this sounds like some form of spatial partioning is needed
Do I just need to work on a much smaller partition?
I did try the partitioning originally but even with 2x2 unit grids (which created a lot of partitions) there can be a lot of units/agents on a single grid
I'm sure the system works but I've made a mistake with how I'm thinking it through somewhere
I did originally try to limit it to squads on squads but a player could just run a squad down the side of the line and the enemy naturally would just accept death lol
Well at that point you can write a parallel job to do distance checks
Yea it's looking like Ill have to implement a proper job/burst system
Or you could try sticking your units inside a kd tree. Thats very fast for finding X amount of closeset things to a point
But you will need to be smart about how and when you rebuild the tree
That would work even worse than spacial/grid partitioning if they all clumped into one big horde right?
But better for long range battles over larger maps?
Mmno because you would use to find the closets units within a range
The range could be a meter
There is a jobified implementation inside the mega city repo somewhere in the audio or util section
But the range might need to be 1 meter or 100 meters so there would be a lot of worst-case checks I think
Oh ok cheers I'll have a look
instead of running all each 3 seconds u can split it into many groups, and running groups on a queue in many updates, and just apply the result when u want
Oh yea I'm doing this already it's qued
Just that each check itself has a 3 second gap before it's requed
don't advertise your question. be patient
if you're not getting any answers, maybe you didn't provide enough info
They did not provide any information
patient for what bro
how tf do u expect me to provide information if i LITTERAlY dont know whats going on myself??????????? ive never animated in my life and i swear all u mfs just love to ragebait for no reason
how do you expect us to help if you don't give us any info to work with
did u not
just
read
what
saiud
!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
and there's so much that doesn't require animation knowledge that you left out
i dont know how to animate thats why im asking
anyway.. stop spamming this channel with unrelated chat (☞゚ヮ゚)☞
- what are you trying to do?
- what assets are involved?
- where did it disappear from?
etc
none of this is related to animation specifically. it's just info about what situation you're in
go provide more detail
not my fault if noone is helping
"provide more detail"
it kinda is
your loss if you don't want help 
are u stupid or smth
i just said i dont know whats going on myself
so how do u want me to provide more detail
<@&502884371011731486>
its not my fault
hes lit
stupid
and cant read the words
displayed on his monitor
jeez calm down
you say you don't know how to animate, but the info i told you to provide doesn't have anything to do with animation
it's just what you see in the editor
but you can.. at the bare minimum you could show a video of the issue
show the setup, show what you have done.
we weren't stopping you 😄
great, let's stop polluting this channel and go to #🏃┃animation
@mint zenith Enough with the spam, or you will be muted.
In the future, ask your questions with details, and dont' cross post.
This is a code channel, for code related questions. #📲┃ui-ux is where you would need to move your question (delete from here so no one tells you off for crossposting)
oh, you've already posted there..
yeah probably not code related
Hi, we're replacing the standard Windows cursor, with a sprite on a canvas (so we can do animated weapon aiming ones etc.). We hide the windows one with Cursor.visible = false;, but that also keeps it hidden if you move the cursor outside of the window etc. Is there a good way to detect that? Like the window losing focus etc.?
It's only hidden while Unity still has focus, make it lose focus and it will come back already
uh why could there be a huge ass triangle in my mesh ;-;
it only apears when the size of the mesh reaches about 300x300
it likely has a 16 bit index buffer and exceeded 2^16-1 verts
how would one go about avoid that but still having more vertices
set its index buffer format to 32 bits
thanks
Hi
How can resolve this error
"Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater."
delete the global using directive from your code on the line the error indicates
How?
looks like you're using some kind of code generating plugin'
and that plugin is generating those
Or you have some kind of setting in your VSCode that is automatically compiling the code
and making these Debug/net10 folders etc
basically this is probably a VSCode issue
you have it misconfigured somehow
How u can see misconfigured?
I can tell it's misconfigured because it's creating that obj/Debug/net10 folder and contents
because those obj files shouldn't exist
just kind of a sanity check, is there any real downside to waiting on a callback in a coroutine for a process i want to be functionally infinite? this is for a turn based prototype
One note - you almost definitely just want yield return null; not yield return new WaitForEndOfFrame()
any reason why?
(that line is actually only there since i was calling EndTurn in StartTurn to test this lol)
waiting one frame is yield return null
WaitForEndOfFrame is a special thing for waiting until a specific part of the frame used for some very niche post rendering things
check the docs
also creating those objects is unecessary GC allocation
that a good image, thank you!
Alright I'm pretty confused here. I found this script online because I want to find a nice way to serialize dictionaries.
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SerializableDictionary<K, V> : Dictionary<K, V>, ISerializationCallbackReceiver
{
[SerializeField]
private List<K> m_Keys = new List<K>();
[SerializeField]
private List<V> m_Values = new List<V>();
public void OnBeforeSerialize()
{
m_Keys.Clear();
m_Values.Clear();
using Enumerator enumerator = GetEnumerator();
while (enumerator.MoveNext())
{
KeyValuePair<K, V> current = enumerator.Current;
m_Keys.Add(current.Key);
m_Values.Add(current.Value);
}
}
public void OnAfterDeserialize()
{
Clear();
for (int i = 0; i < m_Keys.Count; i++)
{
Add(m_Keys[i], m_Values[i]);
}
m_Keys.Clear();
m_Values.Clear();
}
}
I expected 2 Lists to show up in the inspector.
but instead I got this
How... is that happening?
