#archived-code-general

1 messages ยท Page 153 of 1

winged mortar
#

You'd create a single scene that supports loading a level from another file

winged mortar
#

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

gray mural
#

should files be saved in json?

winged mortar
#

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

gray mural
winged mortar
#

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 :)

glossy granite
#

how do you know that you are running the build on the steam deck?

gray mural
winged mortar
abstract nimbus
#

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

winged mortar
gray mural
#

thanks for your help

abstract nimbus
#

wdym long format data?

winged mortar
#

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

abstract nimbus
#

so instead of having multiple lists of moves, I have another list of moves that contains all the moves in a chapter?

winged mortar
#

Yes

abstract nimbus
#

aha

winged mortar
#

If you want to avoid those foreach statements

#

But honestly if it works it works :)

abstract nimbus
#

yeah that makes sense

winged mortar
#

No point in fixing something that ain't broke

abstract nimbus
#

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

abstract nimbus
#

but that's not fixing, that's improving ๐Ÿ˜›

#

you could say readability is broken ๐Ÿ˜‚

winged mortar
#

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

winged mortar
#
    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

abstract nimbus
winged mortar
#

Again I dont know what move.fen is

abstract nimbus
#

do you know what fen is in chess?

winged mortar
#

Nope

#

im 700 at best

#

I can click pieces on chess.com but thats about it :)

abstract nimbus
#

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

winged mortar
#

Boardstate then?

abstract nimbus
#

yeah

winged mortar
#

But then the variation would be different

#

You can get to the same board state by doing a different set of moves

abstract nimbus
#

yeah the variation would be different but since I have a UI with a list of chessboards I don't wanna show duplicates

winged mortar
#

Gotcha :)

#

Anyhow, try to understand why the linq I wrote is different from the one you made

cunning zephyr
#

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.

abstract nimbus
#

yeah you wrote some new stuff for me so I'm trying to understand it hehe

winged mortar
#

I am not sure if DistinctBy exists in unity by the way, but you can look up an implementation for that online

abstract nimbus
#

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

winged mortar
#

We've been scammed

abstract nimbus
#

ignore the Add new text ๐Ÿ˜‚

#

lmao

winged mortar
#

Theres the !csdiscord

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
winged mortar
#

okay thats not it

#

2s

abstract nimbus
#

it says code-general so I assumed it's not unity relevant ๐Ÿ˜›

winged mortar
#

!cdisc

tawny elkBOT
abstract nimbus
#

aha ty

winged mortar
#

Yeah unity coding concepts

#

I mean people help here

abstract nimbus
#

oh

#

then I scammed you I guess ๐Ÿ˜‚

winged mortar
#

but usually its like, my monobehaviours dont get activated using this piece of code please help

abstract nimbus
#

oops lol

#

๐Ÿ˜‡

#

but ty for the help anyway

devout harness
#

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

abstract nimbus
dusk apex
#

Maybe with 1, 0, -1

abstract nimbus
#

I'm still trying to understand the other function you wrote tho

dusk apex
#

Where the 1 and -1 would refer to the opposite sides and 0 refer to both

lean sail
#

although you will need a system for what corner matches to what bit with what i suggested

devout harness
#

Ah I gotchya

winged mortar
abstract nimbus
#

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

winged mortar
#

Using linq you create an expression tree that isnt executed untill you call to list

abstract nimbus
#

oh

#

now I've learnt a game changer

white gyro
#

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

lean sail
white gyro
#

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.

winged mortar
#

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

white gyro
#

Yeah that sounds about right

winged mortar
#

Structure is nicely done by the way! :)

white gyro
#

So there's a grounded movement component and a flying movement controller and basically the state machine just toggles which one is active

winged mortar
#

Well you mentioned that you already decoupled movement from input

#

So you could also redirect the input to another component

white gyro
#

Right

winged mortar
#

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

white gyro
#

I feel like a state machine is the right solution for this but at the same time feels like it's completely unnecessary.

winged mortar
#

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

lean sail
#

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

winged mortar
#

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

white gyro
#

I'll probably continue without a state machine for now and stash the state machine in a separate branch.

winged mortar
#

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

white gyro
#

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.

winged mortar
#
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?

white gyro
#

Well, the one I wrote was a lot more involved with each State having their own classes so at least I can save that

winged mortar
#

ohh yeah for sure

#

but it doesnt have to be that complicated

#

you already did the work

#

so why not use it then xD

trim schooner
#

You should be caching those GetComponents so you only do them once

white gyro
#

Definitely.

thin kernel
#

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?

white gyro
#

Have you tried doing a clean build in the cloud?

gray mural
#

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?

thin kernel
latent latch
gray mural
#

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

latent latch
#

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

gray mural
#

first of all I need to know how to create it

gray mural
latent latch
#

go into scene mode as the game is ran

gray mural
#

and yes, not all GameObjects in the scene are prefabs

gray mural
#

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

winged mortar
#

Dont you want others to also be able to creat elvels for your game?

latent latch
#

Ah, yeah I see what you mean

#

I've done this before let me look

gray mural
#

I need to do it step by first

winged mortar
#

Whatever you are going to do in the eidtor right now

gray mural
#

and my first step is to create GameObject in editor

winged mortar
#

It won't work in the build

#

Editor stuff doesn't exist in a game build

gray mural
winged mortar
#

Because it's editor specific code

gray mural
#

it should be saved in the scene

gray mural
quartz folio
#

the scene (as a loadable asset) is immutable in a build

#

and prefabs are not a runtime concept either

winged mortar
#

If you want other users to able to create levels for your game

#

you need to store it some other way

latent latch
#

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

gray mural
#

that's what I need to achieve first

winged mortar
#

We had a conversation about this this morning

gray mural
#

you had said it, yeah, but I still have no clue how to do it

winged mortar
#

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/

ยทยทยทยทยทยทยทยทยทยทยท...

โ–ถ Play video
#

I told you to google

#

level editor unity

#

gave me this video

#

This is one way to do it

#

Watch it

gray mural
#

I have watched it already

#

it gets infomation about drawing

winged mortar
#

Then you should probably specify what you want

gray mural
#

it converts drawing into prefabs

quartz folio
#

Then find a different tutorial that does what you want

winged mortar
#

Yes and for an ingame editor you'd need a script that converts prefabs into drawings

gray mural
winged mortar
#

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

quartz folio
winged mortar
#

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

gray mural
winged mortar
#

image is just interpretable for humans

gray mural
winged mortar
#

You cant

#

(form a build)

gray mural
quartz folio
#

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

latent latch
#

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

quartz folio
#

and there are no standards

winged mortar
quartz folio
gray mural
latent latch
#

Oh, in build? Ok well that's complete custom code then

winged mortar
#

โšช

gray mural
quartz folio
#

You find a tutorial to do with saving and loading, and you follow it

winged mortar
#

Perhaps this one?

winged mortar
#

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/

ยทยทยทยทยทยทยทยทยทยทยท...

โ–ถ Play video
gray mural
#

and I just need to see what he is doing to create a single gameObject

#

that makes sense

quartz folio
#

Yes, that's how following tutorials works

quartz folio
#

you take what you need from it

#

There will rarely ever be a tutorial that does exactly what you want

winged mortar
#

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

gray mural
winged mortar
gray mural
#

that I know how to implement

winged mortar
#

I think you should have all of the resources, you are now in the hands of god to implement it

gray mural
#

I see

#

thank you all for your help ๐Ÿค” ๐Ÿซก

rancid frost
#

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

winged mortar
#

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?

rancid frost
#

I just did that, no change...

#

wtf

gloomy crag
#

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

rancid frost
#

I would presume since the meshes are coded, this channel is fitting

thin aurora
#

Then you should share your code

rancid frost
#

Under normal circumstances I would, but I dont know which part to share, I am unable to pin point the problem

rancid frost
#

mesh renderer

#

I am using multiple individual mesh renderers

steady moat
#

It is 3d ?

#

Or only fake 3d in 2d ?

rancid frost
#

i would guess fake 3d

#

the hexes are placed along the x and z axis

steady moat
#

So, you render all the white, then all the red ?

rancid frost
#

then the red height is drawn to denote height

steady moat
#

Could you use the frame debbuger ?

rancid frost
#

the red is connected to the white hex, they are thesame mesh

rancid frost
steady moat
#

From what I see, the white is all renderer then you render all the red.

#

Use the frame debugger

#

To analyze the frame.

rancid frost
steady moat
#

The frame debugger

#

That is not the frame debbuger

rancid frost
#

ok will use frame debugger(first time, might be a while)

late lion
#

@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.

steady moat
#

Whatever is the issue, you gonna find it with this tool.

steady moat
#

User said the mesh is generate on the x-z plane.

#

At least, that is what they said.

rancid frost
#

yea, x - z plane, then the red is generated on y plane

#

to create fake 3d

steady moat
#

...

#

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.

rancid frost
steady moat
#

It is on top of it

#

Anyway, you can use the Frame Debugger to understand what I mean.

rancid frost
#

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

steady moat
#

Look at the game view

#

While scrolling in the call

solar current
#

does @everyone know about the shop system

rancid frost
#

damn, you really just pinged everyone?

rancid frost
#

it looks fine here, but the axis are flipped

steady moat
vagrant blade
steady moat
#

One by one.

rancid frost
#

hex checks out in game view

#

frame debugger*

#

its transparent when flipped

short walrus
#

Very nice

#

i guess its the array not the single object

leaden ice
#

yes arrays are not the same as a single object

short walrus
#

yes

#

had to use OverlapCircleAll instead

fervent furnace
#

i believe there should be some overloaded versions which take the array (or list) as out argument and return the length

leaden ice
#

there is

#

not as out argument

#

just a regular argument

#

arrays and lists are reference types so they don't really need out

fervent furnace
#

u are right, array is already reference type, i forgot it

rancid frost
steady moat
#

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.

rancid frost
steady moat
rancid frost
#

as you can see from the video it is rendered

steady moat
rancid frost
#

but whatever this is clearly not working as you said

steady moat
rancid frost
steady moat
#

Like a single pillar that is scaled.

abstract nimbus
#

@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;
        }
winged mortar
#

That does not look right

abstract nimbus
#

it compares each element in sequence with the first and if it's equal it compares the elements with the second

winged mortar
#

Current.ToString() does also not look right

abstract nimbus
#

oh why not?

#

I wasn't able to use .Equals because that compares the reference and I wanna compare values

winged mortar
#

Depending on your type ToString might return some garbage

abstract nimbus
#

oh yeah but in this case it's always a string

winged mortar
#

E.g. list.toString

#

Then dont use a generic

abstract nimbus
#

oh right XD

#

I can just use IEnumerable<string> lol

winged mortar
#

You can constraint the gneeric to always implement IComparable

#

And use that instead

abstract nimbus
#
        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

winged mortar
#

Be sure to test this method btw

#

I don't trusti t

abstract nimbus
#

I do believe this will return true:
1, 2, 3, 4, 5
2, 4

#

but I don't mind that

winged mortar
#

When iterating over the sequence, you advance the subsequence

abstract nimbus
#

yes

winged mortar
#

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

abstract nimbus
#

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

winged mortar
#

yeah but if 4 happened before 2

#

it wont work

fervent furnace
#

4 2 is not a subsequence of 12345

winged mortar
#

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

abstract nimbus
winged mortar
#
  • there is an issue with repeated moves
abstract nimbus
#

maybe the method is named wrong then

winged mortar
#

I mean it depends on how you want it to work tbh

abstract nimbus
#

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

winged mortar
#

Exactly, but if you care about a combination of moves being played

#

when searching for positions

fervent furnace
#

the algorithm looks correct

abstract nimbus
#

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

winged mortar
#

aye

#

glad you got it figured out tho :)

abstract nimbus
#

๐Ÿ™‚

fervent furnace
abstract nimbus
#

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

abstract nimbus
winged mortar
#

Thats correct

abstract nimbus
#

I do get 196 items instead of 116 but I think that's because my previous version didn't allow anything to be between

winged mortar
#

Probably :P

abstract nimbus
#

uh thunder... should I turn off my pc

lethal plank
#

oh dang while true slowly drain RAM

wise arch
#

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?

winged mortar
lethal plank
abstract nimbus
#

๐Ÿค”

winged mortar
rocky jackal
#

why doesnt my Raycast header show up in the unity editor ? There are no compiler errors either

winged mortar
#

From a Start() function on an gameobject that is not tagged with [ExecuteAlways]?

wise arch
winged mortar
wise arch
lethal plank
#

how do i check if 1 variant's value is changed?

cinder pollen
winged mortar
#

I wouldnt rely on values not being null, afaik that code wouldnt run in a build anyway

#

as in, execute always is ignored

wise arch
fleet furnace
winged mortar
cinder pollen
cinder pollen
lethal plank
#

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

rocky jackal
#

buut i still have another problem with this list not showing up in the unity editor

wise arch
cinder pollen
plain nebula
#

am i allowed to ask for help here?

lethal plank
#

yes

wise arch
plain nebula
#

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

tawny elkBOT
#
Posting 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.

plain nebula
rocky jackal
winged mortar
cinder pollen
fleet furnace
wise arch
winged mortar
#

Rather not - playing some other games :P

rocky jackal
winged mortar
#
  • this way others can jump in to help
wise arch
#

Or should I just drop the files that are relevant?

winged mortar
#

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

wise arch
#

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

winged mortar
#

๐Ÿ‘

wise arch
#

GridInventory.AddItem < GridInventory.HandlePlayerInput < GridInventory.Update

lethal plank
#
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?

fathom plank
#

var scopeAndMuzzle = AttachmentType.Scope | AttachmentType.Muzzle; has scope is (scopeAndMuzzle & AttachmentType.Scope) != 0

winged mortar
#

@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

fathom plank
lethal plank
#

it will be long sheet

winged mortar
#

!code

tawny elkBOT
#
Posting 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.

winged mortar
#

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

latent latch
lethal plank
wise arch
lethal plank
#

idk if it worked

latent latch
#

Yeah that looks like it

lethal plank
#

ye i somehow able to google it

winged mortar
rancid frost
winged mortar
#

Just as if you miss a using

wise arch
#

Anyway, that's currently not a problem

winged mortar
#

I think Application.IsPlaying is also editor only

wise arch
#

Gotcha, alright good to know

winged mortar
#

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] pepega

#

Stand by ill take another look at your code

wise arch
wise arch
plain nebula
#

how can i fix this? never happened before

rigid island
winged mortar
#

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

wise arch
winged mortar
#

Honestly the code is super hard to decipher

wise arch
#

My appologies, what part is unclear of what I am trying to do?

winged mortar
#

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?

wise arch
#

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

wise arch
#

So an item can occupy more than one cell

winged mortar
#

Aha, makes sense.

wise arch
#

The owner and reference variables could have better names but I honestly could not think of anything better

obsidian heart
#

please respond as fast as possible

winged mortar
#

And we don't discuss game modding here

obsidian heart
winged mortar
#

I am afraid not sir

#

But I am sure you can find some

broken fractal
#

its a joystick

sleek bough
#

@obsidian heart Not a place for decompile questions.

wise arch
winged mortar
#

Do you always get the same set of errors or did you click multiple times for your screenshot?

wise arch
winged mortar
#

Aha then its probably worth figuring out why it isnt passing your check

#

And then calls it multiple times afterwards

wise arch
#

What gets executed multiple times?

winged mortar
#

Your AddItem function

wise arch
#

Why do you think that?

#

holy shit you are correct

#

what

winged mortar
#

:)

wise arch
#

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 ๐Ÿ˜ข

winged mortar
#

Maybe because it is always updating, it handles your user input right away

#

before it calls start

#

dont quote me on that

wise arch
#

No, the logs are only happening when I actually click

winged mortar
#

Ah okay

wise arch
#

So just hitting play and not touching it is fine and without errors

winged mortar
#

I assume you placed your debug.log in handleplayerinput?

wise arch
#

I did my AddItem func called debug.log as the first line in the add item

winged mortar
#

Aha, well go up the stack and check where its coming from

#

Input.GetMouseButtonDown(0) should work

wise arch
#

It can only come from handle input, just double checked with stack trace. only one reference

winged mortar
#

Do you have multiple instances of this script?

wise arch
#

I was thinking the same, and I am currently double checking but I am fairly certain I have only one instance

winged mortar
#

Try to remove ExecuteAlways Just to see what happens

#

Can always chuck a debug.log in start to see whats going on

wise arch
#

No debug.logs at all

#

so the list again

#

lemme use debugger

winged mortar
#

Remove execute always

wise arch
#

Yeah I did

winged mortar
#

Do you have it attached to atleast 1 gameobject?

wise arch
#

I have

#

And there is only one instance

winged mortar
#

Do the other messages still show up?

#

And your debug.log from start doesnt show up when starting the game?

wise arch
#

Start debug.log gets ran, but anything regarding "errors" of additem is not shown, it just goes to error for the list

winged mortar
#

Okay so remove execute always fixed it from being called multiple times?

wise arch
#

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

winged mortar
#

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

wise arch
#

ah fack ye

winged mortar
#

Then from the loop you set g.ItmeCellReferences to null (but go is equal to mainobj)

wise arch
#

that's dumb of me

winged mortar
#

I dont quite udnerstand what that foreach does anyway

wise arch
#

It works!

winged mortar
#

But that's the problem, and I dont know how to fix it

#

Ah, cool! what did you do?

wise arch
#
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;
        }
winged mortar
#

hahahahhaha

wise arch
#

xD

winged mortar
#

go.itemOwner is now a circular dependency btw

wise arch
#

Yes, that is intentional

winged mortar
#

And you add yourself to yourself aswell

wise arch
#

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

winged mortar
#

I see, well good you got it resolved haha

wise arch
#

ye thanks

#

time for a break lmao

winged mortar
#

I saw this line in the beginning and was like hmmmm this is kind of sus

#

Well deserved one too ;)

wise arch
#

@winged mortarFigured you would like to know, I added execute always back in and it still works ๐Ÿ™Œ

winged mortar
dawn wraith
#

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.

rain minnow
#

as'

carmine carbon
#

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...

leaden ice
rigid island
#

yup def better off using overlapbox or boxcasting

carmine carbon
leaden ice
carmine carbon
true python
#

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? :)

flint island
#

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?

steady moat
steady moat
tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ 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/

true python
swift falcon
#

can any of you help me?

steady moat
steady moat
#

Usually, you have a blend between Idle and Walk.

true python
steady moat
tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ 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/

steady moat
# true python I am

Then you want to smooth the parameter for the blending so the value does not change to fast.

flint island
true python
steady moat
steady moat
#

Essential would be the first to do.

flint island
#

Ok

true python
steady moat
#

You want to play with interruption source and transition length. Also, you can still smooth your parameter.

pure cliff
true python
pure cliff
#

since typically sprites dont have any way to blend and you just wanna hard cut from AnimationA to AnimationB

steady moat
pure cliff
#

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

pure cliff
#

otherwise you pretty much end up with animators that typically look like this for sprite stuff, lol

pure cliff
# steady moat (Or use code)

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

steady moat
#

Simply do the thing inside your own statemachine of your character.

pure cliff
#

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

steady moat
#

It does not look like you are doing that in your Animator.

pure cliff
#

yeah you can see em sorta, the ones that are double long

steady moat
#

The Animator.Play just remove the need for the usage of Parameter in the case of AnyState

#

You can still do the samething

pure cliff
#

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)

steady moat
#

Can you just not rotate the transform ?

pure cliff
#

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

steady moat
#

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)

pure cliff
#

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#

steady moat
noble sun
#

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?

cinder pollen
#

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?

noble sun
#

Thanks

steady moat
cinder pollen
#

Doesn't OnValidate get called when any SerializeField changes?

gray mural
#

almost

#

when it's changd in inspector

#

it can be also public

cinder pollen
#

I was unclear, my bad. That was what I meant.

gray mural
#

without serializeField

cinder pollen
#

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.

gray mural
steady moat
#

You can also create a PropertyDrawer.

#

Which you would do the same as NaughtyAttributes I guess

gray mural
#

just make sure to install them in asset store

steady moat
steady moat
#

I do not think you to have everything from it in theory.

gray mural
#

It's absulutely free and you can redact it how you want

gray mural
#

very useful

steady moat
#

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.

gray mural
#

yes, we also can write our own attributes

gray mural
cinder pollen
carmine carbon
#

So I have line renderer like in first image. Now can i make so that its more like in the second one

latent latch
#

It's just an editor tool. Even if you remove it, your data shouldn't change beyond how you previous serialized it all.

latent latch
wintry crescent
#

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

latent latch
leaden ice
#

also you can just use a loop rather than recursion

wintry crescent
latent latch
#

recursion for cool points though

leaden ice
#

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 ๐Ÿ˜Ž

carmine carbon
wintry crescent
wintry crescent
latent latch
leaden ice
#

it's really not gonna be that slow - it is basically O(heightOfHierarchy)

wintry crescent
carmine carbon
leaden ice
#

who said anything about Update

wintry crescent
leaden ice
#

what does that have to do with Update though?

wintry crescent
#

OnValidate gets called very often sometimes, when edititng values on a component
as often as Update() would be called during runtime

leaden ice
#

GetComponentInParent is fast

#

especially by editor standards

wintry crescent
#

depends how you change the values, for example dragging to change, or using a slider does that

harsh root
#

Can someone explain me why the folder created has a capital S?

leaden ice
wintry crescent
#

and yea, the typo

harsh root
#

OMG I JUST REALISED I MISSTYPED

#

haha

#

I'll try again

#

nope it only breaks with the s added

#

hmmmm

latent latch
#

^ I do that for IDs

harsh root
wintry crescent
latent latch
#

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

whole yew
#

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

topaz plaza
#
[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?

dusk apex
#

You should have an option in the menus to re-import all.

whole yew
#

unless the definition of the function is documented somewhere

trim ferry
#

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

dusk apex
#

You might need to show your lookat implementation if it is important.

modern creek
#

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?

ashen yoke
#

whats the scale of the root canvas

modern creek
#

(looks normal?)

ashen yoke
#

go down the chain look for non 1,1,1

modern creek
#

that's all there is - Canvas and "TitleScreen"

#

titlescreen is where the script resides, and is also correct as far as I can tell:

ashen yoke
#

you have canvas rescaler script

trim ferry
modern creek
ashen yoke
#

what does it do and when

modern creek
#

hm.. lemme investigate, maybe that's it

dusk apex
#

Hmm, scales with screen size.. Would that have any impact?

modern creek
#

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)

dusk apex
#

Hopefully UnityChanFinished

modern creek
#

Lemme try just disabling that component to see what happens

#

Nope, still showing 2560x1540

#

hmmmm

ashen yoke
#

ok

#

lets assume everything is correct and the margin you get is from bounds themselves

modern creek
#

so, interestingly when i just debugline the bounds object, i get "extents" of 1280x770

ashen yoke
#

what is the task at hand

modern creek
#

i'll link to my OP yesterday, standby a sec

ashen yoke
#

bounds are incorrect, generally

#

all bounds from mesh/collider have a shell

#

they arent precise

modern creek
#

โ˜๏ธ

ashen yoke
#

i would try with a group layout first

modern creek
#

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

ashen yoke
#

since the child will have LayoutElement with min width/height set

modern creek
#

LayoutElement..?

ashen yoke
#

built in component

modern creek
#

I see.. Should I get the values from that? I'm not super familiar with all of the RT members tbh

#

googling

ashen yoke
#

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

modern creek
#

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

ashen yoke
#

ive looked at it

#

you want to clamp the size of the inner element

pure cliff
ashen yoke
#

so it behaves as if it was anchored but wont go below certain size

modern creek
#

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

pure cliff
modern creek
#

Oh, I'm not using any layout elements, that's often harder to get things how I want

pure cliff
#

If you just draw a simple example in paint or whatever of how you want the UI subdivided, it's pretty easy

modern creek
#

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)

pure cliff
#

Well what if the width is less than that

modern creek
#

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

#

โ˜๏ธ 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

wintry crescent
#

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?
modern creek
#

the first signature in that document

modern creek
wintry crescent
modern creek
#

!_controler ?

wintry crescent
# modern creek `!_controler` ?

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

pure cliff
#

== null is null check for unity objects

wintry crescent
ashen yoke
wintry crescent
#

and you're supposed to just look at it as a bool

modern creek
modern creek
trim ferry
#

Guys, can i Lerp this?

ashen yoke
#

you can write a method that sets anchors to corners

modern creek
#

Basically I say "ok this object is 100x100 and is in the center of a 760x200 object" and then calculate the anchors by hand

ashen yoke
#

i use it all the time but it comes from now nonexistent on the store asset

modern creek
#

lemme have a look at the source of that if it's available

wintry crescent
dusk apex
modern creek
ashen yoke
#

you can wrap it into a stand alone component

#

all you need is to call update and you get world space data

modern creek
#

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

ashen yoke
#

right, i enforced the canvas to stay in world space

wintry crescent
modern creek
ashen yoke
#

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

modern creek
#

same thing, different application - GetWorldCorners() with some extra shit, basically

modern creek
# wintry crescent that's my problem though. GetComponentInParent returns null, I get an error 1-2 ...

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

ashen yoke
#

!comp should work

#

that is correct way

#

where does the error come from

#

scene object/prefab

wintry crescent
# modern creek Unity serializes references and variables and stuff.. so you're probably better ...

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...

ashen yoke
#

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

trim ferry
#

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

cobalt gyro
#

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

cobalt gyro
trim ferry
#

simultaneously

ashen yoke
#

just instantiate twice

cobalt gyro
#

fr

ashen yoke
#

wrap it into a method

trim ferry
#

how

#

its an variable

#

the thing

ashen yoke
#
private void InstantiateProjectile(GameObject prefab, Vector3 pos, Quaternion rot, float lifetime)
{
    GameObject clone = Instantiate(prefab, pos, rot);
    clone.GetComponent ...
    Destroy(clone, lifetime);
}
trim ferry
#

yeah but i need 1 bullet in each barrel

ashen yoke
#

right so you call it twice

trim ferry
#

will this work

ashen yoke
#

it will but to avoid unnecessary code duping i suggested you wrap it into a method

trim ferry
#

if it works then i will use this

somber nacelle
#

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

modern creek
#

@ashen yoke Using the world space method worked and now I have a rect transform auto-anchor button ๐Ÿ™‚

vagrant blade
#

@trim ferry There's no off topic here

trim ferry
#

sorry

pure cliff
#

blergh, this is a bit annoying that there isnt a built in easy way to convert Vectors in all types

somber nacelle
#

just cast to Vector2, that can be implicitly cast to Vector3

pure cliff
somber nacelle
#

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

weary hollow
#

I haven't used the Input Manager in forever and I have forgotten how to reference it in another script. Does anyone know?

pure cliff
somber nacelle
pure cliff
#

I know what I need to do, I just find it mildly annoying that I have to do it :p

trim ferry
#

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

somber nacelle
#

make sure you add the using directive for that namespace

trim ferry
#

ok

#

thx

modern creek
leaden ice
hasty haven
#

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;
}
modern creek
#

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

hasty haven
#

This whole thing executes in <5ms normally

#

when deep compiler is on it inflates a ton

modern creek
#

deep profiling?

#

yeah that's probably reasonable

hasty haven
modern creek
#

I had success with it in the past in untangling a hairy recursion performance thing

leaden ice
hasty haven
#

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

leaden ice
#

but yeah one easy win here is not to repeat this duplicated calculation coords + Vector3Int.up

#

show more code

somber nacelle
hasty haven
#

This is embarassing code ngl because i am manually typing 6 directions ๐Ÿ˜…

leaden ice
#
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

hasty haven
#

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;
  }
modern creek
hasty haven
#

Sorry for your eyes

leaden ice
#

ok so yeah

hasty haven
#

Rest of the code doesnt look like this

leaden ice
#

off the bat we can cut these additions in half

modern creek
#

slightly embarassing ๐Ÿ™‚ but yes, you can simplify this

leaden ice
#

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

hasty haven
#

Oh yeah I dont know how i didnt see that

leaden ice
#

so you don't have to fix this 6 times lol

hasty haven
#

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

leaden ice
#

also what does GetIndexFromLocalCoordinates do?

modern creek
#

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

hasty haven
#

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

leaden ice
#

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

hasty haven
#

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

ashen yoke
#

@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;
        }
hasty haven
#

Oooo

ashen yoke
#

you can also early out if one of them fails

#

in general

hasty haven
#

What is with the inline function like that, TestPoint

ashen yoke
#

what with it

hasty haven
#

Or are you just putting the implementation in the middle there

ashen yoke
#

its a local method

leaden ice
hasty haven
#

TIL thats a thing, C# isnt my background

leaden ice
#

if there's no early out rn that's a problem

ashen yoke
#

it gets compiled to a static

#

just syntax sugar

modern creek
#

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

leaden ice
#

isBlockExposed needs to either be a ref parameter or this needs to be a local functiion

ashen yoke
#

that allocates a dictionary on each call, dictionary is not necessary since the LUT is finite you can just use array

leaden ice
#

Definitely wouldn't do this though:

#

Dictionary<int, Vector3Int> neighbors = new() { 0 = Vector3Int.up, 1 = Vector3Int.down, ... };

#

super wasteful

ashen yoke
#

in both cases it will be slower than inlined code

modern creek
#

yeah that should be a local readonly dict

leaden ice
#

static readonly Vector3Int directions = new Vector3Int[Vector3.up, Vector3.left, ...etc];

#

it shouldn't be a dict at all

modern creek
#

just to get the point across though in terms of readability/looping

leaden ice
#

array is fine

modern creek
#

well he needs the index to set visibleSides

leaden ice
#

which you get in a for loop

#
for (int i = 0; i < directions.Length; i++) {
  var direction = directions[i];
}```
modern creek
#

ah, fair, although that makes the order of elements in the array important, but.. now we're quibbling ๐Ÿ™‚

leaden ice
#

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

modern creek
#

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

ashen yoke
#

bound checks, type checks, etc

hasty haven
#

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

ashen yoke
#

tho ref hash should just return the ptr

leaden ice
ashen yoke
#

so there should be no hashing at all

#

tho thats not a ref type

hasty haven
#

The reason I want corners is so the blocks can render beveled edges automatically

ashen yoke
#

vectors use spookyhash

#

by default

#

its slower than some impls

#

mines faster ๐Ÿ˜

pure cliff
#

does Physics2D.OverlapPoint not work for UI elements in a Screen Overlay Canvas?

leaden ice
somber nacelle
pure cliff
#

yeh I have a collidor on it

leaden ice
somber nacelle
leaden ice
#

stop now

pure cliff
ashen yoke
#

its not going to work

leaden ice
somber nacelle
leaden ice
#

UI elements live in a totally different coordinate space than physics objects

#

it won't work properly

leaden ice
ashen yoke
#

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

pure cliff
# leaden ice what are you trying to do

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

ashen yoke
#

then maybe you can make it work

somber nacelle
#

use the event system interfaces like IPointerEnterHandler