#archived-code-general

1 messages ยท Page 459 of 1

whole wyvern
#

thank you ill try this

#

if its still not suitable ill try trigger events

fiery steeple
#

Hey, I just finished my minesweeper game and would like to know if someone wants to see my project and give me feedback on it please (mainly the code) ? ๐Ÿ™‚

austere bear
#

i know this isnt the interface channel, but why in the editor my UI looks perfectly normal but in the build it looks like the second photo

#

canvas settings

steady bobcat
#

ui anchors

austere bear
#

im not that great at interface

steady bobcat
#

have a read, they control how rect transforms get positioned when their parent changes size
its a very common mistake and posted here all the time

austere bear
#

better lol

steady bobcat
# austere bear better lol

change the canvas scaler mode to "Scale With Screen Size" then fix your anchors and that should be better
check a few resolutions from the presets in editor as you do this

night harness
#

Might be a kinda donโ€™t ask to ask thing where you might get better feedback either posting a link to a repo entirely or specific files

night harness
fiery steeple
vestal arch
#

ah, i guess that'd make sense here then

night harness
# fiery steeple Here's my code : https://paste.mod.gg/guuzqgfnrsom/0

Just random thoughts/notes. Some of these may not be preferable etc.

  • Highly recommend singleton patterns that find and assign the instance in the getter of the singleton (i can send an example if needed). setting in awake is prone to failure if something tries to access it before it wakes up
  • In OnGameOver just flip the logic homie, (if (win) rather than (if (!win)). The way you have it now just makes it harder to read which is why i assume you needed to comment them
  • This is very much a me thing but i hate the usage of var because it just damages readability, especially outside of an IDE like how I'm reading it
  • Not sure what you think that RestartGame coroutine is doing, that doesn't make the scene loading async or anything. You'd need to use the async version of that function
  • In GenerateMinesLocations i'm pretty sure you can just copy via constructor? eg. new List<Tile>(tiles)
  • It's fine for the scope of this project probably but would be nice if tile type was via enum rather than int for readability purposes (and maybe even a scriptableobject for bigger projects)
  • Personally in GenerateGrid I'm not a fan of how much public access you have in manipulating a Tile. IMO the Tile should be responsible for handling it's colour and value. At the very least if your going to have public ways of manipulating them do it via a function so you can validate the input and potentially react to it. eg. if you had Tile.UpdatePosition(int x, int y) and Tile.UpdateType(int newType) Tile could update it's color in response to those being ran.
  • I'd need more context but those static lists (Tile.minesLocations and Tile.flagsLocations) looks abit weird
  • In StartGame you run OnGameStartEvent before GenerateGrid. From my perspective if i'm listening to OnGameStartEvent I'm assuming the game is ready/setup. You might want a OnBeforeGameStartEvent for whatever that is being used for?
#
  • In ClearGrid, For reasons it's a good habit to explicitly set references to UnityEngine.Object's to null when destroying them.
#

Hope some of these thoughts are helpful in anyway, I won't pretend I'm great at any of this though ๐Ÿ˜„

fiery steeple
# night harness Just random thoughts/notes. Some of these may not be preferable etc. * Highly r...

Thank you for the feedback ๐Ÿ‘ ๐Ÿ™‚

  • Oh that's really smart and I struggled in some projects because of that ๐Ÿ˜ฎ Because also, doing it in the getter would keep doing that check if an Instance is already set each time I call that getter ๐Ÿ˜ฌ
  • I did if(!win) to follow the clause guard principle and return before executing the rest instead of doing if + else statement. Isn't this way, the proper way "pros" do it ?
  • I totally agree, and I had them all being the type instead of var but the IDE added squiggly lines referring me that it's better to make those variable types be var instead of the type itself. What's usually used in pro environement / projects ? ๐Ÿค”
  • Oh yeah, I forgot to remove the Coroutine part because in the beginning I had the coroutine to wait 3 sec before restarting the game so I can see where the mines were ๐Ÿ˜ฌ
  • Just tried and no I can't because tiles is a 2D array while tilesCopy is a 1D array (check picture) and I needed it to be 1D to go through more easily than a 2D array.
  • I totally agree. At first I used enums then I quit that idea for no reason ๐Ÿคฃ How would that work with Scriptable Object in this case or bigger projects ? ๐Ÿค”
  • Yeah that's smart. I will modify that, thanks ๐Ÿ‘
  • Why do they look weird ? 1 is containing all the positions of the mines and the other all the positions where the player placed a flag.
  • Good point ๐Ÿ‘ Funny thing is I don't even use that event anywhere ๐Ÿคฃ Should I remove it ?
  • Oh, using Destroy(gameObject); doesn't set the reference to null by default ? ๐Ÿค” I don't understand the UnityEngine.Object part ๐Ÿค”
dusk apex
# night harness Just random thoughts/notes. Some of these may not be preferable etc. * Highly r...

Personally, I'd prefer not to search the hierarchy unless absolutely necessary. The failure in Awake can be completely negated if you keep the operations of the instance limited to the scope of itself only and instead access other objects in Start. For example: cs private void Awake() { rb = GetComponent<Rigidbody>();//Fine but could probably be assigned in the inspector } private void Start() { gm = GameManager.Instance;//Would always be valid if GM exists }

night harness
night harness
# fiery steeple Thank you for the feedback ๐Ÿ‘ ๐Ÿ™‚ - Oh that's really smart and I struggled in so...

I did if(!win) to follow the cl...
Personally this function and the if/else itself is so small that it's not necessary
I totally agree, and I had them all being the type instead of var but
I cannot attest to preference in industry due to lack of experience
How would that work with Scriptable Object in this case or bigger projects ?
I'm a little bias because of my background in modding but I tend to prefer SO's over enums because enums are static and cannot be added to at runtime. Another massive benefit though is usually for something like a "content" "type" you'll usually have some correlating information (display names, icons, colors etc.) so using scriptableobjects lets you build that information in. This isn't perfect but you could use another scriptableobject to use them like an enum like

public class TileTypes : ScriptableObject

public static TileTypes Instance => /*some public facing reference eg. on a gamemanager*/
public List<TileType> AllTileTypes {get; private set;}
[SerializeField] private normalType;
public static TileType Normal => Instance.normalType;
[SerializeField] private mineType;
public static TileType Mine => Instance.mineType;

then you can use like

if (tile.TileType == TileTypes.Mine)
    etc.
#

Oh, using Destroy(gameObject); doesn't set the reference to null by default ? ๐Ÿค” I don't understand the UnityEngine.Object part
Unity handles object destruction in their own way, You don't need to know tooo much about it but in some occasions where the engine wants to try and clear uneeded memory, a reference to a destroyed object is not the same as a reference to a null object
UnityEngine.Object is the base class for the types affected by this (anything MonoBehaviour, ScriptableObject etc.

#

Why do they look weird ? 1 is containing all the positions of the mines and the other all the positions where the player placed a flag.
Personally just abit odd that no one really "owns" that data nor is it directly connected to all the other data you have setup.

Tile already knows if it's a mine or not so maybe you make a helper function that iterates through the matrix and returns the mines. Or if its never going to change and you wanna be more optimized let the GameManager at the very least own the list instead and (imo) make it a list of Tiles rather than indicies because it's just better information

Same with the flags list where tiles could probably just store if they've been revealed or not

noble herald
#

Trying to make it so left and right can't be activated if the other is activated.... so if left is โœ… then right can never be โœ… until left is โŒ, and vice versa

What currently happens right now is...
Left press -> Right Press = Left โœ… + Right โŒ (What I want)
But...
Right press -> Left Press = Left โœ… + Right โŒ (I don't want this)

        if (leftHitAction.action.IsPressed() && _canHitBool == true && _rightButtonHold == false)
        {
            _leftButtonHold = true;
            Debug.Log("Left Hit");
        }

        if (rightHitAction.action.IsPressed() && _canHitBool == true && _leftButtonHold == false)
        { 
            _rightButtonHold = true;
            Debug.Log("Right Hit");
        }

        if (leftHitAction.action.WasReleasedThisFrame())
        {
            _leftButtonHold = false;
            _leftButtonRelease = true;
        }

        if (rightHitAction.action.WasReleasedThisFrame())
        {
            _rightButtonHold = false;
            _rightButtonRelease = true;
        }
dusk apex
noble herald
#

either way though, if rightHitAction.action.IsPressed should make _rightButtonHold be true.... which means leftHitAction.action.IsPressed shouldn't activate because _rightButtonHold == true?

cosmic rain
#

If both can be true, you'll have to prioritize one or the other.

#

Or handle the case of both being true

noble herald
#

but it can only set it to true if the button is pressed.... and the _canHitBool is true.... and the opposite hit is false

#

if I hit rightHitAction first, that makes it "true" (that part works).... meaning there shouldn't be a way leftHitAction activates here

cosmic rain
#

Then maybe rethink the logic. Honestly, I wouldn't have any conditions for input querying. If the button is pressed, then it's pressed. Regardless of what other buttons are pressed.

#

It's how you handle that input is where you can implement whatever conditions you want.

noble herald
#

I have the logic working in prediction which is fine, but the problem is in the update method as of now (which is what I am showing via my code here)

little meadow
noble herald
# little meadow You may need to show all the code... this seems legit to me. Is there something ...

only other thing I can think of is this.... but the False part is what I have to add according to the CSP docs

    protected override HittingPlayerInput GetInput()
    {
        var input = new HittingPlayerInput()
        {
            leftHit = _leftButtonHold,
            rightHit = _rightButtonHold,
            leftRelease = _leftButtonRelease,
            rightRelease = _rightButtonRelease,
        };

        // Add A False Here
        _leftButtonHold = false;
        _rightButtonHold = false;
        _leftButtonRelease = false;
        _rightButtonRelease = false;
        return input;
    }
harsh rapids
#

why does my player move like 4x faster when i fullscreen when playing in editor

#

;-;

little meadow
little meadow
noble herald
#

but its weird this only happens for Right first then Left second.... but not Left first then Right second.... so I don't think this is a Purrnet issue

little meadow
#

That's just how your logic is. If you have both left and right it goes into left because it's first.

noble herald
#

my old logic I had a left method and a right method.... did it not prioritize left in that case cause it was via a method?

#

cause I dont recall this occurring before me trying to learn prediction logic

little meadow
#

You weren't resetting the values before, I assume

noble herald
#

idk, still weird though cause the left shouldn't even activate if the right bool is active.... and I did a debug log test on that... ๐Ÿ˜ญ

#

if the only bug from this would be left + right at same time (same frame) was it picked left... then who cares very hard to notice.... but this is a problem lol

little meadow
quick token
noble herald
#

or maybe it did...

#

double checking lmao

#

I still dont get why that impacts it but yay? ๐ŸŽŠ

little meadow
little meadow
#

Like... you're setting the bool to true to specifically prevent that... and then you're resetting it to false in something that's probably called about every frame. ๐Ÿ˜„
You see how that's a problem, right?

harsh rapids
#

i fixed it

#

just tinkered around with fixed update

fiery steeple
# night harness > Why do they look weird ? 1 is containing all the positions of the mines and th...

Indeed, Tile knows if it's a mine or not and if it's flagged or not that's why the data is in that class, however to avoid each time looping through all the grid each time I request to know where all the mines are and where all the flags are, each time I set the Value to be a mine or I click to make the Tile a flag, I add it to those static List. When the Tile is no longer flagged, I remove it from that List.

So that way, I don't loop over every Tile in the grid everytime to get this information each time I request it ๐Ÿ™‚

fiery steeple
little meadow
astral orbit
#

Has anyone used the C# dynamic type for anything? Didn't know this thing existed until now. Apparently it leads to spaghetti but I'm curious.

steady bobcat
astral orbit
#

Okay, people said it might be slightly more performant alternative to reflection but yeah

chilly surge
#

It exists pretty much only for COM interop. Don't use it for anything else, everything you do with a dynamic turns into reflection and kills your performance, even if it works.

astral orbit
steady bobcat
#

dont forget unchecked, volatile and __makeref

astral orbit
#

No idea that those existed as well

steady bobcat
#

C# has lots of useful keywords too such as stackalloc, fixed and unsafe that can be used in more "normal" ways

last quarry
worn wing
#

Why is there no TryGetComponentInParent???

vestal arch
#

you'd have to ask unity devs

last quarry
#

It's probably better not to rely on hierarchical relations like that

vestal arch
#

but yeah you could probably use a serialized reference for that

worn wing
#

Yeah i just fixed it like this, but weird that it doesn't exist.

little meadow
#

you can always write it yourself or do a null check

last quarry
#

Oh right, collisions have evil situations like this

fiery steeple
worn wing
vestal arch
worn wing
#

Yes it works! No more hard coding each hit effect into the bullet script XD

vestal arch
#

to avoid the surfacetype juggling

worn wing
#

I had some issues with the bullet destroying itself on hit before the object it hit could even respond.
And i don't wanna attach a script to every wall.

#

So I just made an ImpactManager that can spawn any effect for a given SurfaceType and ImpactType.

#

Now in the bullet script i only need to pass the collision and bullet ImpactType to the manager and it handles the rest.

vestal arch
#

or is there supposed to be a "default" effect when there's no surface info

worn wing
#

Yes each impactType has a default effect. My game is 95% metal surfaces so i just set that effect as the default and only have to add identifiers to the other 5%

vestal arch
#

gotcha

warm parcel
#

is there are way to set an editor-only scripting define that's not on a per-file basis, e.g. MY_DEBUG_FLAG? i want to be able to compile in some debugging features when running in the editor that are generally useful, but compile them out when profiling because they're allocating and really obtrusive in narrowing down the source of real allocations.

hybrid thicket
#

void Update()
{
    float xInput = Input.GetAxisRaw("Horizontal");
    rb.velocity = new Vector2(xInput * speed, rb.velocity.y);

    animator.SetFloat("Moving", xInput);
    animator.SetBool("IsMoving", xInput != 0);

    // only trigger jump flag when pressing Space (and grounded)
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        isGrounded = false;
        animator.SetBool("Jumping", true);

        // jump flip
        if (xInput < 0)
        {
            spriteRenderer.flipX = true;
        }
        else if (xInput > 0)
        {
            spriteRenderer.flipX = false;
        }

    }

    Debug.Log(xInput);

}
#

i cant make flip during jump

vestal arch
#

the code to flip isn't running when you jump

#

it's only running the first frame when the jump is triggered

#

it's not gonna run the rest of the time either

#

that shouldn't be in the jump block

hybrid thicket
#

i made left and right walking animation . if flip happens left walking animation get cursed for prevent this i tried make flip happens only during jump

vestal arch
#

why not 2 separate jump animations for left and right as well?

warm parcel
#

can anyone explain these spikes? my monitor is running at 59.95 hz, so i thought this might be what vsync looks like when not running at true 60hz. however, i was flipping the system refresh rate between a few settings and then back to 59.95, and once in a while afterwards the profiler would show a smooth 60fps.

hybrid thicket
#

first time i see this UI

last quarry
warm parcel
#

this is a build

last quarry
#

It says play mode

warm parcel
#

(but it's not a standalone profiler)

last quarry
#

Youโ€™re profiling play mode in the editor catshrug

warm parcel
#

are you sure that is what that means? that is a toggle between play and edit mode. if i flip it to edit mode, it profiles the editor. right now when i have the editor open, and not playing, the profiler shows nothing. i launch my dev build, and it begins profiling the dev build.

#

i just quit the game again before i took that screenshot, which is why it says "play mode"

warm parcel
last quarry
craggy pivot
#

Anybody know what's causing this error in my terrain mesh generation? Google only showed decade old forum posts, which didn't have a solution.

last quarry
craggy pivot
#

Oh will no vertices do that

#

Ok I'll try preventing that

astral robin
#

Hi ! I'm struggling a bit as to how to update a variable of a Behavior graph's blackboard from code :
don't mind the "GetComponent()" in update(). I was just trying to get it right..
I especially wanted to change the value of the second blackboard in the graph but I don't get it how.. UnityChanFrustrated

vestal arch
#

also what's with the ? at the end

astral robin
#

the "?" was just me expressing that I don't get it .. and the error is : "There is no argument given that corresponds to the required parameter 'newValue' of 'BlackboardVariable.SetObjectValueWithoutNotify(object)'"

vestal arch
#

so do you understand that error

astral robin
#

I don't understand that variable altogether ? as it's only expecting 1 argument of type "object".
even it's defenition is :
public abstract void SetObjectValueWithoutNotify(object newValue);

vestal arch
#

yeah, you're supposed to give it a value

astral robin
#

while you know.. at least I should need to specify the name of the variable and the value I want it to be

vestal arch
#

right now you're telling to set the variable, but not what to set it to

vestal arch
astral robin
vestal arch
#

what exactly is your question here?
how to get a variable reference, or how to set a value to that variable reference?

astral robin
#

my question is how to set the bool variable "InputRun" that live in a behavivor agent. inside a secondary blackboard.

vestal arch
#

and are you stuck on getting the variable, or setting the value?

astral robin
#

both..

#

the only thing I managed to get right seem to be the : agent = GetComponent<BehaviorGraphAgent>();
other than that I have no idea what i'm supposed to do next..

vestal arch
#

have you tried googling it at all

patent cypress
astral robin
left timber
#

Hey everyone,
I'm building a Player Controller using a Finite State Machine (FSM). Would it be acceptable to centralize all input-handling logic in the main State Machine script, rather than distributing it across individual state classes?

Curious about best practices here.

errant flame
#

Hi, i am trying to use messagepack with litenetlib.

I installed necessary packages from Nuget and git.

I am building the server build with IL2CPP, when I send a packet to the server from the editor I get the error:

FormatterNotRegisteredException: Project.Scripts.Network.Packet.TestPacket is not registered in the parser:

There is no problem in my transfer from server to client.

As far as I understand, some links are broken in the build processes with IL2CPP and my estimated package to be parsed.

The doc writes something like code gen stuff but I did not understand how to do it in unity.

IDE : Rider

small schooner
errant flame
#

I just wonder to learn litenetlib for future experiments multiplayer etc . then i searched for serializations i saw proto buff and this message pack they are so fast against json serialization i know i can use json and go ahead but want to learn .

Also i wonder does unity transport support all devices as well as litenetlib and can i do everything that i do in litenetlib ?

small schooner
#

Yes It is support all devices any platform

#

It is also UDP so they litenetlib equal to Unity3d transport

errant flame
#

I just started these communication things litenetlib offsers a reliable unreliable UDP protocol i guess for fast data transmission is unity transport is same thing

#

oh got it

small schooner
#

But actually I had some trouble when I try to use reliable protocol (chat GPT recommended me to use it for the case, I end up with unreliable protocol it worked fine for my case)

errant flame
#

For my case i just want run a physic simulation under a unity server and sync that physic simulation fast as possiable.

I think the problem is not with neither Unity Transport or Litenetlib , main problem is serialization i guess

#

If i use unity transport and do same think with message pack i get again same errors until i use json normal regular serialization

#

I know I'm starting from a difficult point and trying to force something.

But since the simulation I want to do is a bit heavy, I don't want to lose control from the very beginning.

small schooner
#

You can use Unity multiplayer they have higher lvl API that allowing to sync game objects or Entities if ECS

errant flame
#

You are right, I have reviewed most of the higher level network API's , but there is a separate learning process for them.

And for some reason I could not get used to them, I could not learn them quickly :/

small schooner
#

There are Netcode for GameObjects or for Entities and Multiplay for Matchmaker + Lobby they are not very hard to learn

#

but for simple game low lvl API is enough, built my own matchmaking/elo system quite quick after understand how to work with unity transport

heady cedar
#

hey guys, bit of a dumb question but do I need to do anything to reference an objective in an additive scene?

#

say I have a GameManager in a Systems scene that I put ontop of the game scene, can I just slot in references as usual to the manager as if it was in the same scene (in both inspector and code)?

vestal arch
#

not in the inspector, no, but you can via code
but you gotta be a little careful about maintaining the reference across scenes, if the object ever gets unloaded

heady cedar
#

hold on let me pull up my current code

#

my use case for this is I want to completely and temporarily suspend my main level scene (which contains everything atm) and move the player to a smaller but completely separate gameplay area, then move them back

#

so I was thinking I'd just use additive scenes and disable the main one, load the second one, move the player and all the gamemanager and ui stuff

#

my GameManager class is a static instance, it contains references to many other managers like sound, ui, mission, etc. which are all child objects

#

I have various other objects in the scene which reference the instance like this GameManager.Instance.AddEnemy(this);

#

if I move the GameManager out of the game scene and into its own additive scene can I still keepdoing this?

vestal arch
#

well you could, but you'd then have to manage the reference correctly

#

this will be destroyed when the scene unloads, then GameManager would have a dead reference if you don't do anything about it

#

that could lead to NREs afterwards

heady cedar
#

well I was hoping that I could extend this additive scene thingy so that the base scene just disables itself, the new scene loads additively on top (GameManager scene stays), then when the player's done in new scene they go back to base scene

#

so no object gets actually destroyed

spare island
#

Trying to use the unit testing package and I made a tests folder and some tests but I can't reference things in the main assembly for some reason, even though I have it referenced in the test assembly definition

#

oh wait i mightve found the problem

#

yeah no i dont understand this at all, lol.

#

it was my understanding if you make an assembly definition in the root folder it should automatically put all of your scripts into that definition, right?

brazen nest
dawn nebula
#

Any problem with using RectTransforms and LayoutGroups outside of a Canvas?

vestal arch
#

you do end up destroying gameobjects in that process

heady cedar
#

Oh I guess this means that both scenes are just constantly loaded

vestal arch
#

just make stuff link up properly lol

heady cedar
#

Aaaaagh

#

I just wanted a way to hit pause on the base scene ๐Ÿซ 

vagrant blade
#

!ban 1384186123344941157 scam

tawny elkBOT
#

dynoSuccess vera6372bt was banned.

woeful ledge
#

can someone help me with netcode for gameobjects and server/client stuff, i think i know what im doing wrong but I do not know how to fix it

night harness
woeful ledge
#

ty

#

im blind didnt see that

untold gulch
woeful ledge
#

what does that mean?

wanton olive
#

Im use to VS code but ive been told that its unity integration is minimul and VS is fully integrated. Im not sure what that means honestly

#

So with that said. What would be best to use

#

VS or VS code

chilly surge
#

Whichever one that makes you most productive. If you are not sure, try both and see.

wanton olive
#

i should state that i just started using unity. Ive been doing their tutorials for the last few days. But when it came to the scripting i was a little confused because unity had me download VS but in the tutorial the guy is using VS code

#

Ive used VS before but i personally dont like it. Its to clunky if that make sense

chilly surge
#

Sure, personally I use VS Code for a similar reason as well.

wanton olive
#

Ok cool last question. As far as functionality goes i wouldnt have to do some extention work arounds would i if i use vs code for unity ?

chilly surge
#

It's just installing the Unity extension.

#

!ide

tawny elkBOT
chilly surge
#

Follow the guide here.

wanton olive
#

ahhh okay sweet thats what it means by VS is fully integrated right ? This reddit post i seen said VS is better for unity im thinking that might be why.

shadow wagon
#

VSCode I dislike using, as VS feels better
It's totally subjective, your mileage may vary

robust dome
#

keep in mind that Vs is heavy and requires much more space on your local storage

chilly surge
#

You will find a lot of people online saying all sorts of things, the most common thing people say to discredit VS Code is "it's an editor not an IDE." A lot of those people also haven't used VS Code recently to know how much C# extension has improved over time. Evaluate it yourself and see what makes you productive.

#

IDE is a personal tool. Different chefs have their own favorites knives.

wanton olive
#

Thanks for the help! I think im gonna stick with VS code and give it a go with the extension.

twilit scaffold
#

i think for the most part, it is fine. when you get to the point of Debugging though, I do not think VSC can do the same thing. someone else would know better though, as i do not really use VSC anymore

chilly surge
#

VS Code has all the common debugging features stuffs you would expect, breakpoints, step into, step over, view call stack, variables, etc.

twilit scaffold
#

good to know, thanks. i will erase that concern from my 'database' then ๐Ÿ™‚

calm silo
#

Is there any Generics equivalent of the ? from Java in C#? Eg, can I make a class that normally take a generic value and tell it not to care?

chilly surge
#

No, C# generics do exist at runtime unlike in Java where they are erased.

#

You either propagate the generic up further, or do something like class Foo<T> : Foo.

calm silo
#

Crap... oh well

little meadow
#

(But also - Cursor! For the previous IDE discussion. Integration is a bit annoying, but otherwise it's been awesome!)

calm silo
#

So, I cant make a "Map<Type, Delegate<?>" to store callbacks for various types?

chilly surge
chilly surge
calm silo
#

I know its unsafe. But I usually make my own Add which ensures anything I add accepts the type. So yes, Runtime unsafe, reflection unsafe, but otherwise pretty ok

chilly surge
#

Yeah the best you can do is exactly that, to concentrate the unsafeness into implementation and expose only the safe public API.

#

But otherwise it's not any different, just store Dictionary<Type, object> or something, and then cast the retrieved value to Action<T> or whatever.

#

The good thing about C# is that the cast will be checked at runtime and throw if it doesn't match.

calm silo
#

You'd get a sort of class cast exception or no such method exception in java on runtime anyway. Somewhere you'll get errors if you do not properly code anyhow ๐Ÿ˜„

#

But the fact I can do typeof(T) in C# is a blessing โค๏ธ

chilly surge
#

I don't really write Java, but I'm under the impression that the cast wouldn't fail since generics are erased. It would only fail when you try to call it with the wrong argument type, which can happen much later on and makes tracking down the error a lot harder.

tawdry kite
#

has there anyone who made jumping system by only script

#

bc i cant make my vertical collisions like rigidbodies

#

there is always a little space between collision and my player

#

if i put a low value as a distance the cast doesnt work

dim cairn
#

Why not use animations?

tawdry kite
#

Why should i try to close that distance by other things

#

isnt it possible to make collisions by script

dim cairn
#

Why not use colliders

tawdry kite
#

i used to make them by myself at gamemaker

#

And at the tutorials i've watched

#

he did collisions by script

dim cairn
#

You could do that... or you could click a few buttons

tawdry kite
#

But he didnt make any jump mechanic

#

No vertical collisions too

dim cairn
tawdry kite
#

3d

dim cairn
#

Somewhere along the lines of adding force along whatever axis you're using as up and then multiplying by time.fixeddeltatime

tawdry kite
#

You mean rigidbody force by force?

dim cairn
#

MyRigidbody.velocity

dim cairn
tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

calm silo
#

Is there any "difference" between a const and static readonly?

small schooner
#

static u can call class.StaticVariable you cannot call const like this it is just wroks like variable

dusk apex
hasty mural
#

hey, question !
I have a minimap in my MULTIPLAYER game.

On the host everything is generated fine, the minimap, the player markers for everyone connected and generated marker.

but for other people than the host everything is generated (playermarker, other markers) and everything is updated but the minimap is jsut invisible, its just floating markers. is this a camera issue? the camera is generated by the script aswell. the entire code is 600 lines long idk if i should paste it in here

sharp garden
#

is there a way to 'terminate' a branch in the Behaviour package?
I want the Repeat While to only execute the node group immediately below it (the Passively Check node sets the relevant variable so it can break out of the loop) but it executes everything past that as can be seen in the image

#

the documentation doesn't cover the exact definition of 'branch' so I'm not 100% sure what does and doesn't qualify as one

#

(sorry if this is the wrong place to put this)

modern dew
#

why the hell is this an error

#

why is tmpro a different type bruh ๐Ÿ˜ญ

somber nacelle
#

TMP_Text is not a string, it has a text property that is a string though. TMP_Text is the actual component

naive swallow
modern dew
#

wish they could make them the same type :/

naive swallow
#

string isn't a component

#

You can't put a string on a game object

#

A line of text in a book is not the same thing as a library building

robust dome
modern dew
#

I already fixed it lol

#

I donโ€™t have any problems rn

steady bobcat
#

the old "i forgot to put .text"

sudden lantern
#

Hi, Iโ€™m completely stuck. I have a PageController class that manages a stack of UI windows - opening them, closing them one after another, etc. Thereโ€™s also a PauseHandler class that handles pausing: it plays the canvas fadeโ€‘in animation and pauses the game. Hereโ€™s the problem: when I press the button to close the current window and return to the previous one, if thereโ€™s a second window on the stack (for example, I went from the main window into the settings menu), closing that settings window also unpauses the game. Thatโ€™s because I only allow unpausing on the main window, and shutting the current window fires both the close event and the pause event at once, so they coincide and unpause the game. With a gamepad thereโ€™s no issue, since โ€œBackโ€ is a separate button, but on keyboard both close and pause are triggered by Escape. The only workaround Iโ€™ve found is subscribing to the pause event before the close event, but that feels like a hack and has other pitfalls. Whatโ€™s a cleaner way to solve this?

PageController: https://pastebin.com/fKRcF5QT
PauseHandler: https://pastebin.com/P9q86VYa

stray fjord
#

How to disable mouse control? I really just want it to not have input, like affecting which button is currently selected or beig hovered over or anything like that.

quick token
#

with the new or old input system? with the new one I'm pretty sure you can just call DisableDevice or something. with the old one you might just have to use a bool

stray fjord
#

Thanks for response. Using the new system I believe. But you got me on the right path I hadn't looked at my eventsystem which has inspector fields that let me easily disable clicking and pointing pikachuface Easy

calm silo
#

Did I forget something?
m_OnClick.Invoke(position);gets executed, but it does not invoke the associated member function cause a "List.count" is 0,

    public class Clickable : UIBehaviour, IPointerClickHandler {
        
        
        [Serializable]
        public class ClickedEvent : UnityEvent<Vector2> {}
        
        // Event delegates triggered on click.
        [SerializeField]
        private ClickedEvent m_OnClick = new();
        
        protected Clickable()
        {}
        
        public void OnPointerClick(PointerEventData eventData) {
            if (eventData.button != PointerEventData.InputButton.Left)
                return;

            Press(eventData.position);
        }
        
        [Tooltip("Can the this be interacted with?")]
        [SerializeField]
        private bool m_Interactable = true;
        
        public virtual bool IsInteractable()
        {
            return m_Interactable;
        }
        
        private void Press(Vector2 position)
        {
            if (!IsActive() || !IsInteractable())
                return;

            UISystemProfilerApi.AddMarker("Clickable.onClick", this);
            m_OnClick.Invoke(position);
        }
    }
steady bobcat
#

you dont need to do public class ClickedEvent : UnityEvent<Vector2> {} anymore you can just use the generic version directly

#

your question doesnt make sense though, if the event is called whats the issue here?

#

Ideally you will use a debugger to see what is actually happening post click event

calm silo
#

OnDataAreaClicked is not called, despite m_OnClick being invoked. Thats my issue. Havn't had any luck tracking it with the debugger yet. Working on it

#

Oh well, I'll dig around more :3

steady bobcat
#

If you have a breakpoint on the UnityEvent Invoke() call you can step into it and see where it goes (hopefully)

#

verify the subscription is still valid in inspector during play mode OR subscribe in code and ditch UnityEvent (for public event Action<Vector2> OnClick)

calm silo
#

Oh, now it works. :3

merry forge
#

is there any way to run code immediately after the Start() step?

rigid island
merry forge
#

during Start(), all my actors (character, buttons, doors, boxes) call a function in the grid system to register themselves. I need the grid system to be able to run some code once all the actors in the level are registered

#

basically setting up the level, e.g. telling doors to update their state depending on whether the linked button has an actor on it

naive swallow
#

Could put it in update and then in that function set a Boolean to skip over it in the future

merry forge
#

good idea

night harness
merry forge
night harness
#

well the actors could initially tell the central manager via singleton on awake or the start of start?

dawn nebula
#

I've never seen this callback in my life, and there's no documentation on it.

#

Is this thing safe to use?

dawn nebula
#

Doesn't even seem to execute at some strange time.

#

You just make a change to the transform and boom it's called.

empty elm
#

In ProjectSettings/Player/Resolution and Presentation, what settings should I use if I want the game to always have 16:9 ratio, but be fullscreen?
Currently I'm using Exclusive Fullscreen and setting default width and height to 1920x1080, but the documentation says the default width and height are only applicable to Windowed mode? The documentation also says Exclusive Fullscreen is exlusive to windows, but when I tried on mac it worked and had the intended effect.

wanton olive
#

hey could i have somebody please help me with getting visual studio code setup so i can use it. I did what the tutorial told me to do with visual studio but say for example if i go to type "OnTriggerEnter" and press tab it does populate the script with private void OnTriggerEnter(Collider other)

wanton olive
#

Nvm good'ol youtube helped me out!

soft shard
#

Is there a way to check if a reference is missing (specifically, if you set a reference, then delete the object without explicitly setting the reference to null in the inspector, it will display "missing") compared to if it is null? I only need this to work in the editor so if theres some editor API or reflection thats fine (although id prefer to avoid reflection) - what I could find online suggested (object)asset) != null && asset == null (where "asset" here is a UnityEngine.Object), but this still seems to log true when the reference is "missing" or null - the reason I want to do this is so I can know if an asset was deleted outside of the project after Unity recompiles and I can then look for its original path

little meadow
soft shard
quartz folio
#

If it's not assigned in the editor then it's still Unity Null

little meadow
quartz folio
#

Random note that GetInstanceID will be removed in a later version of unity and replaced with EntityID, which will have an index and version, so that hack will have to change ๐Ÿ˜…

#

Maybe the logic will be similar, who knows

soft shard
#

Interesting change, huh

little meadow
#

Eh, you can't future-proof it all ๐Ÿ˜„ If it's for your own project - it'll be mostly fine. If it's for an asset - meh. ๐Ÿ˜„ You could get .name and catch the exception and see what case you're on, but that's a lot more performance heavy and I'd not do. Also, who knows when will they decide to change .name to be something else ๐Ÿ˜›

#

(And of course you could do #if UNITY_VERSION_BLABLABLA to handle the different cases when need be)

soft shard
#

Lol true, though that is interesting - atm its just for my own projects maybe at some point ill make a asset version if it all works out, good ideas as well - thanks for the insight from both of you ๐Ÿ™‚

fiery steeple
#

!code

tawny elkBOT
stoic dagger
#

Im having a problem, I need to install barracuda for this script

using UnityEngine;
using Unity.Barracuda;
using Unity.MLAgents;
using Unity.MLAgents.Policies;

[RequireComponent(typeof(BehaviorParameters))]
public class AssignModel : MonoBehaviour
{
    public NNModel modelToAssign;

    private BehaviorParameters behaviorParams;

    void Start()
    {
        behaviorParams = GetComponent<BehaviorParameters>();
        behaviorParams.Model = modelToAssign;

    }
}

But if I do that it gives me 999+ compilation errors

earnest gazelle
#

It is really annoying. When unloading the scene, I face this error, it is about navmesh agent, "Stop" can only be called on an active agent that has been placed on a NavMesh.
I know the problem, it is because the ground is destroyed before the navmesh agents
The solution is that I disable navmesh agents before unloading the scene but it is messy and awkward

icy quartz
#

Looking for a good tutorial that will show how to use replace the Unity 3rd party starter asset character with a mixamo character

soft shard
# icy quartz Looking for a good tutorial that will show how to use replace the Unity 3rd part...

Maybe looking up how to import a Mixamo character in Unity should give you the knowledge needed to replace the starter character with your package - usually the actual mesh is a child that you can replace, then the animations are linked through the Animator which takes an Avatar (which links the bones of the mesh to the Animator so the states know how to manipulate them), the hardest part would likely be with setting up the import settings, which most tutorials should also show

clever lotus
#

Is this a good channel to ask for issues with Colliders and Raycast Hit registering in Unity2D??

vestal arch
#

if it isn't, we'll redirect you

#

the answer is probably yes, but we can't answer for sure until we actually see the question lol

clever lotus
#

Sorry, alright I'll ask:
I am very new to Unity2D this is my first project. I am trying to make a Balloon Tapping Game and everything is working okay except upon clicking sometimes the Shapes are not registering the click and instead it is passing through and the background is registering the mouse click. I am using RaycastHit to identify colliders to work it out but I cannot understand how to stop the Raycast passing through objects.

wide dock
#

Show the relevant code and how the 'balloons' are set up

#

Also send the video in a correct format.

clever lotus
#

This is the issue where the 'Balloons' or the shapes need to be deleted upon clicking but sometimes randomly the clicks are passing through and the background is registering the click and taking the damage (see the final part where I am trying to click on the yellow square but instead of it getting deleted the health keeps dropping)

#

As for the code I have a Monobehaviour class that is spawning the different shapes of 'balloons':

clever lotus
#

And the individual balloon behaviours are their own different Component Codes. This is for the Triangle one that teleports:

public class PokaBehaviour : MonoBehaviour
{

    public Vector2 minx, maxx;
    public Vector2 miny, maxy;
    // this basically makes a box
    public float timegap; // teleportation time gap
    float timeholder; // just a timer
    Transform gameObj;

    void Start()
    {
        gameObj = GetComponent<Transform>();
    }


    void Update()
    {

        if (timeholder <= 0) // time to teleport!
        {
            Vector3 newPosition = new Vector3(

            Random.Range(minx.x, maxx.x),
            Random.Range(miny.y, maxy.y),
            gameObj.position.z
            );

            gameObj.position = newPosition;

            timeholder = timegap;
        }
        else
        {
            timeholder -= Time.deltaTime; 
        }
    }
}```
vestal arch
#

!code

tawny elkBOT
kind pagoda
#

hey anybody knows how to make a simple map? It can be just a flat space with some blocks which i'll turn into buildings later

#

do I have to create a scene?

vestal arch
#

please don't crosspost

kind pagoda
vestal arch
#

in a single relevant place

kind pagoda
#

cry about it

#

you aint a main character buddy

#

i was just asking

vestal arch
#

neither are you - it's a common courtesy to not spam

clever lotus
clever lotus
clever lotus
clever lotus
#

Why are the Raycasts passing through objects?

ashen remnant
#
using System.Collections;
using UnityEngine;

public class Meteors : MonoBehaviour
{
    public GameObject[] Asteroids;
    private int currentAsteroid;
    public Sprite[] brokenAsteroidone;
    public bool halfGame;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        for (int i = 0; i < Asteroids.Length; i++)
        {
            float randomZ = Random.Range(0f, 360f);
            Asteroids[i].transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, randomZ);            
        }
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    IEnumerator ChangeSprites()
    {
        if (halfGame)
        {
            for(int i = 0;i < Asteroids.Length; i++)
            {
                int chosenSprite = Random.Range(0, brokenAsteroidone.Length);
                Asteroids[i].GetComponent<SpriteRenderer>().sprite = brokenAsteroidone[chosenSprite];
            }
        }
    }
}

I want to run a method outside of Update, so I tried using a coroutine, but you need to return in a coroutine. So where should I put 'return' in the "ChangeSprite" coroutine? Thanks

vestal arch
ashen remnant
vestal arch
#

this feels like an x/y problem
what problem are you trying to solve with making the coroutine

ashen remnant
#

now im trying to wonder how to run a method outside of update or run a method but not every frame

#

my bad if its a dumb question im still not super advanced in coding

vestal arch
ashen remnant
vestal arch
#

and you only want it to change on that specific event?

ashen remnant
#

yes

vestal arch
#

so why not have that event also trigger the sprite change, rather than checking the sprite every time

#

instead of having the halfGame be public, make it a property or use a method that also triggers changing the sprites when halfGame is set to true

ashen remnant
#

i see

#

ill try

worldly stirrup
gaunt mural
#

Hi, I'd need some help from somebody who understands how rigidbodies work. I have made a game for my friends based on a real TV show, where you have to hit the bottom block off from a tower with a hammer without the above ones falling down. In the real show, these blocks have weight, and if the bottom one gets hit, the blocks above it dont fly upwards, or act like if they have no or little weight. They barely move. I have set their weight in Unity to a big number..but still. Any help is appreciated!

vestal arch
#

you'd probably want to also reduce friction and/or increase damping

vale walrus
#

You have gravity, mass, drag, friction, and force of the hammer hit to play with... it is not easy.

gaunt mural
#

Oh okay, I'll check those out, thanks

hidden compass
#

also make sure ur moving the hammer using physic forces..

#

then its ur just finetuning all that was said earlier..

#

drag, friction (physics materials) all that stuff

minor oak
#

Hello I'm having some trouble getting my UI to display properly. I'm trying to create the following

Outer (VerticalLayoutGroup)
|- Inner (HorizontalLayoutGroup) Should forcibly fill all of the width in outer and be max(min height, content height) tall
   |- NameContainer (LayoutComponent) Should be 1/3 of the width of Inner
   |  |- Name (Text) Should be left aligned
   |- Value Containuer (LayoutComponent) Should be 2/3 of the width of Inner
      |- Value (GameObject) Should be aligned in ValueContainer and potentially cause everything to stretch to fit if needed

Currently I'm just trying to get Inner and the containers to properly display.
Outer has outer.childAlignment = TextAnchor.UpperCenter; and displays just fine if I child game objects to it correctly
However, I tried to do the following for inner (please ignore not explicitly getting components in my pseudocode)

inner.transform.SetParent(outer.transform, false)
inner.anchorMin = new Vector2(0,1)
inner.anchorMax = new Vector2(1,1)
inner.anchoredPosition = Vector2.zero
inner.childControlWidth = false;
inner.childForceExpandHeight = inner.childForceExpandWidth = inner.childControlHeight = true;
NameContainer.transform.SetParent(inner.transform, false);
NameContainer.flexibleWidth = 1;
ValueContainer.transform.SetParent(inner.transform, false);
ValueContainer.flexibleWidth = 2;

When I do that I get the attached image (the light grey is outer, the green is NameContainer, and the blue is ValueContainer and even though you can't see it both squares are sizeDelta = 100, 100)
When I inspect I see that inner has both anchormin and anchormax = new Vector(0, 1) and is anchored right.

  1. Why is this happening? What's causing it to override the anchors I gave it?
  2. How do I avoid it
icy quartz
#

I am working on an Endless Runner. For a new game I want to give the user the ability to choose a charactgr. I will have 4 Mixamo characters, 2 males and 2 females they can choose from. So I am guessing I am going to create something called like ThePlayer. I will set it up to use a default mixamo character. but if they choose a different character to use, I am guessing I am going to assign a different prefab to ThePlayer. All the animations will be the same so the only difference is the look of the character. Am I on the right track?

steady bobcat
vestal arch
minor oak
#

thank you both i'll give that a go in just a minute. I didn't realize that i needed to be explicit on that to get it to fill

steady bobcat
#

layout groups, images and text provide preferred width so you want to override it to make only flexible sizing be used

spare island
#

Does it work to have a static class with a UnityEvent or does that have the same problems as using a base C# event?

spare island
steady bobcat
#

same problems? what problems?

#

If you subscribe and unsubscribe correctly there are no problems (e.g. when the monobehaviour is destroyed)

spare island
steady bobcat
spare island
#

this one

#

I'm trying to do the scriptableobject thing

#

Where you have your events be in a scriptableobject so they're decoupled

#

I'm not getting any errors but when the event gets invoked nothing happens and it says it has no listeners

#

but its still the same instance ID?

#

I don't understand.

steady bobcat
#

remember that serialized event subscriptions are NOT the same as runtime subscriptions

spare island
#

Nor do I know how to debug it

steady bobcat
#

How do you subscribe to the events?

spare island
#

I don't need it to be serialized

steady bobcat
#

UnityEvent can do both but otherwise just use event

spare island
#

I tried UnityEvent too, didn't work

steady bobcat
#

e.g. public event Action MyCoolEvent;

spare island
# steady bobcat How do you subscribe to the events?
        public static void Bind(string eventID, Action action)
        {
            var gameEvent = Resources.Load<GameEvent>(eventID);
            if (gameEvent == null)
            {
                Debug.LogError($"GameEvent with ID {eventID} not found.");
                return;
            }
            gameEvent._onInvoke += action;
            Debug.Log($"Action bound to '{eventID}' " +
                      $"({gameEvent._onInvoke?.GetInvocationList().Length ?? 0} listeners) " +
                      $"(ID: {gameEvent.GetInstanceID()})");
        }
#

also, the "2 listeners" is unexpected

#

There shouldn't be 2 listeners

steady bobcat
#

put a breakpoint to check the event before subscription. it should be null when it has no subscribers

spare island
#

It is null

steady bobcat
#

this looks normal though so its probably user error

spare island
#

I had to add a ?

#

otherwise it would throw

spare island
steady bobcat
#

Its managed code it cannot change in regards to a scene

#

unless you unsub or set the event to null elsewhere it will not be mutated by unity scene changes

spare island
#

So the listeners shouldn't be disappearing at all, right?

#

especially because its a C# event, not a UnityEvent

#

I dont expect the listeners to clear

steady bobcat
#

Oh it could be the GameEvent instance was GC'd so each time you are "loading" a new instance...

#

because its just a managed class instance

spare island
steady bobcat
#

you would need to load and keep it somewhere to get again later (e.g. dictionary)

spare island
#

So I see the GameManager initializes, it reloads the scene so it can put the game into the correct state (for the editor), then the game starts

steady bobcat
#

read what i said above

spare island
#

I will make a dictionary

steady bobcat
#

so something like:

if(!events.TryGetValue(eventId, out var gameEvent))
{
   gameEvent = Resources.Load<GameEvent>(eventID);
    events.Add(eventId, gameEvent);
}
gameEvent._onInvoke += action;
spare island
#

yep thats exactly what i typed

steady bobcat
#

But anyway this makes the use of a scriptable object pointless

#

could just be an Action or whatever created when first used

#

unless the SO has extra data required

spare island
#

I kind of forgot why its a SO

steady bobcat
#

rando yt tutorial?

spare island
#

No I'm way past tutorial days

#

I've just never quite grasped how events work in unity

steady bobcat
#

Dont think about unity, think about c#

#

its gonna work the same, its managed code that follows the same rules

#

just has some funny stuff relating to == null on unity classes for assets/game objects

spare island
#

I think the reason I wanted to use an SO is because I thought UnityEvent automatically removes dead references, doesn't it?

#

I don't remember what the SO part was for, other than holding the UnityEvent

steady bobcat
#

the inspector made ones may do this because its all reflection based

#

otherwise code subs wont unless there are checks to specifically check the .target of the original subscriber

gaunt mural
# hidden compass

Hey! Thank you very much for your help :) Would it be possible to ask for the unity file you made? I am not an expert really and being able to see the code indirectly would help me out a lot. EDIT: FIXED IT, THANK YOU SO MUCH!!!!!

steady bobcat
#

(perhaps your system can provide a UnityEngine.Object for lifetime checks?)

spare island
#

The problem with C# events is that they don't go away when you stop playing in the editor by default

#

so you get a memory leak

#

also applies in the game, too

steady bobcat
#

a domain reload will happen eventually so thats not that bad
but you can use events to know when play mode ends

#

And during gameplay its YOUR job to unsub things that should not be subscribed anymore

spare island
#

well the usual fix for that is to use on OnDestroy or OnDisable

steady bobcat
#

for a fully static class you can use the init on load things + events to know when playmode ends to clean the events

spare island
#

Ah right in a static class

steady bobcat
#

anyway this is all stuff you can do but you just have to do it correctly
If you want it to be automatic and cool then it needs that functionality to be added

spare island
#

It felt stinky to just drop an event in my GameManager and be like "ok now everybody go ask the gamemanager to subscribe to this"

#

but honestly whatever for now

spare island
#

Pain...

#

I wanted to be able to drag in game events into a component so I can set up what happens on an event in the inspector

ocean hollow
#

<@&502884371011731486> off topic / potential scam

rugged granite
#

Hi everyone!

I got an error trying to automatically upload my .ipa to TestFlight through Post-build script (Unity Cloud Build (Build Automation)):

  โ€œFailed to generate JWT token: ErrorDomain=NSCocoaErrorDomain Code=-43
   โ€˜Failed to load AuthKey file.โ€™
   The file โ€˜AuthKey_<YOUR_API_KEY>.p8โ€™ could not be found in:
     โ€ข /BUILD_PATH/.../private_keys
     โ€ข ~/private_keys
     โ€ข ~/.private_keys
     โ€ข ~/.appstoreconnect/private_keysโ€```

In post-build.bash I tried the following two options but both don't work:
1 option:
```KEY_WITH_NEWLINES=$(echo $CONNECT_API_KEY | jq '.private_key |= sub(" (?!PRIVATE|KEY)"; "\n"; "g")' -c -j)
echo $KEY_WITH_NEWLINES > ~/.appstoreconnect/private_keys/AuthKey_${API_KEY_ID}.p8```
2 option:
```mkdir -p ~/.appstoreconnect/private_keys
echo "$CONNECT_API_KEY" | jq -r '.private_key' > ~/.appstoreconnect/private_keys/AuthKey_${API_KEY_ID}.p8```

In Unity Cloud Build (Build Automation) โ†’ Advanced Options โ†’ Environment Variables โ†’ Variable value for CONNECT_API_KEY I indicate in the following format:
```{"private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----"}```

Please tell me how to fix the error? Is it wrong in my code in post-build.bash or the input format Variable value for CONNECT_API_KEY?
hexed bough
#

with unity 6.1 the editor im unable to get the editor layout as it was for facebook sdk

what has to be changed ?

#

it has to be something like this

#

same for game analytics as well
there's no login button

steady bobcat
#

ongui should still work so must somehow be broken by some editor gui change

hexed bough
#

what can be done as of now?
is it because of editor?

steady bobcat
harsh rapids
#

why is this happening

leaden ice
modern creek
#

I restarted my computer yesterday and this morning, Unity Hub is uninstalled.. What could have caused that? I can just reinstall it obviously but I'm confused

hybrid thicket
vestal arch
#

you should generally just not use genai for that kind of stuff

hybrid thicket
vestal arch
#

i read your message, that doesn't change my answer

naive swallow
eternal sierra
#

hello, i want to have a variable that can be used by other script but not inspector tied is :
private int money = 10;
public int GetMoney() => money;

the best solution ?

vestal arch
#

there's no best solution, there are several solutions

somber nacelle
#

use a property not a method to expose it to other objects, it's basically exactly the same, but remove the () and you can treat it like a readonly variable in other objects

vestal arch
#

the typical approach would probably be public int money { get; private set; } = 10;

#

you could also (for example) use NonSerialized/HideInInspector on a public field

somber nacelle
#

note that HideInInspector does not prevent it from being serialized, you'd want to use NonSerialized for that

vestal arch
#

ah, whoops

eternal sierra
#

it seems like public int money { get; private set; } = 10 is what i'm gonna use, i don't rly like having a getter

somber nacelle
#

i don't rly like having a getter
do you perhaps mean you don't like having an explicit getter method? because your auto property does have a getter, it's an implicitly generated getter method because that's what properties are

eternal sierra
somber nacelle
#

That's what having an explicit backing field is and even with properties there might come a time where you would need an explicit backing field (for example if you need to add logic to your getter or setter you must use an explicit backing field)

eternal sierra
somber nacelle
#

because it is serialized

eternal sierra
#

what is the workaround for that ? I still want to change the hp in the scene but i want the prefab to follow the script

somber nacelle
#

reset the component and it will go back to its default values

eternal sierra
somber nacelle
#

no, that's the whole point of serialization. whatever value is set in the inspector is applied when the object is created at runtime. the value in the inspector doesn't change just because you change the code because it has already been serialized.

eternal sierra
#

it's a prefab ofc the script should matter more that the inspector it seems logic to me no ? Is there no shortcut to like reset every prefab or idk

#

but i didn't put anything in the inspector tho

#

" i didn't even touch it i thought it was when modified manually then the inspector become the reference"

somber nacelle
#

you set the value when you first created the component with a serialized field

#

just because you didn't manually assign a value doesn't mean it didn't serialize the existing value

vestal arch
#

the value assigned in the script is just the default when you create a new component
it doesn't automatically change every existing instance of the component

eternal sierra
#

So there is no way to force the variable to follow the script at the start of the scene but to still access it in play mode ?

somber nacelle
#

you could just not serialize it

vestal arch
#

something like maxHP you probably do want to serialize though

eternal sierra
vestal arch
#

that would make it useless as a property then lol

somber nacelle
#

why do you need to access it in the inspector if you don't plan to change it outside of play mode

vestal arch
#

everything would have the same max hp

#

it feels like you're trying to solve a problem that doesn't exist here tbh thonk

eternal sierra
eternal sierra
#

i'm plrobably creating an inexisting issue

somber nacelle
#

yeah you're just writing yourself into a corner with this line of thinking

eternal sierra
#

but i like modifying the hp while in play mode but still want the script to work x)

vestal arch
#

hp should be separate from maxhp though

#

hp doesn't need to be serialized unless you need it to start at a specific point

worldly stirrup
#

So, I removed the code to create the procedural walking animation, and instead made it so the legs would instantly move to their new points (the points that the red curved raycasts hit, marked by the green rays) and discovered that the issue of the leg animation not being the same, with one of the legs being streched fully isn't a result of the animation code, but an inherent issue. Any help?

eternal sierra
young yacht
#

do you guys use unity cloud to store your repos?

young yacht
#

@rigid island does it save binaries well?

#

3d meshes

rigid island
# young yacht <@968604165150507078> does it save binaries well?

it saves whatever you want it to save. the limit per file is 100mb I think? then there is LFS for bigger size per file.. Sure 3D meshes though I don't recommend storing big art asset files , If they are big and barely ever change I store them in a cloud service like google drive that gives more space for free/cheap

eternal sierra
full pawn
#

I'd like to make camera animation from weapon animation I have. There's camera_bone. This code is just locking camera and rotate it full, but I'd like that it only "affect" to main camera and player can control his camera

private void HandleCameraAnimation()
    {
        if (_holder is ICameraHolder cameraHolder)
        {
            Quaternion currentBaseRotation = cameraHolder.GetBaseCameraRotation();
            Quaternion animRotation = _cameraBoneTransform.rotation;
        
            Vector3 animEuler = Quaternion.Inverse(animRotation).eulerAngles;
        
            animEuler = new Vector3(
                NormalizeAngle(animEuler.x),
                NormalizeAngle(animEuler.y),
                NormalizeAngle(animEuler.z)
            );
        
            Quaternion effectRotation = Quaternion.Euler(animEuler);
        
            _playerCameraTransform.rotation = currentBaseRotation * effectRotation;
        }
    }
vestal arch
tame silo
#

I have a weird bug, I have a Sprite array added to a script that is added to a GO. it worked fine for a few weeks, it contained 4 sprites just set in the inspector (first element being null). but now when I want to add 2 new sprites to that list, the editor only remembers that the array size increased to 6, not the references to 2 new sprites.

the scene file doesn't change, so the change is not persistent. if I hit play, the newly assigned sprites disappear, (but the first 4 references are fine, it's just the last 2 become null). I can change references to the first 4 elements just fine, it's just everything after the 4th disappears and becomes null on play

I will try to debug tomorrow and try more things, but maybe someone saw this already? is this a known bug? I'm using Unity 6000.0.43f1

small schooner
#

You may set the list size somewhere in script, or initialize the list inside script

cunning python
#

can anyone help me code a throwing baseball system with a glove that can catch it without closing your hand in vr

quick token
shell scarab
#

Why can I not make playmode tests? in either of these folders with these assembly definitions?

#

this is in an embedded package, which i see is supposed to work with the test runner?

quartz folio
shell scarab
#

Is my test defined correctly to be recognized?

[UnityTest]
        public IEnumerator PlayerInputSource_SouthWest()
        {
            PressDirectionalKeys(Key.S, Key.A);
            yield return WaitForSmoothDamp();
            AssertDirection(-1, -1);
            ReleaseDirectionalKeys(Key.S, Key.A);
        }
```Inside a class that extends `InputTestFixture`
quartz folio
#

Does the test fixture have [RequiresPlayMode] on it?

shell scarab
#

it seems that attribute does not exist in the version I'm on, which is test framework 1.5.1

quartz folio
#

Not sure, I'd restart Unity if you've not tried it yet

shell scarab
#

when I create a test assembly and a test script it looks like this and is recognized inside of the embedded package:

 [UnityTest]
    public IEnumerator NewTestScriptWithEnumeratorPasses()
    {
        // Use the Assert class to test conditions.
        // Use yield to skip a frame.
        yield return null;
    }
#

is it because the class my test is in extends from InputTestFixture?

shell scarab
quartz folio
shell scarab
#

ah restarting Unity worked, thank you. Perhaps it is a bit unstable, I am in unity 6.2 beta.

quartz folio
#

Always a depressing time when that's the fix UnityChanBugged

shell scarab
#

ah haha yea sometimes I forget

#

glad I didnt spend too much time on it tho

ocean hollow
#

when working with unity's spline package, objects usually follow the spline as intended. but if i set a gameobj to start following the spline's path during runtime, it starts to exhibit weird behaviour. it still follows the path, but it seems to use some sort of broken interpolation method instead of the expected spline follow method. has anyone experienced this before?

#

i should add that this only happens if there are no pre-existing objects affected by the spline already

vestal arch
woeful ivy
#

i keep getting these warnings from dynamic water physics 2 plugin, and they are super confusing to me - what bindings are they talking about? why does the thing i have on the second image not work or count as bindings?

leaden ice
#

It describes exactly the situation with the missing bindings

#

The docs do seem a little vague

#

It's not clear how it's resolving which input asset to use, nor is it clear if the input needs to be in a particular action map or something

#

If you check the code that's emitting those warnings it should become a little more clear

woeful ivy
woeful ivy
somber tapir
woeful ivy
#

i also get this while in the editor
InputActionMap with path 'UI' in asset "Assets/NWH/Common/Scripts/Input/InputSystem/SceneInputActions.inputactions" could not be found. The Input System's runtime UI integration relies on certain required input action definitions, some of which are missing. This means some runtime UI input may not work correctly. See Input System Manual - UI Support for guidance on required actions for UI integration or see how to revert to defaults. UnityEngine.UnitySynchronizationContext:ExecuteTasks () (at /home/bokken/build/output/unity/unity/Runtime/Export/Scripting/UnitySynchronizationContext.cs:110)
possibly related?

leaden ice
#

Are you sure there's not different code in the plugin for the new system?

vestal arch
#

what input backend is selected in player settings?

leaden ice
woeful ivy
#

okay i fixed it, i went from "Both" to just "Input System" and for safe measure removed the already disabled InputManager scripts

#

thanks everyone!!! UnityChanwow

sonic bloom
#

hello everyone,

I am trying to send a command in loop to my robot, using thread in background,

void ServojSendLoop()
    {
        float prevTime = 0f;
        double interval = servojUpdateRate; // 0.008
        while (keepSending)
        {
            double start = servojStopwatch.Elapsed.TotalSeconds;

            float[] anglesToSend = new float[6];
            float currentTime;
            lock (angleLock)
            {
                Array.Copy(targetServojAngles, anglesToSend, 6);
                servojAngleLog.Add((float[])anglesToSend.Clone());
                currentTime = (float)servojStopwatch.Elapsed.TotalSeconds;
                servojLogTime.Add(currentTime);
            }
            float delta = prevTime == 0f ? 0f : currentTime - prevTime;
            servojLogDelta.Add(delta);
            // UnityEngine.Debug.Log($"Sent angles: [{string.Join(", ", anglesToSend)}], dt={delta:F6} s");
            prevTime = currentTime;
            robotManager.SendServoJCommand(anglesToSend, 0.1f, 300);

            // Busy-wait until the next interval
            while (servojStopwatch.Elapsed.TotalSeconds - start < interval)
            {
                Thread.SpinWait(10); // Yield CPU briefly
            }
        }
    }

It stays very close to 8 ms, but sometimes it fluctuates a little by 1 or 2 ms, is there any way to get absolute 8 ms loop time??

little meadow
#

I'd go with "no", but I'm not 100% sure. Why do you need it to be that precise?

steady bobcat
#

It could be better? not fully sure tbh

tame silo
tame silo
tame silo
#

what helps is just creating a new public Sprite[] sthIcons2 array, it's only the old sthIcons that's bad

#

and it doesn't even help commenting out the array completely, recompiling so that the script doesn't have the array at all, and only then adding it with references back in the editor

#

unless I use a new variable name

#

so for now I will just rename

small schooner
#

looks like a bug, you may try to update your project to the last Unity3d version it could be fixed there

tame silo
#

yeah I will try that. in any case the workaround is super simple, so it's not an issue

#

it's just... bizarre behavior

#

thanks for all the help!

fringe scroll
#

Question about the life cycle of Scriptable Objects.

If I have created a Instance of a Scriptable Object and set it as a field on a MonoBehavior and the MonoBehavior is destroyed does that also destroy the instanced Scriptable Object?

night harness
#

No

fringe scroll
#

oof now I have to redesign my entire game controller ๐Ÿ˜…

#

Well not the game controller but a sub system that uses it.

sonic bloom
sonic bloom
steady bobcat
#

And do think about any costly operations you do that may be taking 1-2 ms

#

Otherwise you will want to have a queue of pre processed commands that is filled by another thread to minimise time between each cmd

sonic bloom
steady bobcat
#

I guess best case with that technique would be an 8ms delay

austere solar
#

Only 1 of 2 public fields is showing up in the inspector. Idk why. All you need to know is that Registry inherits from ScriptableObject.

naive swallow
austere solar
naive swallow
#

You probably want to use CreateAssetMenu

austere solar
#

The weird part is why Sprite works but string doesn't...

naive swallow
austere solar
#

I wanna make my game available to modding, that's why i want it to work in the Inspector too. I couldn't care less about the inspector if not for that.

naive swallow
#

The inspector you are looking at is for the script file itself, not an instance of this SO.

#

You will need to actually create an instance of your SO to change the values on it

austere solar
#

i see...

naive swallow
#

What you see here is akin to just doing = "SomeStringValue" on your string variable in the initializer

#

It changes what new instances will be created with

#

Since you cannot set an asset reference in code, it lets you assign one here. You can't see the string variable because you can just set that in the code

austere solar
#

ok maybe im doing BS again becouse im new to SO's so i'm still figuring out how i could use it...

naive swallow
#

ScriptableObjects are scripts that define an asset you can create, like a prefab or a texture but just containing variables. You should be adding on a CreateAssetMenu attribute so you can actually create an instance of this SO that you can drag into a variable slot in some other component

cloud tartan
#
        print(PosX);
        print(PosY);```
this snippet *should* get the position of the player, and set the posX and posY variable to the x and y position of the player respectively, and then print out the values of both variables.
What it instead does is set the player's position to 0, 0 and in return sets both variables to 0
What am I doing wrong here?
naive swallow
cloud tartan
#

I got that much, but how should I do this instead?

#

Or at least point me in the right direction

naive swallow
#

The thing on the left of the = is the thing that you are setting

chrome trail
#

Trying to play with properties again and I'm trying to get the property to fire off an event when another script tries to assign a value to it like so.

public int currentHP { get { return currentHP; } set { currentHP = value; onUpdate?.Invoke(Stats.CHP); } }

I already know this causes a StackOverflowException because it's effectively stuck in an infinite loop, but I don't know how to design this in a way that doesn't invoke an infinite loop

naive swallow
chrome trail
naive swallow
#

Ah, you edited it just as I sent

chrome trail
fossil steeple
#

I know that instantiating a canvas per gameobject is bad performance wise
but, if I wanted to create an hp bar above enemies
but make the hp bar a child of the enemy GO
what's the best approach?

lean sail
fossil steeple
lean sail
#

Profile it and see if you have a performance issue. Especially before going down a rabbit hole of a harder solution because you read it from someone who read it from someone who read it....

young yacht
#

works wonders

#

and unity handles a shit ton of enemies pretty well

#

as long you do it right

#

personally what eats away the performance is meshes and textures

#

make sure your enemy animations are baked and meshes that dont move are static

#

you should be fine

#

if its a 2D game then ignore what i said

quiet depot
#

Hi, trying to create a loading screen using a coroutine and unity Android. However the next scene doesnโ€™t load?

west lotus
#

Show code

quiet depot
# west lotus Show code

Itโ€™s literally just an IENumerator Start()

{
Yield Return new wait for seconds(3)
SceneManager.LoadScene(โ€œMain Sceneโ€);
}

#

Canโ€™t take a photo, havenโ€™t got discord on the computer ๐Ÿคฃ

west lotus
#

Well for starters the capitalisation of the code you shared is wrong. This is why we need to see the exact code and what errors you have in the console

#

My best guess right now is that Main Scene is not added to the scene build list

#

Or itโ€™s added but itโ€™s not called Main Scene

quiet depot
#

Thatโ€™s the best I can do, sadly. Iโ€™m so confused.

west lotus
#

And I canโ€™t help without more concrete info

quiet depot
west lotus
#

Is loading manager attached to a game object?

quiet depot
#

Yes.

west lotus
#

Well what does the console tab say ?

quiet depot
vestal arch
quiet depot
vestal arch
#

you can access discord via any browser

quiet depot
vestal arch
vestal arch
quiet depot
vestal arch
#

really should find a way to share actual screenshots or code then, it gives us a much easier time helping you

quiet depot
#

Yep, I know. If I was at my computer at home I would. However that isnโ€™t the case, Iโ€™ve searched online for answers, forums etc and now I find myself in the Discord because I havenโ€™t found an answer. Iโ€™m working with what I have.

vestal arch
#

have you checked to see if the code is actually being reached? ie having a Debug.Log at the start of the method

naive swallow
#

If your timescale is 0 this will never finish

vestal arch
#

ok, what about after the Wait?

quiet depot
#

Yep, it logs. It just doesnโ€™t go to the next scene.

vestal arch
#

what if you rename the scene to not have the space?

#

and update the load call as well

naive swallow
cloud tartan
#

how do I get the position of another object to be referenced in a script?

vestal arch
#

get a reference to the other object and get its transform.position

cloud tartan
#

I think ive tried that but I want to use the x and y positions for PosX and PosY variables respectively

#

oh wait I should probably move code beginner

cloud tartan
#

transform.position.x?

vestal arch
#

yeah

cloud tartan
#

oh

vestal arch
#

it's a Vector3

#

you can get the components like any other Vector3

cloud tartan
#

is there a way to make an infinite array?

night harness
#

a list?

cloud tartan
#

actually it doesnt need to be infinite, it just needs to automatically add things

cloud tartan
night harness
#

no

#

what do you mean by automatically add things

cloud tartan
#

so basically, I have a script that gets the position of the player every frame, and i want to make a list of all the x positions and all the y positions it has

night harness
#

you have to do that

cloud tartan
#

do what

#

like is that a question?

night harness
#

you said it needs to automatically add things

#

you need to write code to add things to it

cloud tartan
#

well yeah, but i want it to add the new position of the player to the array/list whenever it gets a new position

#

I can't type out all of those positions

rigid island
#

if(oldpos != newPos)
//Add To List

steady bobcat
#

unless an int vector positions will probably never match so you need to use an approximate comparison

steady bobcat
#

Huh you are right

public static bool operator ==(Vector3 lhs, Vector3 rhs)
{
    float num = lhs.x - rhs.x;
    float num2 = lhs.y - rhs.y;
    float num3 = lhs.z - rhs.z;
    float num4 = num * num + num2 * num2 + num3 * num3;
    return num4 < 9.99999944E-11f;
}
#

TIL

vestal arch
rigid island
#

I see.. yeah its very much depends also how you're using it too.. I wouldn't rely it on it for big things, for my uses it was always okay so yeah something you'd want to keep in mind for sure

earnest gazelle
#

There is a problem when using skeleton root motion. I use native spine system to play animations.
Imagine, for specific animation, I wanna enable root motion and after finishing it, disable it.
The problem is when disabling the root motion and play the next animation (non root motion), the character snaps back , how can I resolve it?
To enable/disable root motion, I write the code below

 _skeletonRootMotion.enabled = isActive;
#

I see the fields X, WorldX and Ax skeleton are not zero but by setting them to zero does not solve the problem. In the next frame, the values change to non zero again and smoothly moves to zero!

brazen nest
#

Anyone here have a good grasp on quaternions? I have to work with rotations so much but barely understand how the system works, I just know multiply something rotation by another rotation basically adds it

naive swallow
#

The general rule is: If you find yourself ever reading or writing to an individual component of a quaternion - don't.

steady bobcat
#

Its usually enough to construct them from Euler angles and to know how to multiply them together

little meadow
#

And if you don't know how to multiply them together, just multiply them the other way around ๐Ÿ˜‚

steady bobcat
#

haha yep very true

viscid plaza
#

Sorry, maybe I'm dumb and I don't fully understand how inheritance works, but this:

foreach (var thingObject in ActiveThings)
{
    if (thingObject.TryGetComponent(out Thing thingComponent))
    {
        thingObject.GetComponent<Landmark>().ChunkId = (10, 0);
        Debug.Log(thingComponent.ChunkId + "ChunkId From thing");
        PackYourThings(thingComponent, thingObject);
    }
}

Always print 0 0 (the default for an int,int tuple) instead of the value I am assigning to Landmark, which inherits from Thing. So, if I use GetComponent (TryGetComponent) on a component that a GameObject doesn't have, but does have a component it inherits from, it returns an empty object for some reason?

#

Worth noting that thingObject does NOT have a Thing component assigned, ONLY Landmark. Also, ChunkId is ONLY declared in Thing, not in Landmark.

naive swallow
viscid plaza
#

The GetComponent call is only for demonstration.

naive swallow
#

Does the object in question have multiple components of type Thing

viscid plaza
#

No.

#

The problem is that I set the value inside of Landmark earlier, but when I do TryGetComponent, which should return Landmark, since it inherits from Thing, but instead it returns an empty Thing.

#

Or so it would seem.

naive swallow
#

Maybe show the inspector of one of the objects in ActiveThings

viscid plaza
#
if (thingObject.TryGetComponent(out Thing thingComponent))
       {
           Debug.Log(thingObject.GetComponent<Landmark>().ChunkId + "ChunkId From thingObject");
           Debug.Log(thingComponent.ChunkId + "ChunkId From thing");
           PackYourThings(thingComponent, thingObject);
       }

Here is a better example.

viscid plaza
#

Cheers!

#

I was inheriting Thing on another class for no reason.

vapid merlin
#

Hi I was wondering does anyone have problem when rotating with player or moving it feels like it is sturreing a little bit like the objects them self.

Me using rigidbody for movemnt, yes rotation of camera point is in late update and actuall camera that is following rotation and position of that object is also in late update and rigidbody is set to interpolate

fossil steeple
vapid merlin
#

should movemnt be in fixed update since it is physics

rigid island
vapid merlin
#

but it is more camera point and player that are rotating

#

actaull camera is not a child object

#

it is just following camera point

rigid island
#

for camera I only used Cinemachine when it was following the player instead

#

but yeah lateupdate I think is usually where to add cam

little meadow
#

how are you doing the movement exactly?

rigid island
#

hopefully not using translation lol

vapid merlin
little meadow
#

actual code that does the movement... specifically wondering if it's using rigidbody.position, MovePosition, AddForce or velocity, or perhaps still doing transform.position

vapid merlin
#

rb.linearvolocity for moving

#

addforce for jumping and sliding

#

and wallruning

little meadow
#

hmm... that is appropriate

#

and how's the camera moved?

vapid merlin
#

just camera.position = camerapoint.position

#

camerapoint is child of player

#

camera itself seperate object

little meadow
#

this also seems reasonable... can you record a video of the problem?

edgy patio
#

Iam getting an error on this line

transport.SetRelayServerData(new RelayServerData(allocation, "dtls"));

It says "The type or space name 'RelayServerData' could not be found (are you missing a using directive or an assembly reference?)
https://paste.mod.gg/stzyavyogqxz/0

#

I can't find where this error is stemming from

naive swallow
#

Does your IDE suggest anything

edgy patio
# naive swallow Are you missing a using directive?

I shouldn't be, the error occurred after i tried using the older Lobby and Relay packages with the Multiplayer one. But I deleted the older ones, reinstalled the new one, and regenerated project files, and it is still ongoing.

ruby thistle
#

Hello Everyone, I have installed Unity Hub and I have installed the latest Unity Version, it is Unity 6 and some other numbers, anyway, I have created a project but when it loads a bit it crashes

naive swallow
cosmic rain
tawny elkBOT
#
๐Ÿ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

ruby thistle
cosmic rain
#

Nothing what?

ruby thistle
#

But I tried forcing Unity with OpenGL and it did work

edgy patio
naive swallow
edgy patio
#

its says unity transport

#

which i have, but the code is not working when i try to use Unity.Networking.Transport.Relay

#

iam unsure how to apply this to my code to get RelayServerData to work.

cosmic rain
edgy patio
cosmic rain
edgy patio
cosmic rain
edgy patio
edgy patio
cosmic rain
edgy patio
cosmic rain
edgy patio
#

this "Unity.Netcode.Transports.UTP;" since "Unity.โ€‹Networking.โ€‹Transport.โ€‹Relay" falls under it

cosmic rain
#

I'm not sure what you mean by since "Unity.Networking.Transport.Relay" falls under it

edgy patio
cosmic rain
edgy patio
#

they have one small change to make it

transport.SetRelayServerData(new RelayServerData(allocation, connectionType: "dtls"));

but the issue still persist where it says namespace name RelayServerData could not be found

cosmic rain
edgy patio
# cosmic rain Well, they don't show what namespaces they use, but they likely use the one we m...

when i try to use the one we mentioned earlier it does not work with their code, saying

Severity    Code    Description    Project    File    Line    Suppression State
Error    CS1729    'RelayServerData' does not contain a constructor that takes 2 arguments    Assembly-CSharp    J:\Unity chess\My project\Assets\Scripts\NetworkUI.cs    51    Active

and if i use the code they have for the relayserverdata i get this

Severity    Code    Description    Project    File    Line    Suppression State
Error    CS1739    The best overload for 'RelayServerData' does not have a parameter named 'connectionType'    Assembly-CSharp    J:\Unity chess\My project\Assets\Scripts\NetworkUI.cs    79    Active
edgy patio
#

in one of the other pages in that same section

edgy patio
#

still have not been able to get anywhere with this

#

i have been able to figure out that this code works, but idk how to integrate what i need onto it

public async Task<string> StartHostWithRelay(int maxConnections, string connectionType)
{
    await UnityServices.InitializeAsync();
    if (!AuthenticationService.Instance.IsSignedIn)
    {
        await AuthenticationService.Instance.SignInAnonymouslyAsync();
    }
    var allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections);
    NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(AllocationUtils.ToRelayServerData(allocation, connectionType));
    var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
    return NetworkManager.Singleton.StartHost() ? joinCode : null;
}
#

and it only works because its avoiding RelayServerData

#

which using Unity.Netcode.Transports.UTP; should allow me to use

cosmic rain
#

It also feels like you have several packages installed that are not meant to be used together or have version incompatibilities.

agile brook
#

Hi all, I just started throwing together an isometric game in Unity and made a point of using pure 2D w/ sprites rather than a 3D environment with an orthographic camera at an isometric angle. I'm currently just starting out with the basics: taking a Cartesian coordinate and converting it into an isometric coordinate and backwards.

I can spawn a grid of tiles with a given width and size ratio (so this isn't strictly isometric, as my tile sprites are a bit steeper than the expected 30 degree angle). However, when I use my inverse transformation method to figure out which tile the mouse is hovering over, I notice a strange distortion that seems to increase the further away I get from the center of the screen. I've tested this with properly isometric tiles and it still failed to work, so I believe the error doesn't come from the fact that the tiles are dimetric.

My conversion methods can be found here. https://pastebin.com/uxDJJQj1
In case it becomes relevant, the code for testing the hovered tile is here. https://pastebin.com/rEnQVD2x

wooden gate
#

hey guys, so i am a beginner to making games on unity and i came across some random issue that shouldnt happen?

 void FixedUpdate() // Check for the current states of the player.
 {

     // All states being checked.
     if (isJumping)
     {
         print("Player is jumping.");
         rb.AddForce(new Vector2(0, jump_power), ForceMode2D.Impulse);
         isJumping = false;
     }

     if (isFalling)
     {
         print("Falling");
     }

     if (isMoving)
     {
         rb.AddRelativeForce(new Vector2(x_input*movement_speed,0), ForceMode2D.Force);
         print("Player is moving.");
     }
     if (isGrounded)
     {
         print("Player is grounded.");
     }
 }

And it has to do in the "isMoving" part, where if i made it using linearvelocity or addForce or addRelativeForce, the character just does not move at all even though with the same code it used to move the character with no problem. everything else like the jumping works And all the prints get printed out

#

i was using linear velocity at first and it stopped suddenly and switched to addforce, then while working on a way to set a limit on the force it also stopped working

#

now both stopped working even though i would revert to the exact same code

#

Original linear velocity to move:

            rb.linearVelocity = new Vector2(x_input * movement_speed, rb.linearVelocity.y);
            print("Player is moving.");
#

ok i fixed the problem somehow?

#

printing the "movement_speed" it is changing from 5 to 0 when i never ever changed the value

#

the only time it gets changed is in the unity properties itself because it is [SerializedField] float

#

but not once in code, now i put an integar instead of the variable it works fine, i have no idea why

leaden ice
wooden gate
#

turns out i inserted the script twice in my player

#

which explains why i had 2 different values for the movement speed

#

it works completely fine now ๐Ÿ˜…

rustic ember
#

Hi! I have a question regarding the order of operations

string result = "";
int a = 1;
int b = 2;

result += a * 2 + b```

What will be the result string? "4" or "22"?
#

And if it's 22, will () around the math fix it to be 4?

night harness
#

4 i believe. the += is in charge of turning your value into a string

#

easy to test though ๐Ÿ˜„

rustic ember
sudden ruin
#

i used this when do a post api call
cs UnityWebRequest.Post(uri, jsonData)
but it said this is obsolete? and recommended me to
cs using (UnityWebRequest webRequest = UnityWebRequest.PostWwwForm(uri, jsonData))
which isnt sending object as json anymore but in this thing: application/x-www-form-urlencoded
is there something else to use or i should ignore this obsolete

rustic ember
#

Is "math" always preferred over adding strings?

night harness
night harness
rustic ember
#

I see. Thank you ๐Ÿ˜Š

sudden ruin
rustic ember
#

The parenthesis are grayed out, so I assume it doesn't matter @night harness

night harness
#

remember this counts for the + too (though im not actually sure which value is in charge of that here, i know it does end up as a string)

#

result.UpdateValue((a * 2 + b).UpdateValue(".")) (i added parenthesis because they will implicitly be there due to being on one half of the + were the other half is a different type(?))

#

hopefully im right on that ๐Ÿ˜„

mellow sigil
summer kettle
#

Why is there another 'apple' script in the Solution? How do I get rid of it?

cyan ivy
mellow sigil
#

I assume they mean this part

shadow wagon
#

I'd right click to view the file in the explorer

#

see what folder opens for apple.cs and Apple.cs

summer kettle
#

Nvm, Unity didn't update the metadata yet. I just reset it

last quarry
#

Is that not just the class

#

Oh wait

shadow wagon
last quarry
#

I see apple and Apple

shadow wagon
#

couldnt help myself

summer kettle
#

I renamed the apple file to uppercase, but the engine didn't update the project file immediately

shadow wagon
#

unity and vs are weird with file modifications sometimes

#

ive renamed files in VS, only for unity to switch them back the moment I go back to the editor

#

I think its also happened when I deleted a file that then reappeared moments later

#

I think making new .cs files within Visual Studio also confuses unity. I get why it confuses unity, but its annoying as it can often be more convenient to make a new file in VS with a simple hotkey, than it is to go back to unity to do it there

steady bobcat
#

Unity is in control of the solution/project files so when it reloads it will re generate.
Making a new cs file should work fine in visual studio, i use the "move to xx.cs" option all the time just fine.

vestal arch
summer kettle
#

What does it mean half-size? Horizontal or vertical?

vagrant blade
#

It's the height

vestal arch
#

it's half the height*

vestal arch
#

please don't crosspost

edgy patio
upbeat fulcrum
#

hi, i have a problem, i hava a nav mesh agent that stop in front of a door when exist a wall to pass throught it, how i can solve it. If i instantiate another enemy, the new one can pass without problems

edgy patio
vapid merlin
#

Hi, does anyone know know good way to have like solid in air movment
I was tryinfg just to add force in direction that I want to move with forcemode.aceleration but just little bit so game does not feel to stiff(I dont want that full in air controle but just to be able to movve little bit so game is nto to stiff)
but then second jump is way to strong

sand escarp
# vapid merlin Hi, does anyone know know good way to have like solid in air movment I was tryi...

lots of ways you could do this @vapid merlin. not sure what you mean by "but then second jump is way to strong" but if you want to keep control of the player in the air you could have an "inAir" multiplyer to your speed and if you are not touching the floor you multiply it by that amount. You could check if they are in the air in multiple ways , raycast, boxcollider or sphereCast depending on how you wanted to do it.

brazen nest
vapid merlin
#

I mean if I jump right for example it has very slighy change for other directions

#

and so on

#

but my method makes second jump way to big

hexed oak
#

is there no UnloadScene Synchronous that isn't deprecated?

#

they deprecated all the sync unload calls and slapped a note in there to say "well just use async"

elder hazel
#

Anyone here with knowledge about Handles, EditorWindow and color?

am having a problem with drawing, in the code I use the same Color for the DrawAAConvexPolygon() and DrawSolidArc(), yet they differ in color.

    Handles.color = new Color(color.r, color.g, color.b, color.a * color.a);
    Handles.DrawSolidArc(pointA, Vector3.forward, startDir, 180, radius);
    Handles.DrawSolidArc(pointB, Vector3.forward, -startDir, 180, radius);

    Handles.color = new Color(color.r, color.g, color.b, color.a);
    Handles.DrawAAConvexPolygon(
            new Vector3(pointA.x, pointA.y, 0) + startDir * radius,
            new Vector3(pointA.x, pointA.y, 0) + startDirR * radius,
            new Vector3(pointB.x, pointB.y, 0) + startDirR * radius,
            new Vector3(pointB.x, pointB.y, 0) + startDir * radius
    );
elder hazel
#

oh sorry, my mistake

lavish yacht
#

Hi, im new here. What channel can I ask a question relating to the Unity game engine itself. Im currently having an issue where my friend can't download a build of my game because it's getting flagged as a virus. We have tried turning off safe browsing in chrome and turning off his windows security and it's still getting flagged for some reason

maiden fractal
lavish yacht
#

Thank you

limber fog
#
    {
        if (Vector3.Distance(transform.position, player.transform.position) < fov.viewdistance)
        {
            Debug.Log("1");
            Vector3 dirToPlayer = (player.transform.position - transform.position).normalized;
            Debug.Log(Vector3.Angle(transform.up, dirToPlayer) + " < " + fov.fov / 2f);
            Debug.Log(Vector3.Angle(transform.up, dirToPlayer) <  (fov.fov / 2f));
            if (Vector3.Angle(transform.up, dirToPlayer) < (fov.fov / 2f));
            {
                Debug.Log("2");
                RaycastHit2D hit = Physics2D.Raycast(transform.position, dirToPlayer, fov.viewdistance);
                Debug.DrawRay(transform.position, dirToPlayer * fov.viewdistance, Color.red);
                if (hit.collider != null)
                {
                    Debug.Log("3");
                    if (hit.collider.gameObject == player)
                    {
                        Debug.Log("I SEE YOU");
                    }
                }
            }
        }
    }```

So this code seems to be written correctly, but i get this wonderful debug message. it states that the equation comes out false but it goes through anyway. any tips?
somber nacelle
#

pay attention to the warnings in your IDE

elder hazel
wintry crescent
#

What is the simplest way to have a mask that only makes rendering OUTSIDE of itself possible not inside
Both the mask and the masked object are custom graphics components already - I'm looking for a component analogous to mask but called inverse mask or something

Is there a package for this?

small schooner
#

You can invert the image and it will show the outside I think this is is the simplest way

#

Or you can wait until Unity Team add the invert option for mask ๐Ÿ™‚

#

You can also write shader with 2 texures of same size and setup to render second texture if dot of first texture is not transparent or if dot is transparent for Inversed version it is not hard

wintry crescent
wintry crescent
#

I'm trying to figure out how to change the stencil write mask in a shadergraph shader right now

#

if I figure that out I think I got it

small schooner
#

Why "Flipped textures and custom materials aren't an option " is not an option just open in Photoshop select all transparent part with magic wand and press invert selection and then fill it white color

wintry crescent
#

there's no texture to edit

#

it generates its own mesh

#

it's a custom MaskableGraphic

small schooner
#

Didnt you need the sprite for mask?

wintry crescent
#

the generated mesh is used for the mask

#

figuring out what the generation does and reversing it is a last resort I really dont wanna do

small schooner
#

flip the mesh in this case if you know how to generate mesh it should not be hard to generate inverted version

wintry crescent
#

I don't want to mess around with that unless I really need to

#

as I said, figuring that out is a last resort

small schooner
#

I do not understand how u masking the mesh?

#

Or u use it as Rawimage the only way i supose

#

If you really need I can write shader for you, but will you be able to set the texture of your generated mesh into custom shader material?

wintry crescent
wintry crescent
small schooner
#

Is it contain shader code?

wintry crescent
#

so not sure what you mean

small schooner
#

Do you have shaderName.shader file in project? where ShaderName is not necessary much shader in material path

#

I do not sure shader graph generate the shader but I think it should generate the shader cg file if you have it I can try to modify but I never worked with shader graph only with cg.

merry aspen
#

Hey there, I needed to learn how to add ads to a mobile game in unity6 but the guides I find online all seem outdated. Can anyone help me with that?

cosmic rain
dusky tulip
#

Hello, I have a question on how I can replicate the cloud shadowing just like this video. https://youtu.be/_uxV9R3JrXo?si=5NQowkQuJUrh4ev9

To me, it seems like itโ€™s two layers of clouds that are casting shadows at a different intensity, and when they overlap each other, the intensity of the shadow gets darker. (I could be wrong)

Date of Recording: 2020-10-17

Building a cloud shadowing engine which is consistent with the pixel art aesthetic poses some unique challenges:

  1. A purely screenspace approach looks great, but does not behave consistently when the camera perspective changes
  2. A purely worldspace approach is stable to camera rotation, but looks artistically in...
โ–ถ Play video
edgy patio
#

if anyone has the time, can you see why in this code, my black pieces on the client side do not detect each other? For the life of me, I can't figure it out. I was just able to fix the white pieces' movements being out of whack, but the black pieces still only detect white pieces, allowing them to be moved to other black pieces' locations and eat them.
https://paste.mod.gg/zgtxxidflcif/0

#

and some of the white pieces can still move in ways they shouldn't, like one piece can detect it can't move somewhere when there is one of its own but some of them can still do it

#

its very odd

lean sail
#

that truly is some code though. I dont think id recommend to be doing multiplayer at the moment either

edgy patio
brazen nest
brazen nest
light wraith
#

has anyone found a way to reduce Unity's long compile time?
currently unity opens up very fast, but it takes around a minute to compile my code. it's a really long time.
I see online people saying it takes them less than a few seconds. how???
I am already working with asmdefs. and reload domain is disabled

last quarry
#

Domain reloads always happen after compilation, no matter what, and reload all the code in your project. So the more packages you have, the longer it takes. Doesn't matter if the assembly was recompiled or not.

cold parrot
light wraith
#

I beleive mono has faster build times

light wraith
last quarry
#

And no, that's not IL2CPP. IL2CPP is only for builds.

light wraith
#

so what could be taking so long? is there a way to debug compilation?

cold parrot
light wraith
#

just restarted, still takes a while

somber tapir
light wraith
#

I started working with live editor reload (hot reload?) for playmode and for the editor. So far so good

last quarry
#

post process il for assemnly csharp editor sounds like an entities thing