#archived-code-general
1 messages ยท Page 153 of 1
does it reffer to me?
Yes
The file format is the hard part can't help you with that, you can always make like your own parser but there is probably a better way
maybe you can detail it a bit?
should files be saved in json?
That's your decision to take
Can do json can do some binary fkrmat
XML if Ur a fan of that
But you probably need a way for your systems to translate the level to some sort of simple representation
And then another way to translate it back from the file
yeah, I probably know how to do it.
For the scene, you'd create a shell of a scrne
So a scene which expects a level to be passed with it
From a persistent object for example
That loads the file and bootstraps the level
And you are done :)
how do you know that you are running the build on the steam deck?
maybe there is any documentation or even a video how to do that?

nah I've no performance issues. I display the variations on a UI list and when I scroll down I display 10 more etc. I got 116 variations when I searched for e6 d6
Aha then in order to avoid loops like this, you could change this data into long format data
I see, I will try to find it
thanks for your help
wdym long format data?
You'd have your variation as an observation and then have your chapterid and stuff as columns
Makes it easy to grab a list like you do in your ui without combining one from 4 nested ones
so instead of having multiple lists of moves, I have another list of moves that contains all the moves in a chapter?
Yes
aha
If you want to avoid those foreach statements
But honestly if it works it works :)
yeah that makes sense
No point in fixing something that ain't broke
it does work but I watched a youtube video that explains why it's good to limit nested brackets to 3 and I liked that so I wanted to try and see if I could achieve that philosophy on this piece of code too lul
the point is to make it more flexible tho
but that's not fixing, that's improving ๐
you could say readability is broken ๐
2s I'll get to my pc and do some Linq
It's just a thing with your data layout honestly
And also you could move your sequence checker to another function
public List<Variation> GetVariationsFromMove(string moveNotation)
{
var moveNotations = moveNotation.Split(' ');
return GetChapters()
.SelectMany(c => c.GetVariations())
.Where(x => ContainsSubsequence(x.moves.Select(m => m.MoveNotation), moveNotations))
.DistinctBy(x => x.moves.Last().Fen)
.ToList();
}
public bool ContainsSubsequence<T>(IEnumerable<T> sequence, IEnumerable<T> subsequence)
{
// See https://stackoverflow.com/questions/34575317/how-to-check-if-list-contains-another-list-in-same-order
// There's better solutions for this.
if (subsequence.Count() > sequence.Count())
{
return false;
}
return Enumerable
.Range(0, sequence.Count() - subsequence.Count() + 1)
.Any(n => sequence.Skip(n).Take(subsequence.Count()).SequenceEqual(subsequence));
}
@abstract nimbus
Since you are a linq fanatic
I dont understand why you'd need the filter by the move.fen
but I dont fully understand your domain, I'd understand if you were to filter out duplicate movesets, so I included it in the final code anyway
it's because multiple variations can have the same move.fen and I want to return variations with a unique move.fen so I can display it on a board
Again I dont know what move.fen is
do you know what fen is in chess?
fen is a line of string that explains where all the chess pieces are on a chess board
so move.fen is the fen that you would get from that move
Boardstate then?
yeah
But then the variation would be different
You can get to the same board state by doing a different set of moves
yeah the variation would be different but since I have a UI with a list of chessboards I don't wanna show duplicates
Gotcha :)
Anyhow, try to understand why the linq I wrote is different from the one you made
Hi I'm a gumby coder and I'm having trouble generating a random number on a worker thread - it says Random.Range can only be accessed on the main thread, but the thread wrapper thingy I'm using doesn't allow return values and now I'm completely lost as to how to pass a random value to a function on a worker thread. Not even sure what code to post to demonstrate my problem.
yeah you wrote some new stuff for me so I'm trying to understand it hehe
I am not sure if DistinctBy exists in unity by the way, but you can look up an implementation for that online
ah this is not Unity but this was the only channel I had to discuss with ๐
it's Maui
btw this is how it would look like
We've been scammed
Theres the !csdiscord
it says code-general so I assumed it's not unity relevant ๐
!cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
aha ty
but usually its like, my monobehaviours dont get activated using this piece of code please help
I've always wondered this- is there a "best way" (relatively speaking) to structure multiple checks based on combinations of bools?
E.g. I have 4 bools for the sides of a square: top, bottom, left, and right. I want to determine what corners are active based on them, with the option of opposite-corners or L shapes impossible. Is it really just two forked if-statements (top -> left/right, bottom -> left/right)?
Further, what if I want an extra replacement condition if all are active?
I was thinking the all-condition could be slotted into the if for top -> left -> (right && bottom) then just break/return since it would be the end of the function in that case
this code should be slower than my foreach version right? Cuz mine is using a Dictionary to distinguish by move.fen but here you have to go through the list again when you do DistinctBy right?
Maybe with 1, 0, -1
I'm still trying to understand the other function you wrote tho
Where the 1 and -1 would refer to the opposite sides and 0 refer to both
you could do what layermasks do and use bits, then check if the combination you want matches with the bits active. That way at least you can have it work for any combination. But at the same time if this can be written with 2 if statements and the code will never need to be adjusted then ๐คทโโ๏ธ just write it and move on
although you will need a system for what corner matches to what bit with what i suggested
Ah I gotchya
I think with the way it is currently set up it only iterates the entire list once
only once? I thought .where loops through the list one time and DistinctBy loops through the list another time
and a third time with selectmany
Using linq you create an expression tree that isnt executed untill you call to list
A bit stuck in a rut. I'm making a prototype for a platformer. I have a MoveComponent which allows any game object to move via an input provider (player gets input from unity Input class and enemies gets input from a steering class).
Now I introduced a state machine to my player but am confused now on what the "moving" state will contain since all the moving logic is handled in the move component.
idk if I should continue combining the two or just stick with one of them
What's the state machine for? You might not even need one
That's what I'm thinking right now. My character is supposed to switch from flying to walking and vice versa and the movement is supposed to differ between those modes. Think of a superman type character.
Youd swap the bindings that you have between movecomponent and the input provider
such that the input provider now manipulates the flycomponent
That would be the only reason for the statemachine to exist
Yeah that sounds about right
Structure is nicely done by the way! :)
So there's a grounded movement component and a flying movement controller and basically the state machine just toggles which one is active
Well you mentioned that you already decoupled movement from input
So you could also redirect the input to another component
Right
The way you do it doesn't really matter all that much
Enabling / disabling of component could work
Assigning references could work
Really depends on the exact set up of your code
I feel like a state machine is the right solution for this but at the same time feels like it's completely unnecessary.
Well a state machine is just a concept right, it could be a simple one where you just have an enum and a switch case in the update loop of your statemachine
It could be that you add more states later
e.g. if you stop flying in mid air you character goes into a falling state where you cant move at all
It's definitely solvable by just putting both types of movements in 1 script, but if you have extra modes then it gets a little awkward
You could just implement it quickly to get a working version, and swap it to a proper structure when you want. Because this would really just be a matter of moving a function out to a new file, maybe declaring an interface or just having something toggle which components are active
Probably one of the quicker things to refactor
Keep it simple, but not too simple :P
I personally would just make a super simple statemachine
So just enum -> update loop with switch case -> function to change states
I'll probably continue without a state machine for now and stash the state machine in a separate branch.
I'd advise against stashing it in a different branch, just don't do it all together if it's not main worthy
youll just have tghis branch laying there and after 3 months too much has changed in the class for you to be bothered to solve merge conflicts
so you end up tossing it away
I mean, at least I have the code on the repo.
I can foresee at least two more states (on top of the usual ones) I want to add.
public PlayerStateEnum {
Grounded,
Flying
}
// Some monobehaviour
private PlayerStateEnum _currentState = Grounded;
public void ChangeState(PlayerStateEnum newState)
{
if(_currentState == newState)
{
return;
}
switch(newState)
{
case PlayerStateEnum.Grounded:
GetComponent<GroundedMovement>().enabled = true;
GetComponent<FlyingMovement>().enabled = false;
break;
case PlayerStateEnum.Flying:
GetComponent<GroundedMovement>().enabled = false;
GetComponent<FlyingMovement>().enabled = true;
break;
}
}
Really worth keeping?
Well, the one I wrote was a lot more involved with each State having their own classes so at least I can save that
ohh yeah for sure
but it doesnt have to be that complicated
you already did the work
so why not use it then xD
You should be caching those GetComponents so you only do them once
Definitely.
Hi. First time after I clone my project it fails to start with an error "unity Assembly will not be loaded due to errors: Reference has errors". After unity restart the issue is solved. I think the problem is dll-s, and it wouldn't be a big deal, but I can't build project on the cloud because of that. Anyone encountered something similar?
Have you tried doing a clean build in the cloud?
Does anyone know how to create gameObjects in the scene in the script?
When we use Instantiate method, it just creates gameObject in game mode, not editor. When we exit game mode, it destroys itself. How do I make it not destroy even in editor?
or does it require reading json?
yes, didn't work
So you want to create an object in the game mode which is then saved to the scene when you exit? You'll have to serialize it for the most part. You can also prefab stuff during a editor build, but any instantiated data during the play must be serialized if you want to keep it
yes, that's exactly what I want to achieve
I want to make my own mini game engine
to create levels in my game
maybe you know e.g. geometry dash
there you can create levels and then play them without writing any code
If you create it during the game, you can simply drag it to the asset folder and it'll prefab it, but it'll most likely just keep the component data and the structure, so you'll have to serialize anything else
first of all I need to know how to create it
I don't get it, how am I supposed to drag it?
go into scene mode as the game is ran
and yes, not all GameObjects in the scene are prefabs
I have to do that via script
let's say I need to instantiate gameObject from prefab and then when I exit game mode, this gameObject need to be in my scene
in editor mode
Dont you want others to also be able to creat elvels for your game?
I think I want, but I cannot to that instantly even without knowing how to create GameObject like that
I need to do it step by first
Whatever you are going to do in the eidtor right now
and my first step is to create GameObject in editor
why.?
Because it's editor specific code
it should be saved in the scene
really?
the scene (as a loadable asset) is immutable in a build
and prefabs are not a runtime concept either
If you want other users to able to create levels for your game
you need to store it some other way
Yeah, you can still prefab stuff though, but it'll not have any references you saved to it. It should save positional data if you do save it during the scene though
- I create gameObject in the Start method
- I exit game mode and I see this gameObject in my scene
- I run the game one more time and another gameObject is created, there're too gameObjects already
that's what I need to achieve first
@gray mural
We had a conversation about this this morning
yeah, I am just starting this topic one more time
you had said it, yeah, but I still have no clue how to do it
In this video we set up a quick and easy way to edit levels.
โ Download the Scripts: http://forum.brackeys.com/thread/level-editor-using-image-data/
โ Download the Sprites: http://devassets.com/assets/2d-mega-pack/
โ Quill 18's Livestream: https://youtu.be/5RzziXSwSsg
โฅ Support my videos on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยท...
I told you to google
level editor unity
gave me this video
This is one way to do it
Watch it
nah, that's not what I need
I have watched it already
it gets infomation about drawing
Then you should probably specify what you want
it converts drawing into prefabs
@winged mortar
Then find a different tutorial that does what you want
Yes and for an ingame editor you'd need a script that converts prefabs into drawings
I have tried, I haven't succeded to find it
Its cool that you want this now, but if you want to have other people be able to create their own levels when your game is build
This sounds like editor scripting, but seeing as you apparently want this to occur in a build too, this description is incomplete
I don't wanna draw.
it wont work the way you want it right now
You can create images from code
Image is just a medium to translate it
you can do json xml binary doesnt matter
how am I able to achieve this if I cannot even create single GameObject in this way?
image is just interpretable for humans
I see, I want to create scenes in game mode
I see, I want to do whatever is done to create e.g. geometry dash levels or clash of clans bases
You can spawn whatever you want, however you want, then you need to serialize what you've done in some form or another, whether that's JSON, XML, a custom format, whatever.
Then on startup you read the file you wrote and deserialize the info to create the scene
There are plenty of assets that exist to do that sort of thing, but there is nothing built-in
Yeah, serialize what you do in the game, then you want a editor script to deserialize it onto your scene is the idea of it all
and there are no standards
read this again
They want this to work in a build, so it's not editor scripting
you have entered a closed circle now
Oh, in build? Ok well that's complete custom code then
โช
You have said I have to deserialize the info to create the scene. I have to do this with a script, right? So how do I create smth with the script - that's the question.
You find a tutorial to do with saving and loading, and you follow it
Perhaps this one?
I cannot find it
In this video we set up a quick and easy way to edit levels.
โ Download the Scripts: http://forum.brackeys.com/thread/level-editor-using-image-data/
โ Download the Sprites: http://devassets.com/assets/2d-mega-pack/
โ Quill 18's Livestream: https://youtu.be/5RzziXSwSsg
โฅ Support my videos on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยท...
but actually if I think about this, he should create them actually
and I just need to see what he is doing to create a single gameObject
that makes sense
Yes, that's how following tutorials works
editor script?
you take what you need from it
There will rarely ever be a tutorial that does exactly what you want
In this beginner easy tutorial I will show you how to make a level editor for your game. this tutorial will try to create a similar idea to Super Mario Maker, but allows you to edit your levels while playing. I will go over how to create customisable items that can be placed anywhere with cool visual effects and more!
At the end you will have a...
this shows you how to add stuff to your scene, it just dissappears
so what you need to do is when you add stuff to your scene from game view
to save that to a file
and then when you launc the game you read from that file
this is just drag & drop tutorial
In this tutorial I'm gonna show you how to create a level editor in Unity using it's built-in tilemap system. This part will showcase how you can place and remove tiles with your mouse, and how you can save those tilemaps at runtime to a json file.
Create rule tiles in seconds: https://youtu.be/yI8fMXbtjew
You can download the project in this v...
that I know how to implement
I think you should have all of the resources, you are now in the hands of god to implement it
does anyone know why my hex are see through?
I have verified that they are drawn clockwise
If i look at the mesh from the underside, it looks fine
I dont know which direction you are supposed to draw them in
But you could try flipping it, I know you said clockwise but maybe try counter clockwise?
Hey everyone. Can UI Toolkit Support Worldspace Canvas and also work with VR? I read that it does Not do so by default, but maybe someone still got it to work
This is a coding channel #๐โfind-a-channel
I would presume since the meshes are coded, this channel is fitting
.
Then you should share your code
Under normal circumstances I would, but I dont know which part to share, I am unable to pin point the problem
Are you using tilemap ?
So, you render all the white, then all the red ?
then the red height is drawn to denote height
Could you use the frame debbuger ?
the red is connected to the white hex, they are thesame mesh
the problem is, the white mesh is not see through but the red is
From what I see, the white is all renderer then you render all the red.
Use the frame debugger
To analyze the frame.
ok will use frame debugger(first time, might be a while)
@rancid frost Do you have z writing enabled? If not, the order of the triangles in the mesh will determine which triangles appear on top of which.
Whatever is the issue, you gonna find it with this tool.
It is fake 3d
User said the mesh is generate on the x-z plane.
At least, that is what they said.
...
Why are you not doing a full 3D then.
And for sure your red will be on top of your white.
It is literally on top of it.
It is on top of it
Anyway, you can use the Frame Debugger to understand what I mean.
ok
not particular sure what to make of this
It drew the 25 hex cells are required, but the clones have no additional info on them
does @everyone know about the shop system
damn, you really just pinged everyone?
saw, here is the game view
it looks fine here, but the axis are flipped
You gotta look trough the call.
Please do not ping usergroups or anyone not in conversation with you, it's obnoxious.
One by one.
yes arrays are not the same as a single object
i believe there should be some overloaded versions which take the array (or list) as out argument and return the length
there is
not as out argument
just a regular argument
arrays and lists are reference types so they don't really need out
u are right, array is already reference type, i forgot it
How come I am able to see the red even tho the preview says it wont be rendered
Not exactly sure what you mean by won't be rendered. Seem to be me that the mesh you are looking could be the mesh being there.
Anyway, you should definitly try to use an alternative instead of what you are doing.
The easiest would be to use real 3D mesh.
You could also try to use isometric view.
dont u see how it says the back end wont be rendered,
No idea what you are talking about. Backfacing face not being rendered is pretty standard.
as you can see from the video it is rendered
Maybe because you are previewing the mesh in the wrong side.
No Im not
but whatever this is clearly not working as you said
It does look like it could potentially be upside down.
what exactly are 3d meshes?
I mean, doing the full mesh.
Like a single pillar that is scaled.
@winged mortar not sure why your method didn't work but I made my own version like this
public bool ContainsSubsequence<T>(IEnumerable<T> sequence, IEnumerable<T> subsequence)
{
var subsequenceEnumerator = subsequence.GetEnumerator();
subsequenceEnumerator.MoveNext();
var sequenceEnumerator = sequence.GetEnumerator();
while (sequenceEnumerator.MoveNext())
{
if (sequenceEnumerator.Current.ToString() == subsequenceEnumerator.Current.ToString()
&& !subsequenceEnumerator.MoveNext())
{
subsequenceEnumerator.Dispose();
return true;
}
}
sequenceEnumerator.Dispose();
subsequenceEnumerator.Dispose();
return false;
}
That does not look right
it compares each element in sequence with the first and if it's equal it compares the elements with the second
Current.ToString() does also not look right
oh why not?
I wasn't able to use .Equals because that compares the reference and I wanna compare values
Depending on your type ToString might return some garbage
oh yeah but in this case it's always a string
You can constraint the gneeric to always implement IComparable
And use that instead
public bool ContainsSubsequence(IEnumerable<string> sequence, IEnumerable<string> subsequence)
{
var subsequenceEnumerator = subsequence.GetEnumerator();
subsequenceEnumerator.MoveNext();
var sequenceEnumerator = sequence.GetEnumerator();
while (sequenceEnumerator.MoveNext())
{
if (sequenceEnumerator.Current == subsequenceEnumerator.Current
fixed xD
totally forgot about that
When iterating over the sequence, you advance the subsequence
yes
but lets say the sub sequence is of multiple things
you dont create a new enerumator
so itll stay at the second item
This is what unit tests are for
yeah so let's say I compare 1, 2, 3, 4, 5 with 2, 4 like I said above
I iterate first to 1, and it's false. when I get to 2 subseqenceEnumerator will run MoveNext()
so now I'm comparing with the 4 instead
4 2 is not a subsequence of 12345
It will match with 2,4 but it wont match with 4,2 and you just said you dont care about there being anything in between
yeah that's how I want it to work
- there is an issue with repeated moves
maybe the method is named wrong then
I mean it depends on how you want it to work tbh
in the case of
1, 2, 3, 4, 5
2, 4
returns true
1, 2, 3, 4, 5
4, 2
returns false
1, 2, 3, 4, 5
2, 3
returns true
it just makes sure they are in the correct order but it doesn't matter what's between
Exactly, but if you care about a combination of moves being played
when searching for positions
the algorithm looks correct
yeah so if I search for "e6 d6" I'm asking give me all the variation where I've played d6 after I've played e6
but it doesn't ask directly after
and that's fine for my case
๐
oh so I could put in my code there but change it a little so it works with the already implemented stuff
ye this is what my code does
btw if I understand C# correctly, in this piece of code:
if (sequenceEnumerator.Current == subsequenceEnumerator.Current
&& !subsequenceEnumerator.MoveNext())
if sequenceEnumerator.Current == subsequenceEnumerator.Current equals false then the MoveNext() will not run
Thats correct
I do get 196 items instead of 116 but I think that's because my previous version didn't allow anything to be between
Probably :P
uh thunder... should I turn off my pc
oh dang while true slowly drain RAM
I am having a weird issue where my initialised memory turns null and I can't seem to find where exactly.
I am making a grid in editor through code (using [ExecuteAlways]), when I boot the game up and look at how everything is getting initialised it looks good but when I want to run a function after initialisation (when the user clicks) everything in an object that got initialised before is null.
For example, this is the constructor of the object where everything turns null:
public GenericGrid(int width, int height, float cellSize, Vector3 originPosition = new Vector3(), Func<T, int, int, T> initFunc = null)
{
_width = width;
_height = height;
_cellSize = cellSize;
_originPosition = originPosition;
_initFunc = initFunc;
GridArray = new T[_width, _height];
if (_initFunc == null) return;
ForEach(_initFunc);
}
Nowhere I write that GridArray is now null, I never assign it anything except for here. However, later, in this function:
public GenericNullable<T> GetValue(int x, int y)
{
GenericNullable<T> gn = new GenericNullable<T>();
if (RangeCheck(x,y))
{
gn.Value = GridArray[x, y];
gn.IsValid = true;
return gn;
}
return gn;
}
Trying to read from GridArray gives a nullptr exception because for some reason it is null.
Any help?
it shouldnt, you are probably doing an allocation in there
turn on plane mode and hoping nothing will happen
also unplug
๐ค
Where exactly do you check it not being null?
weird
why doesnt my Raycast header show up in the unity editor ? There are no compiler errors either
From a Start() function on an gameobject that is not tagged with [ExecuteAlways]?
in the getvalue function when I look in the debugger it says gridarray is null
I am not an expert on editro scripting ( see #โ๏ธโeditor-extensions ) but could it just be that everything gets cleared once you press play?
That's what I am thinking as well, but I know my start is getting executed everytime I press play and I initialise everything there aswell. Basically, in my start I run my updategrid function which remakes my generic grid which runs the constructor
how do i check if 1 variant's value is changed?
Is this still the correct way to use auto-implemented properties in Custom Editors? https://forum.unity.com/threads/c-7-3-field-serializefield-support.573988/#post-6731440 I am trying to do this, but it doesn't seem to work...
I wouldnt rely on values not being null, afaik that code wouldnt run in a build anyway
as in, execute always is ignored
Right, but start gets run regardless of execute always right?
Because its over a private variable. For it to be visible you have to put it on a public or [SerializeField]
It should - are you sure that that start runs before the other function?
userConfigProperty = serializedObject.FindProperty("<UserConfig>k__BackingField"); Is what I am trying to do. Where
[field: SerializeField] public UserConfig UserConfig { get; } is the auto-implemented property whose backing field I'm trying to serialize.
thank you, that worked
But I get Null Reference Exceptions when trying to do stuff with Move this to #archived-code-advanceduserConfigProperty later.
anyway my code somehow
everytime i boot up and press play
some scripts say value is null
but when i save it again, it run normally again
very weird
buut i still have another problem with this list not showing up in the unity editor
Yes, since the other function gets called on button press and my object is in the scene so the start func is called when it boots up
Maybe Add the [Serializable] attribute to the influencer class.
am i allowed to ask for help here?
yes
Yes, code related
not sure if this is related to a unity update, but a mod for a game i made stopped working and these fields arent accessible anymore (using GUIStyle)
and the border field is now read only
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
guistyle.active.textColor = Color.magenta;
guistyle.hover.background = Texture2D.whiteTexture;
guistyle.active.background = Texture2D.whiteTexture;
guistyle.border = new RectOffset(10, 10, 10, 10);```
doesnt work, it gives me this error, SerializeField doesnt make it visible either
Going to need to see more code to provide any further help I think
Add it to the class. Not the field.
Put the attribute on the class
if you're down for it, I can share my screen
Rather not - playing some other games :P
oh, thank you
- this way others can jump in to help
Alright, any suggestions of what code would help?
Or should I just drop the files that are relevant?
The entire stacktrace probably
Relevant files
(you've never really posted the error either)
Another solution you could try is to just chuck a debug.log in update to see when it becomes null
if it ever does
I tried to do debug.logs whenever the variable gets assigned something and I can't catch it turning null
it's as if it was never initialised
I'll post files and error in a moment
๐
public enum AttachmentType
{
None = 0,
Scope = 1 << 1,
UpperHandguard = 1 << 2,
Handguard = 1 << 3,
Muzzle = 1 << 4,
Cover = 1 << 5,
Mount = 1 << 6,
Magazine = 1 << 7,
Grip = 1 << 8,
StockAdapter = 1 << 9,
Stock = 1 << 10
}```
so i made this enum
[Flags] help enum is multi-selectable
but idk how to check if some object is valid with what i selected
not much people using it i guess?
var scopeAndMuzzle = AttachmentType.Scope | AttachmentType.Muzzle; has scope is (scopeAndMuzzle & AttachmentType.Scope) != 0
@wise arch could you maybe post it on a website? I dont have line numbers in disc..
Also you seem to have integrated a lot of editor code inside of your monobehaviour, thats going to be troublesome when you try to create a build later
you can do basic bitwise operations to determine which flags are set
what about i chosen 8 types?
it will be long sheet
How so?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Well, the editor assemblies dont exist during a build
And your build checks for that -> the build will just fail if you have anything referencing the editor or its utilities
So ideally youd put your editor stuff in another script
GridInventory: https://paste.ofcode.org/5cRqSwdpxkP3FBse5s4SHz
GenericGrid: https://paste.ofcode.org/H9capymskkS2LSxmzCnuPB
You do bitwise operations like you'd do for layer mask operations. I believe there some specific GetFlag() type methods too you can use
So it will remove my entire monobehaviour since it has execute.always?
idk if it worked
Yeah that looks like it
ye i somehow able to google it
No Itll just not compile
It was a shader problem it looks like. The default sprite material rendered both sides
Just as if you miss a using
I see, I think my code should be fine if I just remove the attribute for building
Anyway, that's currently not a problem
I think Application.IsPlaying is also editor only
Gotcha, alright good to know
Now but you refactoring your code so thats not longer a problem might fix your issues
Oh nevermind, Application.IsPlaying existins in a build
Same goes for [ExecuteAlways] 
Stand by ill take another look at your code
Thanks, I appreciate it
Thought so, I couldn't recall reading it in the documentation ๐
how can i fix this? never happened before
how should we know without context?
mainObj.ItemCellReferences.Add(go); is the offending line, but you clearly initialize all of them, I genuinely have no clue, but place a breakpoint on that line / debug.log so you can figure out what the exact state of the program is
@wise arch
You also get multiple "errors" - the function gets called multiple times
First it is somehow too early, then it returns false so some of the earlier checks fail and only then do you rfun into your nullreference
First screen is first time and when I press continue it goes to null. Genuinly don't understand how that's possible
Honestly the code is super hard to decipher
My appologies, what part is unclear of what I am trying to do?
So I don't really know what I am looking at :s
Well I know what you are trying to do, just the way you are doing it is unclear to me haha
You have all this stuff with like parents and owners and stuff? And for some reason an item has multiple positions which is relevant when adding an item?
Right, so what I am trying to do is have every cell point to the item and to be able to efficiently delete an item (which can occupy more cells) I let them all reference to on cell deemed the owner which has a list of all cells that the item occupies
Yea so it's like a tetris inventory system like tarkov
So an item can occupy more than one cell
Aha, makes sense.
The owner and reference variables could have better names but I honestly could not think of anything better
please respond as fast as possible
No one is going to download a file for you, this is a channel for people with coding questions
And we don't discuss game modding here
do you know a game modding community on discord ?
its a joystick
@obsidian heart Not a place for decompile questions.
Anything else that is unclear?
Do you always get the same set of errors or did you click multiple times for your screenshot?
Always same error, I only clicked once for this time
Aha then its probably worth figuring out why it isnt passing your check
And then calls it multiple times afterwards
What gets executed multiple times?
Your AddItem function
:)
so the first time it does indeed fail and I catch the errors so to speak but the second time it just passes all my hcecks but the data is still invalid?
that makes even less sense ๐ข
Maybe because it is always updating, it handles your user input right away
before it calls start
dont quote me on that
No, the logs are only happening when I actually click
Ah okay
So just hitting play and not touching it is fine and without errors
I assume you placed your debug.log in handleplayerinput?
I did my AddItem func called debug.log as the first line in the add item
Aha, well go up the stack and check where its coming from
Input.GetMouseButtonDown(0) should work
It can only come from handle input, just double checked with stack trace. only one reference
Do you have multiple instances of this script?
I was thinking the same, and I am currently double checking but I am fairly certain I have only one instance
Try to remove ExecuteAlways Just to see what happens
Can always chuck a debug.log in start to see whats going on
Remove execute always
Yeah I did
Do you have it attached to atleast 1 gameobject?
Do the other messages still show up?
And your debug.log from start doesnt show up when starting the game?
Start debug.log gets ran, but anything regarding "errors" of additem is not shown, it just goes to error for the list
Okay so remove execute always fixed it from being called multiple times?
Yes, it seems like it, but the error of the list being not null one iteration and the next iteration being null is still present
Are you sure that the reference of the object that you set to null isnt linked to the other reference?
Ah
Thats it
You get your mainObject, which is on the same coordinates as the first position
ah fack ye
Then from the loop you set g.ItmeCellReferences to null (but go is equal to mainobj)
that's dumb of me
I dont quite udnerstand what that foreach does anyway
It works!
var mainObj = _grid.GetValue(x, y).Value;
mainObj.ItemCellReferences = new();
foreach (Vector2Int xy in positions)
{
GridObject go = _grid.GetValue(xy.x, xy.y).Value;
mainObj.ItemCellReferences.Add(go);
go.Item = item;
go.ItemOwner = mainObj;
if (go != mainObj) go.ItemCellReferences = null;
go.VisualObj.GetComponent<Image>().sprite = item.Sprite;
}
hahahahhaha
xD
go.itemOwner is now a circular dependency btw
Yes, that is intentional
And you add yourself to yourself aswell
Yes, also intentional
It is all for the purpose of removing
var itemOwner = go.ItemOwner;
var itemCellRefs = itemOwner.ItemCellReferences;
foreach (GridObject cellRef in itemCellRefs)
{
cellRef.Item = null;
cellRef.ItemOwner = null;
cellRef.ItemCellReferences = null;
cellRef.VisualObj = _visualPrefab.GetComponent<RectTransform>();
}
itemOwner.Item = null;
itemOwner.ItemOwner = null;
itemOwner.ItemCellReferences = null;
So this is the remove item, I get a coordinate
and I basically get the value of the grid, ask the item owner and all its reference which basically means: I get all cells that the item occupies
I see, well good you got it resolved haha
I saw this line in the beginning and was like hmmmm this is kind of sus
Well deserved one too ;)
@winged mortarFigured you would like to know, I added execute always back in and it still works ๐

anyone have tried making a split screen local multiplayer in unity? im currently following this tutorial on youtube https://youtu.be/l9HrraxtdGY but didnt get the same output. if someone have an experience, can u help?
Already implementing all the scripts in the split screen multiplayer video, and everything works like in the video except when new players joined, the camera of the players suddenly move to the new players although the layers and the culling mask works fine. Here's some screenshot of what i mentioned.
the problem is that when player2 joined, player1 cam suddenly focus on player2.
player1 can also perform lookAt for both cam while player2 cant even perform lookAt.
the tutorial's full code https://github.com/onewheelstudio/Adventures-in-C-Sharp/tree/main/Split Screen
as'
Does anyone here know how could I make laser like this? I need it to be gameobject cause I need it have layer and collider, so I cant just use raycast...
LineRenderer
Use circlecast or boxcast for the collision detection
so what are you asking exactly, you're in a code channel. Do you want to make a dynamic mesh or
yup def better off using overlapbox or boxcasting
I mean I putted taht player takes damage when player collides with a layer. Could try to use boxcast tho
that's what the boxcast/circlecast is for
I mean I used boxcast to actually check is player colliding with layer, so yeah...
is this a question?
I have a very basic script so that the player moves horizontally according to the mouse cursor (follows the mouse).
Everything works fine, except i don't know how to calculate the parameter values for the animator and then add a walking animation to the whole thing.
I tried saving the last frame's position and checking whether the mouse moved to the left or right in the next frame, but now the animation is super choppy (because it restarts the animation every frame).
Because I want the player to move at the speed of the mouse (so the animation should speed up accordingly), I can't implement that the player has to walk at a constant pace and the "mouse has to wait for it".
Does anyone know how to implement that feature? :)
Hi, I am making a skin shop in another scene, how can I make it that if I push on the next button (to go to the next skin) that it switches sprite and how can I get this sprite into the skin gameObject sprite. Can u help me out and do i need to send screens?
Are you using Animation Blend Trees ? You can also add smoothing to your parameter. Instead of using the value at this frame, you can use the value in the last X frames. And, should seriously consider using the player speed instead of the mouse position for the Animation of the player.
The best for you would be to learn the fundamental by following a complete tutorial or using resource such as !learn.
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
I forgot to mention that this is in a 2D space, and i am using parameter transitions. It is used for a minigame where you have to sometimes be fast and sometimes slow, that's why the speed of the animation should be determined by how fast you move the mouse
can any of you help me?
So, you are not using Animation Blend Tree ?
Do u recommend a tutorial?
Usually, you have a blend between Idle and Walk.
I am
!learn is a great place to start learning about Unity.
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Then you want to smooth the parameter for the blending so the value does not change to fast.
which course is recommended
If I use pixel art (where you usually don't blend the animations) does this work too?
So, you do not use Animation Blend Tree...
Ok
I'm confused, sry, this is what i'm using :')
This is not an Animation Blend Tree. It is fine. We are just not working with the same tool thus the solution might be different.
You want to play with interruption source and transition length. Also, you can still smooth your parameter.
for sprites I just have almost everything connect to AnyState and set all transition times to zero
I see, thank you! Actually, just making the exit time longer helped a lot
since typically sprites dont have any way to blend and you just wanna hard cut from AnimationA to AnimationB
Kinda different in the situation that @true python was. But true, you might not want to have any transition time with sprite base animation.
only time you really bother not transitioning out of "Any State" is when you want to automatically "chain" animations inherently (like combo attacks and whatnot)
like if you wanna limit it so AbilityB can only play out of AbilityA, then youd actually do AnyState->AbilityA->AbilityB
(Or use code)
otherwise you pretty much end up with animators that typically look like this for sprite stuff, lol
well the animator already does this for you so, why bother re-inventing the wheel right? that sorta stuff is what the animator is good for
Simply do the thing inside your own statemachine of your character.
A good example, and you can see it in my pic sorta, is if you have like "slide stop" animation for when running and then you stop running, instead of needing to write logic the animator can just straight up automatically handle that transition for you without any code required
Just have like
AnyState -- State==Running-->Running--State==Idle-->RunningStop or whatever
And then RunningStop will just naturally transition back to your idle animation once it finishes playing if you have transition time set, ez
It does not look like you are doing that in your Animator.
yeah you can see em sorta, the ones that are double long
The Animator.Play just remove the need for the usage of Parameter in the case of AnyState
You can still do the samething
Params primarily help for sprite stuff cuz typically you have both a Direction and State of some sort
only thing I am a bit sad about is Mirror doesnt work for sprite animations, would be nice if there was an AnimatorController2D or something that specifically was setup for sprites so Mirror worked the way you'd hope (flipping it around)
Can you just not rotate the transform ?
you can but it would just be nice if there was an animator from unity optimized for specifically sprite stuff
its just a bit of a noob trap when you see this in the animator for a 2d game and you're like "oh sick easy" and then it doesnt work at all lol
I do not think you should use the Animator for Sprite base animation because the overhead is higher than what is needed.
(If performance is a concern)
I have no idea, I mean if there's better alternative tools folks have made that are free Id love to hear about em
writing one myself from scratch though sounds like quite the undertaking, and a lot for someone who might be much newer to C#
Definitely. Not exactly sure if there is any asset for that.
im not quite sure where to put this so ig ill have to ask it here until i get redirected
we all know how to code an arcade game, but how do you make your game sequenced like any story based game you'l play?
What is best practice for running custom logic whenever a SerializeField is updated by someone in the Inspector? Is there a standard way to do this?
My best guess is this:
https://docs.unity3d.com/ScriptReference/EditorGUI.EndChangeCheck.html
But, I am not sure.
Thanks
It depends on what you want to do. The quickest is OnValidate()
Doesn't OnValidate get called when any SerializeField changes?
no
almost
see this
when it's changd in inspector
it can be also public
I was unclear, my bad. That was what I meant.
without serializeField
yeah
I want some logic to run only when a single specific thing is changed in the Inspector.
Not when anything changes in the Inspector.
I could have additional fields saved to check whenever things change in OnValidate, but that seems ugly to me.
yeah, NaughtyAttributes are cool
You can also create a PropertyDrawer.
Which you would do the same as NaughtyAttributes I guess
just make sure to install them in asset store
it's simpler
NaughtyAttributes is open source isnt ? You can just extract what is needed.
yes
I do not think you to have everything from it in theory.
It's absulutely free and you can redact it how you want
yeah, but there are useful things like ShowIf and HideIf
very useful
Which you can take whenever you want.
I mean, it is just preference there.
You do what you want.
I'm just pointing out that it is not that hard to implement this functionnality.
yes, we also can write our own attributes
just nobody has to do that if someone has already implemented it for you
Yeah I might skim through it to get a general idea of what they do. For my use case I don't want another dependency.
So I have line renderer like in first image. Now can i make so that its more like in the second one
It's just an editor tool. Even if you remove it, your data shouldn't change beyond how you previous serialized it all.
Isn't there an animator curve along with the line renderer? Otherwise just extend into the plane there ;)
Wdym?
Is there a way to check if an object is somewhere as a parent, parent of a parent etc. of another object? I'm gonna be doing it in onValidate, so I'd prefer it to not be too slow
do I just do a recursive CheckIfParent function or something like that? Seems like a slow idea
what's the difference?
OnValidate is the place you'd want to do the slow stuff though, so if you need to recursively check then go for it
A GameObject? or a component? Or what
also you can just use a loop rather than recursion
Isn't OnValidate called like every editor frame, when the object is selected?
recursion for cool points though
Anyway this iexists @wintry crescent
if (potentialChild.IsChildOf(potentialParent))```
https://docs.unity3d.com/ScriptReference/Transform.IsChildOf.html
> Returns a boolean value that indicates whether the transform is a child of a given transform. true if this transform is a child, deep child (child of a child) or identical to this transform, otherwise false.
recursion is uncool imo ๐
They lok different when touching ground.( 2nd image was made in paint so it doesnt look perefect)
I have a component, that needs to get a reference to a component in a parent object somewhere up up the tree of components, and it needs to always be up to date, in editor
just extend it further
ooooh, nice, thanks!
GetComponentInParent<TheType>()
that seems super slow. I've had OnValidate freeze up my editor in the past, never again
OnSerializeCallback is called every frame, but OnValidate is only when the object is serialized (or deserialized?)
it's exactly the same as if you are doing the recursion or loop yourself. Possibly faster since it'll be in C++
it's really not gonna be that slow - it is basically O(heightOfHierarchy)
that's an equivalent to calling GetComponent in Update() I think
what about edges? Just leave it?
huh?
who said anything about Update
this I mean
what does that have to do with Update though?
OnValidate gets called very often sometimes, when edititng values on a component
as often as Update() would be called during runtime
depends how you change the values, for example dragging to change, or using a slider does that
Can someone explain me why the folder created has a capital S?
idk but you misspelled Assests. probably not created by this code.
delete the folder and recreate it again, maybe? Seems like it didn't update properly
and yea, the typo
OMG I JUST REALISED I MISSTYPED
haha
I'll try again
nope it only breaks with the s added
hmmmm
You can always add your own logic to prevent continuous validation, or control the validation via bool on the gui
^ I do that for IDs
it for whatever reason sees it as two diffrent words (map) and (S)
yea, I'll just use the IsChildOf, seems exactly like what I want
I'm wondering now though, is OnValidate called when an object changes parents? Would OnBeforeSerialize or OnAfterDeserialize be?
OnBeforeSerialize is called everytime the editor is refreshed, so that's usually bad to use, at least for larger operations
OnAfterDeserialize I do use a bit in nested non-mono classes and it does seem to run validation only when that specific instance of data is edited
I have this game with view angles that range from 0 all the way until it reaches 359.999... then it loops back to 0.
My question is, how can i find the closest distance between the two angles? Since just subtracting the two will not always work
[2023-07-20T20:44:42Z - Unity] [Package Manager] Done resolving packages in 80.49s seconds
[error] [2023-07-20T20:44:42Z - Unity] An error occurred while resolving packages:
[2023-07-20T20:44:42Z - Unity] Project has invalid dependencies:
[2023-07-20T20:44:42Z - Unity] com.unity.render-pipelines.universal: Package [com.unity.render-pipelines.universal@14.0.8] cannot be found
[2023-07-20T20:44:42Z - Unity] com.unity.visualeffectgraph: Package [com.unity.visualeffectgraph@14.0.8] cannot be found
[2023-07-20T20:44:42Z - Unity]
[2023-07-20T20:44:42Z - Unity] A re-import of the project may be required to fix the issue or a manual modification of BUILD_PATH/p/Packages/manifest.json file.
[2023-07-20T20:44:42Z - Unity] Exiting without the bug reporter. Application will terminate with return code 1
I am not really sure what they mean by "remport" the project? Delete it and git clone it again or what?
You should have an option in the menus to re-import all.
Forum post that might be relevant to re-importing: https://forum.unity.com/threads/updating-unity-may-require-re-import.457144/
Reminder that this may fix the problem - no guarantees.
welll...... the thing is... im not using unity for this case ๐
unless the definition of the function is documented somewhere
Hey guys, im using a lookAt() thing in my script for my turret, but it doesnt work. It is animated, but i had to do a little something, I had to create an empty gameobject to animate it so i can animate separate objects or the entire group. But the lookAt() thing have to move IT. Please help
You might need to show your lookat implementation if it is important.
I'm confused by this. I have a RectTransform under the parent canvas. The following code shows 2560 x 1540 (not 1440), when the size of both the parent rect and "this" rect are 2560x1440.
Bounds parentBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(parentRT);
Bounds ourBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(ourRT);
float parentWidth = parentBounds.size.x;
float parentHeight = parentBounds.size.y;
float ourWidth = ourBounds.size.x;
float ourHeight = ourBounds.size.y;
v($"ParentWidth:{parentWidth} ParentHeight:{parentHeight} OurWidth:{ourWidth} OurHeight:{ourHeight}");
where's the extra 100 pixels coming from?
whats the scale of the root canvas
go down the chain look for non 1,1,1
that's all there is - Canvas and "TitleScreen"
titlescreen is where the script resides, and is also correct as far as I can tell:
you have canvas rescaler script
nvm i just made a parent for the BODYBODY thing and now its working
what does it do and when
hm.. lemme investigate, maybe that's it
Hmm, scales with screen size.. Would that have any impact?
ah, i recall.. my canvas scaler script is a script that forces the canvas to the same aspect ratio - either letterboxing on the left or right
i must have the wrong "magic number" in there for the desired aspect ratio
hm.. no, that looks correct as well.. 0.5625 (2560x1440)
Hopefully 
Lemme try just disabling that component to see what happens
Nope, still showing 2560x1540
hmmmm
ok
lets assume everything is correct and the margin you get is from bounds themselves
so, interestingly when i just debugline the bounds object, i get "extents" of 1280x770
what is the task at hand
i'll link to my OP yesterday, standby a sec
bounds are incorrect, generally
all bounds from mesh/collider have a shell
they arent precise
โ๏ธ
i would try with a group layout first
Basically I'm looking for a way to .. streamline my current process for laying out UI elements .. which is finicky and tedious, so I'm writing a custom inspector to extend RectTransform to do it automatically.. but I'm having trouble getting the correct numbers from the components' members
"Rebuild Anchors" button above
since the child will have LayoutElement with min width/height set
LayoutElement..?
built in component
I see.. Should I get the values from that? I'm not super familiar with all of the RT members tbh
googling
what im saying is that you can use the built in layout groups
at least you can attempt to do that so that you dont write crutches for problems that can be solved with unity components
well that's my OP ๐ I don't know of a way to get the % anchors automatically, I have to do it by hand
There's a video attached to the OP above - have a peek, it should make it more clear what I'm trying to accomplish
Depending on your %s the existing layout scripts should get the job done
so it behaves as if it was anchored but wont go below certain size
Right but I mean.. calculating the %s is the part I was hoping to automate
instead of all that fiddly typing of numbers/formulas in the video
I do this repeatedly for every component in our apps to get the layout to scale properly
I'm hoping there's ... functionality that I'm just missing
The existing scripts evenly divide into rows/columns and with smart nesting of em you can get your desired sizes usually
Oh, I'm not using any layout elements, that's often harder to get things how I want
If you just draw a simple example in paint or whatever of how you want the UI subdivided, it's pretty easy
Like if I just want some floating icon or dialog box or whatever.. I'm not going to make a layout element with one item in it and custom padding.. even that seems like it wouldn't work
well, take the video as my example - I want a dialog box that's 1334x666 pixels to be right in the middle of the screen (with a reference resolution of 1920x1080 or 2560x1440, take your pick)
Well what if the width is less than that
ideally I could just drop it in, hit a button to anchor it all by % and I'm done.. but I don't know if that exists? the anchoring buttons I've seen use pixel references
I want the dialog to scale up/down by % as the canvas scales up/down - so it's always the same relative size if you're playing in 190x60 or 1900x600 or 2560x1440
like this
โ๏ธ to get that working like that, I have to manually type in the 4 anchors, which is what i'm trying to automate
I just... can't seem to get the "true" bounds/extents of the current and parent rect transforms.. the recttransform utility method seems to be giving me 100 extra pixels
maybe i should use the overload called on the parent with the "this" RT as the child? https://docs.unity3d.com/ScriptReference/RectTransformUtility.CalculateRelativeRectTransformBounds.html
I have the following code in my script:
private void OnValidate()
{
if (!_controller || !transform.IsChildOf(_controller.transform))
{
_controller = GetComponentInParent<VehicleProblemController>();
if (!_controller)
{
Debug.LogError("No controller found as parent for " + gameObject.name, gameObject);
}
}
}```
Every time a recompile happens, I get 1/2 errors per each instance of the script present in the scene, then it quitetens down. When I check, each component has the _controller variable properly assigned. What's going on?
the first signature in that document
don't use null checking on unity objects
I know, there's no null check there
!_controler ?
so setting anchors works for you?
I don't think that's just a null check? I always thought that's how you're supposed to check for "null" or just a missing object
== null is null check for unity objects
I always thought that's the bad way of doing it
i can send you some code to get true bounds
and you're supposed to just look at it as a bool
!_controller is the same as _controller == null which is not what you are likely expecting, and certainly not in OnValidate()
Manually typing them, yes, but I was hoping not to do that - for the game jam last week I realized how often I had to do it.. I probably had to do that process like... 200 times?
Guys, can i Lerp this?
you can write a method that sets anchors to corners
Basically I say "ok this object is 100x100 and is in the center of a 760x200 object" and then calculate the anchors by hand
i use it all the time but it comes from now nonexistent on the store asset
This is what I'm trying to do ๐ but.. I can't seem to calculate the RT properly
lemme have a look at the source of that if it's available
that's news to me, I thought it's a shorthand for .IsUnityNull()
should I use that instead?
Maybe consider https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html if you want gradual change rather than instantaneous change.
I would track it manually - GetComponentInParent will return null if the object isn't found, so .. stick a bool on it, something like isInitialized or isFound (since you don't want to be calling GetComponentInParent often, it's slow)
i wrote this small class i embed in code where i need to keep track of rect in real time https://gdl.space/wutuvisedo.cs
you can wrap it into a stand alone component
all you need is to call update and you get world space data
Yeah - I have something like that, but I'm not sure if world space is .. going to translate to UI/canvas space
i have some old library that does something like this.. it's similar to yours, it gets all the info from GetWorldCorners() and .. does some math
right, i enforced the canvas to stay in world space
that's my problem though. GetComponentInParent returns null, I get an error 1-2 times after a recompile, then it's apparently called again, GetComponentInParent finds what it's looking for, and no error happens. I'm just wondering what is really happening there
even tho the canvas is set to world mode, and uses a camera, im rescaling it and repositioning the camera so that it is always at 0,0 and has correct world scale
same thing, different application - GetWorldCorners() with some extra shit, basically
Unity serializes references and variables and stuff.. so you're probably better of starting from what you're trying to accomplish or the bug you're trying to solve rather than doing some .. gymnastics in OnValidate there - I didn't look too closely at your issue but I'm pretty sure that null checking a component there is going to behave differently than you expect, depending on how/when unity serializes it
!comp should work
that is correct way
where does the error come from
scene object/prefab
The functionality I need, is to always have a proper reference to a controller that is a parent to the object with this script. This is actually a separate function, that I call both from OnValidate and during runtime. I renamed it to OnValidate here, because my issue was purely in edit mode, and I wanted my shorten the code block I posted.
The functionality is to automatically update the controller when a component changes parents during gameplay, for example by being dragged around in the hierarchy, or if it's copied or moved to different parents in edit mode.
I can't do the bool flag idea, because it could result in an actual null error when checking it - since I can't just check for a null, or a unity null. Is there anything else I can do?
using IsUnityNull doesn't work
what's super weird is that I have 15 objects, each with 1 instance of the component, yet I get 20 errors every time...
thats why im asking if its scene object throwing or prefab
because if its the prefabs, they wont be ever able to locate the parent
guys how do i instantiate 1 gameobject to 2 points?? I want to instantiate a bullet from these 2 barrels but i only know how to instantitate a bullet from 1 barrel
like this
How do i create something like the update method where it calls all references in one place and can have multiple definitions in different scripts
alternating or simultaneously?
just instantiate twice
fr
wrap it into a method
private void InstantiateProjectile(GameObject prefab, Vector3 pos, Quaternion rot, float lifetime)
{
GameObject clone = Instantiate(prefab, pos, rot);
clone.GetComponent ...
Destroy(clone, lifetime);
}
yeah but i need 1 bullet in each barrel
right so you call it twice
will this work
it will but to avoid unnecessary code duping i suggested you wrap it into a method
if it works then i will use this
also if you store your prefab as a Rigidbody reference instead of a GameObject reference then Instantiate will return a reference to the newly created Rigidbody instance so you can skip the GetComponent call
@ashen yoke Using the world space method worked and now I have a rect transform auto-anchor button ๐
@trim ferry There's no off topic here
blergh, this is a bit annoying that there isnt a built in easy way to convert Vectors in all types
just cast to Vector2, that can be implicitly cast to Vector3
blegh, thats annoying when you gotta do it a whole bunch of times is my point
i mean, that's what happens when you use a type that cannot be implicitly converted to the type that you need ๐คทโโ๏ธ
you do only have to do it once though, just store the result of the cast in a local variable and use that instead of casting on each individual line you use kvp.Key
I haven't used the Input Manager in forever and I have forgotten how to reference it in another script. Does anyone know?
yes... that is what I am lamenting, that they havent done IEquatable or whatever the interface is so that they can be implicitly converted
if you're using the input manager you use the methods on the Input class to get input
I know what I need to do, I just find it mildly annoying that I have to do it :p
Guys, i cant mention my FirstPersonController script in another script. Like: public FirstPersonController PlayerScript;
is there something wrong
what do i have to change here
make sure you add the using directive for that namespace
@ashen yoke Quite a bit of fiddling but it works. One button to size an arbitrary object to % and location of the parent RectTransform. No more pixel math. ๐
When you have an issue it helps usually to show any error messages you are seeing.
Heyo, is there a clear way to increase performance here?
My method is simply checking the six sides of a voxel to see which faces are visible.
Could I increase performance by passing the method x,y,z coordinates so I dont have to do things like (IsValidPoint(coords + Vector3Int.up)
For context, this is how I check one of the sides:
if(IsValidPoint(coords + Vector3Int.up) && blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.up)] == BlockType.Air)) {
visibleSides[0] = true;
isBlockExposed = true;
}
Paste a bit more code - are you doing that vector op_Addition multiple times on the same value? without seeing more, that's the obvious culprit, but that should be really quick.. even 47k calls shouldn't take 30ms
This whole thing executes in <5ms normally
when deep compiler is on it inflates a ton
you could try Benchmark.NET to get better insight into it
I had success with it in the past in untangling a hairy recursion performance thing
looks like a TON of vector operations. The best way to improve will be to reduce the number of operations you do. Which depends on the algorithm in question.
Heres a method that gets called a lot in that part i pasted, IsValidPoint, and a version i propose that uses ints instead
public bool IsValidPoint(Vector3Int coords) {
return (coords.x >= 0 && coords.y >= 0 && coords.z >= 0 &&
coords.x < chunkSize && coords.y < chunkSize && coords.z < chunkSize);
}
public bool IsValidPoint(int x, int y, int z) {
return (x >= 0 && y >= 0 && z >= 0 && x < chunkSize && y < chunkSize && z < chunkSize);
}
i think extracting coordinates 6 times is bad in that method, could be wrong
but yeah one easy win here is not to repeat this duplicated calculation coords + Vector3Int.up
show more code
doesn't work in unity.
however there is the performance testing extension for the test runner
https://docs.unity3d.com/Packages/com.unity.test-framework.performance@1.0/manual/index.html
This is embarassing code ngl because i am manually typing 6 directions ๐
just use a for loop
static readonly Vector3Int directions = new Vector3Int[Vector3.up, Vector3.left, ...etc];```
just loop over those
rather than manually doing the same thing 6 times
reduce your code repetition 6x
I'll paste it lol
private bool TryGetVisibleSides(Vector3Int coords, ref bool[] visibleSides) {
isBlockExposed = false;
if(IsValidPoint(coords + Vector3Int.up)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.up)] == BlockType.Air) {
visibleSides[0] = true;
isBlockExposed = true;
}
} else {
visibleSides[0] = true;
isBlockExposed = true;
}
if(IsValidPoint(coords + Vector3Int.down)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.down)] == BlockType.Air) {
visibleSides[1] = true;
isBlockExposed = true;
}
} else {
visibleSides[1] = true;
isBlockExposed = true;
}
if(IsValidPoint(coords + Vector3Int.left)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.left)] == BlockType.Air) {
visibleSides[2] = true;
isBlockExposed = true;
}
} else {
visibleSides[2] = true;
isBlockExposed = true;
}
if(IsValidPoint(coords + Vector3Int.right)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.right)] == BlockType.Air) {
visibleSides[3] = true;
isBlockExposed = true;
}
} else {
visibleSides[3] = true;
isBlockExposed = true;
}
if(IsValidPoint(coords + Vector3Int.forward)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.forward)] == BlockType.Air) {
visibleSides[4] = true;
isBlockExposed = true;
}
} else {
visibleSides[4] = true;
isBlockExposed = true;
}
if(IsValidPoint(coords + Vector3Int.back)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.back)] == BlockType.Air) {
visibleSides[5] = true;
isBlockExposed = true;
}
} else {
visibleSides[5] = true;
isBlockExposed = true;
}
return isBlockExposed;
}
embarassing is fine, you might get helpful tips to make it less embarassing which.. ultimately is going to be more simple
Sorry for your eyes
ok so yeah
Rest of the code doesnt look like this
off the bat we can cut these additions in half
slightly embarassing ๐ but yes, you can simplify this
e.g.
if(IsValidPoint(coords + Vector3Int.back)) {
if(blockData[GetIndexFromLocalCoordinates(coords + Vector3Int.back)] == BlockType.Air) {```
becomes
```cs
var toCheck = coords + Vector3Int.back;
if(IsValidPoint(toCheck)) {
if(blockData[GetIndexFromLocalCoordinates(toCheck)] == BlockType.Air) {```
now we have 1/2 as many addition ops
Oh yeah I dont know how i didnt see that
also again recommend this to reduce code repetition #archived-code-general message
so you don't have to fix this 6 times lol
True
I was wanting to possibly turn this logic into a job later with burst compiler
and try to make things more powerful, but it works just fine right now
also what does GetIndexFromLocalCoordinates do?
you know what might be better, btw - perhaps refactoring your IsValidPoint into a List<Vector3> GetValidNeighbors() and then just checking those for "if they're filled or air"and then setting the visible = true for those, instead of writing essentially the same thing 6 times
So the voxels are stored in a single array, 16x16x16 = byte[4096]
private int GetIndexFromLocalCoordinates(Vector3Int coords) {
return coords.x + (coords.y * chunkSize * chunkSize) + (coords.z * chunkSize);
}
I believe yeah you can check 3 sides
and another big optimization you could potentially do here is to skip the check for any coordinates you have already previously checked. That will require coordination with the other code that orchestrates this
I would guess you're checking many coordinates 2-4 times
maybe more
Yes the data is cached
There is a thing called exposureMatrix which is an array of bool[6]
same indices for the voxels
maybe I could do things differently
reduce that so theres no redundancy
@hasty haven
private bool TryGetVisibleSides(Vector3Int coords, ref bool[] visibleSides)
{
isBlockExposed = false;
void TestPoint(Vector3Int p, BlockType checkFor, int index, ref bool[] visibleSides)
{
if (IsValidPoint(p))
{
if (blockData[GetIndexFromLocalCoordinates(p)] == checkFor)
{
visibleSides[index] = true;
isBlockExposed = true;
}
}
else
{
visibleSides[index] = true;
isBlockExposed = true;
}
}
TestPoint(coords + Vector3Int.up, BlockType.Air, 0, ref visibleSides);
TestPoint(coords + Vector3Int.down, BlockType.Air, 1, ref visibleSides);
TestPoint(coords + Vector3Int.left, BlockType.Air, 2, ref visibleSides);
TestPoint(coords + Vector3Int.right, BlockType.Air, 3, ref visibleSides);
TestPoint(coords + Vector3Int.forward, BlockType.Air, 4, ref visibleSides);
TestPoint(coords + Vector3Int.back, BlockType.Air, 5, ref visibleSides);
return isBlockExposed;
}
Oooo
What is with the inline function like that, TestPoint
what with it
Or are you just putting the implementation in the middle there
its a local method
oh yeah this is huge
TIL thats a thing, C# isnt my background
if there's no early out rn that's a problem
at a minimum you could simplify the above like this:
private bool TryGetVisibleSides(Vector3Int coords, ref bool[] visibleSides) {
isBlockExposed = false;
Dictionary<int, Vector3Int> neighbors = new() { 0 = Vector3Int.up, 1 = Vector3Int.down, ... };
foreach (var kvp in neighbors) {
Vector3Int loc = kvp.value;
int bdIndex = GetIndexFromLocalCoordinates(loc);
if (!IsValidPoint(loc) || blockData[bdIndex] != BlockType.Air) continue;
visibleSides[kvp.key] = true;
isBlockExposed = true;
}
return isBlockExposed;
}
I wrote that kinda quick, but I think? it's functionally identical to your code block
isBlockExposed needs to either be a ref parameter or this needs to be a local functiion
that allocates a dictionary on each call, dictionary is not necessary since the LUT is finite you can just use array
Definitely wouldn't do this though:
Dictionary<int, Vector3Int> neighbors = new() { 0 = Vector3Int.up, 1 = Vector3Int.down, ... };
super wasteful
in both cases it will be slower than inlined code
yeah that should be a local readonly dict
static readonly Vector3Int directions = new Vector3Int[Vector3.up, Vector3.left, ...etc];
it shouldn't be a dict at all
just to get the point across though in terms of readability/looping
array is fine
well he needs the index to set visibleSides
which you get in a for loop
for (int i = 0; i < directions.Length; i++) {
var direction = directions[i];
}```
ah, fair, although that makes the order of elements in the array important, but.. now we're quibbling ๐
sure but it will be a lot faster than dictionary lookups
they're 0(1) sure but there's a whole HashCode call etc in there
in any case i think PB's suggestion to track whether or not a given block has already been checked (globally) is best, since at a minimum you're doing around 6x too many checks
on top of all the guards
bound checks, type checks, etc
Heres something for thought: I was wanting to check the corner neighbors as well but that adds 8 more checks to the equation
Originally at least
tho ref hash should just return the ptr
very easy to do once you're using an array for the directions. All you do is add more directions to the array
The reason I want corners is so the blocks can render beveled edges automatically
does Physics2D.OverlapPoint not work for UI elements in a Screen Overlay Canvas?
Physics2D only interacts with 2D physics components
why would you use physics for UI?
yeh I have a collidor on it
๐คฎ
why
stop now
Im already scanning for hits
its not going to work
what are you trying to do
again, why
UI elements live in a totally different coordinate space than physics objects
it won't work properly
^
ui by default maps 1 pixel to 1 world unit
for it to work each of your 2d pixels have to be 1 unit
so ppu will be 1
I already have code in Update that scans for what I am hovering my mouse over, wanted to re-use that for when I hover over UI elements as well since I've already done the hit check
then maybe you can make it work
makes sense
use the event system interfaces like IPointerEnterHandler
