#archived-code-general

1 messages Β· Page 150 of 1

ashen sage
#

its Line 111 differs from yours

trim ferry
#

of wht

ashen sage
#

so either you have modified it and made a mistake, or just a big typo

trim ferry
#

differ of what

#

what is different

ashen sage
#

this is the line 111 on the original code

#

this is your line 111

trim ferry
#

huh

#

lemme just

#

k i "fixed" it

ashen sage
trim ferry
#

nothing works 😭

#

i tried some tutorial for this but everything i try fails

#

if i make the animation by keyframes in blender it will look horrific

ashen sage
#

you cant succeed from the first time

#

i personally started from roll-a-ball tutorials

trim ferry
#

how do i fix my camera view clipping into things

ashen sage
#

camera has a property for that

#

i think its called near clipping plane

#

set it to 0.01f

#

Camera.nearClipPlane

swift falcon
inland dust
#

is there anyway to do something like this just in the program for visualization purposes? like it still is just top down. Is it possible in notepad or any other programs?

leaden ice
inland dust
#

no, its maps for a html platform game

leaden ice
#

You can certianly write a graphical program that lets you produce that text, sure

inland dust
#

I'm just wondering if theres a way to like partition a block of text and shunt it into a popout window for visual purposes

#

Nah not that, like

#

Just in a coding software

#

to help with the coding process

leaden ice
#

I'm not sure I understand the workflow you're looking for tbh

inland dust
#

I'll make a better photo to explain what I'm going for

leaden ice
#

It would probably be better to define that string in a separate file

#

and easier to pull it out to a separate window

#

have your code read it from the file

#

most code editors and fancy text editors will let you open two tabs into the same file though

inland dust
#

yeh

compact spire
#

I'm not sure what I'm looking at here.

topaz ocean
#

Im trying to expose component variables in my script with EditorGUILayout.FloatField, but every time I re-enter the prefab the components reset, how do I fix this?

compact spire
#

oh wait I see, it's wrapped on the screen

#

@inland dust I agree with @leaden ice, you should just have a separate editor, like a WYSIWYG editor with a font that gives clean spacing.

inland dust
#

yeh, i need to learn more

compact spire
#

Considering how much of a pain it is to edit text though to make levels

#

You could also create a system where you feed in a 64x64 image, and you associate each color to a character.

#

You would have to keep track of some sort of legend that says "brown is C"

inland dust
#

I was planning maybe using two images for every world

#

where 1 is the visuals the other the interactables, like collision and objects and npcs

compact spire
#

because you have to stack objects in a single space right?

inland dust
#

Kindof, only objects and NPCs would actually be visualized, collision based things would just be the data

#

Hmm, thanks yeh, I'll just give up on the text

#

and work with images

compact spire
#

If you went one step farther, you could have some small sprites and a grid, and then use some of unity's tile tools too easily draw things, then export that as text

inland dust
#

I'm not doing this in unity at all

leaden ice
#

Why are you asking in the Unity discord then πŸ€”

inland dust
#

I've made some cool stuff in unity but I like understanding everything that goes into it

#

Cause you guys still helped?

#

I actually dropped the same question in a few code related servers im on

#

you guys answered first, and therefore the most helpful!

vagrant blade
#

This server is for Unity specific coding questions, only.

inland dust
#

well ok, I wont ask for help then?

#

the thing is unity coding is still applicable to almost all other code? its just logic

vagrant blade
#

Sure, and questions that don't fall into the "almost all other", don't belong here. If you have a Unity specific question, you're free to ask.

#

Though, as you said, you're not using it. πŸ€·β€β™‚οΈ

inland dust
#

which thread is non unity code?

ashen sage
#

on any other server

inland dust
#

Ah, okay goodbye forever everybody

#

didnt know the unity server was like this but okay...

orchid island
#

why is this happening? I've already tried reimporting all assets

#

my visual studio is updated to the latest version

simple egret
#

Does the error also appear in the Unity Console?

orchid island
#

no

#

wait

#

mb it does, i jus had to save

simple egret
#

Hm, can you post the full error message?

orchid island
#

wait mb again, the error is indirectly related

light rock
#

isn’t there a UI package that you have to import?

orchid island
#

its a button error due to the UI not having a reference

leaden ice
#

Actually yes

simple egret
#

Yeah UI is there by default

leaden ice
#

but it's in most projects by default

leaden ice
orchid island
#

Assets/scripts

#

a folder i created

leaden ice
#

did you put an assembly definition file in that folder

orchid island
#

no

leaden ice
#

show the unity editor console window

orchid island
#

but ive never had to do it before

orchid island
simple egret
#

VS probably just desynced from Unity, it happens

leaden ice
#

oh then it's just your IDE

#

Preferences -> External Tools -> Regen Project FIles

orchid island
#

nothing changed

#

i think wat caused it was me hitting ctrl + b

simple egret
#

Unload the solution in VS, and reload it with all dependencies

orchid island
#

so i built the .cs file independently of unity or sum

ashen yoke
#

close vs, delete .vs open vs

orchid island
simple egret
#

From the Solution Explorer tab, right click the project, Unload

orchid island
#

im blind

#

i dont see it

jagged hedge
#

Heya, anyone know how to make a method that gets called each time a new scene is loaded in a singleton script? Since stuff like OnEnable() won't work there

simple egret
jagged hedge
#

ty all! ❀️ (:

orchid island
#

these are the options i get wen i right click the project

#

well i right clicked the solution..

simple egret
#

Yup

#

Project is the green item below

orchid island
#

theres nothing green

simple egret
#

Oh weird. Assembly-CSharp is the one

ashen yoke
#

@orchid island did you do this - close vs, delete .vs open vs ?

simple egret
#

One thing at a time

orchid island
ashen yoke
#

root project folder

orchid island
#

ill try if this doesnt work

ashen yoke
#

has to be the other way around

#

generally you first nuke .vs and then in 99% of cases the issue is resolved

topaz ocean
#

Does anyone know how to fix the problem of "CreateEditor" having values not save when a prefab is exited and re-entered?

placid temple
#

im trying to do a multiplayer game and read i need to set the variable "Default Is Networked" to true. I cant find it in project settings, can anyone help?

ashen yoke
topaz ocean
#

im trying to create a layered inspector where I have an inspector for the "wheel" which is then brought to the "suspension" inspector. Problem is that when I change values through this, it resets the next time I enter the prefab im editing it in.

orchid island
#

@ashen yoke you were talking about this folder right?

ashen yoke
#

yes

orchid island
#

yeah... i deleted it and reopened vs and nothing changed :/

ashen yoke
orchid island
#

tried that too

pure cliff
#

Hmm, whats considered a clean pattern in a Dependency Injection setup to hook up your existing world GameObjects to your dependency tree

ashen yoke
#

but for future always delete .vs when you have issues like intellisense stopping working, or files not recognized or namespaces or errors displayed that are not real

#

.vs is where vs cache is and it often gets corrupted

leaden ice
#

"Clean" is subjective πŸ€·β€β™‚οΈ

ashen yoke
pure cliff
#

Im thinking I might need to pass in all my GameObjects as variables via Editor on the "Root" of my DI tree, which should be a single monobehavior (and then everything else all the way down are POCOs)

and then I have some kind of "GameObjectManager" I register that handles holding a reference to my "scene" game objects

ashen yoke
#

but i dont know how created editor (which you create on each gui call btw) behaves

#

what you can do to hack around this is to set the object dirty

pure cliff
# leaden ice "Clean" is subjective πŸ€·β€β™‚οΈ

So heres my issue, effectively speaking the GameObjects are all monobehaviors, so I dont think I can simply just Inject them, especially if later I want to also have more instances of them get made dynamically, as opposed to the ones that you start with in the scene

ashen yoke
#

through EditorUtility.SetDirty()

#

this circumvents normal unity serialization mechanisms for inspector display but ensures that the data wont be lost

pure cliff
#

Like uh, lets say I have a Bat enemy, I might have a buncha BatEnemy prefabs dropped in preset spots in the scene they will always be.

But I might also have a VampireEnemy that has SpawnBat() to summon moar bats dynamically

leaden ice
ashen yoke
#

you are serializing references at edit time, its not really DI

leaden ice
#

for dynamically loaded objects - you're basically going to end up with a collection at runtime to track them

#

but something like a "BatManager" which holds the list of bats could be injected

pure cliff
#

But what if I have like, 500 bats in "preset" places in the game that I already could have set and baked in

#

I presume the act of generating 500 bats from a prefab at runtime with a script is far more expensive than doing it via the scene editor and having all those prefabs already placed at compile time right?

#

the second one will effectively have done all that work already and "baked" em in right?

ashen yoke
#

most likely there is marginal difference

#

you probably get gains because unity will batch deserialization

#

but all the components on those objects will go through the same init calls

leaden ice
#

but for prebaked bats you can:

  • Use FindObjectsOfType<Bat> in the Awake for your BatManager
  • make a List<Bat> in your BatManager and drag n drop all the scene bats in.
pure cliff
#

It also means I gotta write all the code and stuff for placing those 500 bats, vs them being placed through the editor already

pure cliff
leaden ice
#

it should be a MonoBehaviour

pure cliff
#

No it will be a POCO

leaden ice
ashen yoke
#

what i assume most DI's and other architectures do is go through all the scene objects before they are initialized

leaden ice
#

doesn't matter

pure cliff
#

Only the very top level entry point will be a MonoBehavior and everything else can just be POCOs going down

leaden ice
pure cliff
#

So yeah the List<Bat> was the second option I originally outlined

ashen yoke
#

scene.GetRootGameObjects(), disable all roots, visit the hiearchy looking for what you are interested in

#

then restore the scene state

pure cliff
#

Effectively what I was describing was a SceneObjectManager service or whatever, who's job is to go snag all those existing objects in the scene at startup and manage the Refs to em

#

So it can be used to get all the bats, the player, all that jazz

ashen yoke
#

yeah

#

thats what most frameworks do

pure cliff
#

aight, was mostly just sanity checking that its a decent way to approach it

ashen yoke
#

type is not abstract?

#

not generic?

#

if its generic you have to construct generic type

#

where is the GoToState<DiggingState>

#

what subclasses it

#

Default constructor not found for type Characters.Core.States.DiggingState

#

so you are invoking that with a T that is DiggingState

#

anyway, this possibly just means that Character is null

#

possibly

#

ah

#

i remembered this one

#

let me check

#

no that was something else

#

what was it?

pure cliff
#

hmm, my next thing Im mulling over is at the core of my game I want to build all of the stuff that happens around "ticks" or "rounds", and I want a way to start off by firing off "okay everyone a new tick is starting, everyone do 1 tick of stuff", and then everyone does their 1 thing, which can take a variable amount of time, and then once everyone gives the thumbs up that their "thing" is complete, then the system queues up the next tick of stuff to do

#

simple example would be simply just movement, the player could click to queue up moving 3 squares, each 1 square of movement counts as 1 tick, so all the enemies will also move 1 square, possibly (some enemies may only move one square every 2 ticks, so they skip every other tick and give back an Okay asap every odd tick, doing nothing)

#

I definitely am thinking Coroutines are gonna be involved here, and some kind of callback to signify the given entity has completed its coroutine, and once everyone signs off, the next tick fires

ashen yoke
#

is character a uobject?

leaden ice
pure cliff
#

like "rounds" maybe is a better word

ashen yoke
#

turns

pure cliff
#

yeh

leaden ice
#

then yeah a turn manager. Just keep a list of objects which need to act

#

and have them call back to the manager when they're done

#

at which point the manager removes them from the list/set

#

and when the set/list is empty you move on

pure cliff
#

yeah thats what Im thinking, Im thinking instead of events though, if you havent tried em yet, Pipes are super cool

#

works similiar to events but inherently Async

#

I dunno how I go about firing off a Task that doesnt block though, but still has a callback of some form I can monitor from Update

tulip temple
#

I have code for storing scripted objects so I can use the array as an ID
but right now its a class but I want it to be predefined and global (I think is the term?), so any script can access the lists data from any scene (even if I need to define everything myself like how minecraft does it, just without the registering stuff they use lol). I feel like I need to use a struct but im not sure how I would convert what I have.
the class based way I'm using right now is simple as its just for storing data

public class GameTileManager : MonoBehaviour
{
    public List<GameTile> tiles;
    public List<Stamp> stamps;
    public List<GameTile> decoreTiles;
    public List<FunctionTile> functionTiles;
}

help and direction would be amazing!
still new to this higher level coding even if it is basic stuff

tulip temple
#

ill ask phind about it, thanks!

pure cliff
#

is it safe to modify a class variable from inside of a fire and forget async void task, that future Update calls will keep checking in on?

weak viper
#

hello I need some help, will wait till you finish your discussion

wooden cove
#

Is there a difference in overhead between declaring a function and using a lambda?
or is the difference purely that lambda functions can basically not be detached from events?

leaden ice
pure cliff
#

something like, uh

bool Busy = false;

void Update() {
    if (Busy) return;
    GetBusy();
}

async void GetBusy() {
    Busy = true;
    await Task.Delay(2000);
    Busy = false;
}

Will Unity be cool with this?

leaden ice
hoary shard
#

Hi, can anyone tell me which guide I can read to create my first tycoon game? Thank you πŸ™‚

leaden ice
wooden cove
leaden ice
wooden cove
#

well no

#

but I could

#

if I didnt declare a function, it would

leaden ice
#

it's kinda complex - but if your lambda needs to do any variable capture, it will create a new object (new delegate) every time you run AddToScene

pure cliff
# leaden ice sure but why bother with Update here?

so instead of await Task.Delay() its actually gonna fire off a Pub/Sub Pipe<ReadyEvent> or whatever that all of my other classes are listening in on, and itll delegate out "do this action" on the pipe which they read off of async, and then when they finish they fire back on the same pipe "Okay done" and once everyone has fired back "okay done" then it sets Busy back to false, which on the next Update tick will refire off the method if there's another "round" queued up

wooden cove
#

ah, like that

#

I do wonder, what happens if I call the AddToScene a second time? does it instantiate it immediately or does it work differently?

leaden ice
#

You should really look into UniTask

#

without UniTask Unity's async support is kinda pitiful

#

it's very half baked

pure cliff
#

So something like, uh

async void GetBusy() {
   Busy = true;
   var events = CalculateNextRound();
   var writeTasks = events.Select(e => OutPipe.WriteAsync(e)).ToList()
   await Task.WhenAll(writeTasks);
   await foreach(var ready in InPipe.GetStuffAsyncIForgetTheMethodName()) {
   }
   Busy = false;
}

something vaguely like that

pure cliff
leaden ice
#

instead of Busy = false just put this in a loop

pure cliff
#

yeah busy=false is just pseudocode

#

its more likely to be

while (queuedActions > 0)
``` or whatever
#

it has an exit case for once its chewed through all the queued up rounds of action to complete, at which point Update() will start handling other stuff like re-enabling the UI, and looking for user input events (which will re-queue up 1 to n more rounds of actions, which puts us back into re-firing off this task)

bold coral
#

Hi I was reading up on task cancelling, Is this correct pattern to cancel a UniTask?

        private CancellationTokenSource cts = new CancellationTokenSource();

        private async UniTaskVoid LoadAndUseAa()
        {
            var go = await LoadAa(cts.Token);
            // do something with go
        }

        private void CancalLoadAa()
        {
            cts.Cancel();
            cts.Dispose();
        }

        private async UniTask<GameObject> LoadAa(CancellationToken ct)
        {
            var handle = Addressables.LoadAssetAsync<GameObject>("Something");
            await handle.WithCancellation(ct);
            Debug.Log("Loading done.");
            return handle.Result;
        }

Thank you πŸ™‚

pure cliff
#

@leaden ice so something like, this, ish

int queuedActions = 0;
void Update() {
   if (queuedActions > 0) return;
   if (noUserInput) return;
   var actionQueue = GetQueuedActionsFromUI();

   GetBusy(actionQueue);
}

async void Getbusy(DoTheThing[] actionQueue) {
    queuedActions = actionQueue.Length;
    while (queuedActions > 0) {
       var events = CalculateNextRound();
       var writeTasks = events.Select(e => OutPipe.WriteAsync(e)).ToList()
       await Task.WhenAll(writeTasks);
       await foreach(var ready in InPipe.GetStuffAsyncIForgetTheMethodName()) { ... }
       queuedActions--;
    }
}
earnest gazelle
#

Dudes, to doc TDD and GDD, do you use wiki in git for example or jira?
Where do you put it?

ashen yoke
#

technical docs git, design googledocs

leaden ice
pure cliff
leaden ice
#

nothing I said really contradicts that?

earnest gazelle
pure cliff
#

Id have to mess with it but, I would want to do things other than GetBusy in the update method, it should be firing off many other things, or not firing them off, etc

#

like in my example its just calling GetBusy but in reality there may be dozens of other things that could be firing off instead of GetBusy

#

or I guess we can call it PerformCombatRounds() or whatever

#

like it wont be getting called during cutscenes and stuff, and outside of combat

#

I dont want PerformCombatRounds() to be running constantly 24/7 on the game, effectively, it should only spin up for combat and then spin down when the rounds conclude

swift falcon
#

if you do:

int x;

what is the value of x? You can't do:

x + 1;

So what is x? I thought it was 0 but it can also be infinite or negative infinte. Is it all 3 at the same time?

pure cliff
#

you can indeed do x+1 in C#, non nullable int will default to 0 on init :3

#

if you declare int? x though, that will default to null

swift falcon
#

Visual studio just gave me an error

#

So theoretically all ints are 0

soft shard
#

Looking for some ideas on a code design problem - Im working on a FSM AI system that uses ScriptableObjects, my setup is essentially "AIAgent -> holds SO's for Idle, Chase, Attack -> agent performs logic/checks to change to Chase when player in sight, then Attack when in range", once in range/in attack state, it will periodically call an event to attack, and this is where im not sure the best next step - should I make a MeleeAttackSO and a RangedAttackSO, or create 2 extra scripts that subscribe for both types of combat (which would mean the agent would have specific state logic, which I dont really like), or is there another option I could look into? The reason im using SO's for the states instead of just classes, is so I can more easily modify what each "type" of AI should be, maybe one could patrol and chase but not attack, etc

bold coral
bold coral
ashen yoke
#

class members are initialized for you

#

locals have to be initialized

#

also not x + 1 its x += 1

#
        public void Foo()
        {
            SomeLargeStruct s;
            bool condition = false;
            if (condition)
            {
                s = new SomeLargeStruct();
                s.x += 1;
            }
            else
            {
            }
        }
#

if the condition here is false, s is never initialized, meaning its never allocated meaning you dont waste cycles

#

same thing will happen if you just move declaration into if but there are scenarios where its preferable to forward declare variables

flat tree
#

Hey, does someone know how I could create a list of variables I can hide and show in the editor (like the screenshot) without using lists ?

soft shard
#

Oh wait, these are not game objects/transforms, are they?

flat tree
#

I mean, how could I create a list on the editor without using a list or arrays in my code, a list i can hide or show

#

Because I have a lot of serialized variables and I would like to know if its possible to make it more readable

west lotus
#

Or you know feel free to use other attributes from here to make your inspectors look better

soft shard
#

That seems like a really useful git

flat tree
#

yep, thanks i'll try it

stone loom
#

Does anyone know why my script execution order wont go below the letter "N?"

#

I cant find ANY resources for why it wouldnt let me add a script to the list

#

like anywhere on Google, is there a bug or is there some reason i wouldnt be able to find a script in the list?

#

is it displaying as the namescpace?

#

It starts with PM_

#

but it cuts off right at "N"

#

can my script not be in a subfolder? i organize via Assets/MyFolder/Scripts/ScriptOrganizationName/TheScript.cs

#

SMH nevermind you can drag and drop the actual script from the folder into the list, so it doesnt matter

timber jewel
#

I guess this really isnt code but anyone know why remote 5 just isnt working randomly?

#

even when I close and reopen its just not working and in unity all the stuff is right

#

it was working like 10 minutes ago

orchid island
#

Make sure it's on USB tethering

timber jewel
#

Sorry I should have mentioned Im using IOS

orchid island
#

oh... I hav no idea then lmao

timber jewel
#

lmao

#

thanks anyway

orchid island
#

np

#

does anyone know why UnityEngine.UI is not recognized?

leaden ice
orchid island
#

I've tried:

  • deleting the .vs folder
  • deleting all .sln and .csproj folders
  • reimporting all assets
  • regenerating project files
  • unloading and reloading the project (with dependencies) from vs code
#

my vs code is also updated

leaden ice
#

Is this error in Unity too or only vsc

night harness
#

do you have the package installed

orchid island
#

wats the package name?

leaden ice
#

the ui package

night harness
#

Unity UI iirc

leaden ice
orchid island
#

i dont think it has anything to do with the package tbh, cuz i hav TMP installed and "using TMPro" is also not working

leaden ice
#

then it's just VSC

#

do you have the visual studio code editor package installed

#

and is it up to date

#

(also VSC is kinda terrible with Unity tbh)

orchid island
orchid island
#

u use mono?

leaden ice
#

monodevelop doesn't really exist anymore.

orchid island
#

oh

#

i never heard of rider ngl, ill check it out

leaden ice
#

it's by far the best - but it's not free unless you're a student

orchid island
#

i am

leaden ice
#

would definitely use it then

orchid island
#

what advantage does it have over vs?

leaden ice
# orchid island what advantage does it have over vs?
  • faster
  • better search features
  • better Unity integration (shows you all kinds of things like when fields have values assigned in inspectors, unityevent listenevers, etc.
  • usages in the unity project
  • fucking works all the time without any effort
orchid island
#

"must only be used for non-commercial educational purposes" lmao... how they gonna know?

opal sluice
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

opal sluice
#

Hi, let me know if this isn't an appropriate place to ask, but I've got a very strange problem here. It seems like Unity's random isn't working anymore for one specific project. Here's the line of code in question:

Debug.Log(Random.Range(0, System.Int32.MaxValue));

No matter how many times I call this, I always am getting the number 0. This line works fine for (at least one of) my teammates, and System.Random works fine:

// This works
System.Random systemRandom = new System.Random();
Debug.Log(systemRandom.Next(0, System.Int32.MaxValue));

This line also used to work just fine for me, but it seems to have stopped working today for some odd reason. It also worked when I made a blank project, but when I made the same script in an empty scene in my other project, it was still broken.

I've tried re-cloning the GitHub project, restarting my computer, and re-installing unity. No luck. Does anyone have any clue what could be going on here? Is there editor/project settings to do with Random somewhere that I don't know about? Has Unity just developed a grudge against my computer?

opal sluice
# leaden ice Are you calling https://docs.unity3d.com/ScriptReference/Random.InitState.html a...

No, but this has been working for a few months now and only broke today.

This is the entire class I tested in an empty scene:

public class UnityWhy : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("system max value: " + System.Int32.MaxValue);
        Debug.Log(UnityEngine.Random.Range(0, 5));
        Debug.Log(UnityEngine.Random.Range(0, 5));
        Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));
        Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));
        Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));

        Debug.Log("SYSTEM RANDOM");
        System.Random stupid = new System.Random();
        Debug.Log(stupid.Next(0, System.Int32.MaxValue));
        Debug.Log(stupid.Next(0, System.Int32.MaxValue));
        Debug.Log(stupid.Next(0, System.Int32.MaxValue));
    }
}
leaden ice
#

and it prints 0 three times in a row?

opal sluice
#

5 times in a row cause of the 0, 5 ones

#

but yes

rain minnow
opal sluice
#

No, Debug.Log max value gives me 2147483647 as usual

orchid island
leaden solstice
opal sluice
#

No

leaden solstice
opal sluice
#

Hmm, interesting. Calling Random.InitState(0) did make it spit out some numbers that were not 0. But that brings up 3 questions:

  1. Why was it working before
  2. Why is it still working for someone else
  3. Why do I have to call it in the first place? I thought unity called that at some point itself
leaden ice
opal sluice
#

I'm going to go and check to make sure we aren't loading random's state somewhere, thanks for the help

leaden solstice
#

I have no answer to those questions but if it is for your local PC, Unity is likely using system clock or something to init state, so maybe problem with that

opal sluice
#

It seems that the culprit was this line:

Random.state = SaveManager.savedRandomState;

We have a save manager that saves a bunch of stuff, and it looks like someone added the random state to it. Now, why on earth it wasn't working for me, but it was working for other people, I have no idea. Also not sure why exactly we're saving the Random state in the first place. But anyway, thanks for the help!

swift falcon
#

it sounded better in my head

mortal fractal
#

I just discovered PlayerPrefs

rugged goblet
#

PlayerPrefs should be avoided like the plague

jade phoenix
#

I forgot discord allowed you to talk like this

#

hi guys i have a problem can u help

leaden ice
#

Can you not though

jade phoenix
#

so basically I use the OnCollsionEnter/Exit function to help track fall damage for my player. Only problem is when the player moves from one ground object to another adjacent to it, the methods arent able to properly detect if the player has actually become off the ground

#

shown here ^

#

i tried putting the function in an Invoke() and waiting like 0.2 seconds later but that doesnt seem to change anything

leaden ice
jade phoenix
#

yes i do

leaden ice
#

only when it becomes 0 have you stopped touching the gorund

#

and only when it goes from 0 - 1 did you start touching the ground

#

that will let your code distinguish

jade phoenix
#
    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "ground")
        {
            Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, gameObject.transform.localScale.x);
            if (!(colliders.Any(c => c.gameObject.tag == "ground")))
            {
                Debug.Log("Is in air.");
                isInAir = true;
            }
            else
            {
                Debug.Log("Still colliding with: " + string.Join(", ", colliders.Where(c => c.gameObject.tag == "ground").Select(o => o.name).ToArray()));
            }
            yOnExit = gameObject.transform.position.y;
        }
    }```'
#

ik about the redunant if condition i'll fix that later

leaden ice
jade phoenix
#

im remaking marble madness

#

my player is a sphere

leaden ice
#

there's no need for OverlapSphere

#

this is what OnCollisionEnter/Exit are for

jade phoenix
#

i need to make sure the player isnt touch ANY ground objects though

leaden ice
#

I know

leaden ice
#

use this

#

e.g.

OnEnter() {
  numberOfColliders++;
}

OnExit() {
  numberOfColliders--;
}```
#

when it's 0 you're touching nothing

#

when it's 1 or more you're touching something

jade phoenix
# jade phoenix

that wouldnt do anything though because like the image above, the two objects enter and exit each other interchangeably

leaden ice
#

it would do everything

jade phoenix
#

when you leave one object, you enter another so the object's never 0

leaden ice
#
OnEnter() {
  numberOfColliders++;
  if (numberOfColliders == 1) {
    // Have just touched first object e.g. has just Landed
  }
}

OnExit() {
  numberOfColliders--;
  if (numberOfColliders == 0) {
    // Have just stopped touching last object e.g. has actually just come off the ground
  }
}```
#

for example

lean sail
jade phoenix
#

the logs

#

and gravity

lean sail
# jade phoenix and gravity

if it was the logs from the previous code youve shown, that logic is flawed since you are using a OverlapSphere on the same frame you OnCollisionExit. Also it was kinda bloated with a lot of linq thats not needed
What praetor wrote is good, i already use the same logic in my game

slow fable
#

i have a first person controller in which case that i want to flip the player's gravity for some puzzles, can anyone help?

#

flip the player's gravity upon pressing a certain key i should add

jade phoenix
#

maybe code the gravity yourself then

#

and use Vector3.<direction>

slow fable
#

this is the test level

#

and this is the code for the player


[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    [Header("Movement Settings")]
    public float movementSpeed = 5f;
    public float jumpHeight = 2f;
    public float gravity = -9.81f;

    [Header("Look Settings")]
    public float mouseSensitivity = 100f;
    public Transform playerCamera; // Reference to the main camera

    private CharacterController characterController;
    private Vector3 playerVelocity;
    private bool isGrounded;

    private float xRotation = 0f;

    private void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        HandleMovement();
        HandleMouseLook();
    }

    private void HandleMovement()
    {
        // Calculate player movement
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 moveDirection = transform.right * moveHorizontal + transform.forward * moveVertical;

        // Apply gravity
        isGrounded = characterController.isGrounded;
        if (isGrounded && playerVelocity.y < 0f)
        {
            playerVelocity.y = -2f;
        }

        // Handle jumping
        if (isGrounded && Input.GetButtonDown("Jump"))
        {
            playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        // Check if the player controller detects the bottom of a GameObject
        // and adjust gravity accordingly
        if (isGrounded && IsUpsideDown())
        {
            gravity = 9.81f;
            playerCamera.localRotation = Quaternion.Euler(180f, 0f, 0f); // Set camera upside down
        }
        else
        {
            gravity = -9.81f;
            playerCamera.localRotation = Quaternion.Euler(0f, 0f, 0f); // Set camera upright
        }

        // Apply movement with gravity
        playerVelocity.y += gravity * Time.deltaTime;
        characterController.Move(moveDirection * movementSpeed * Time.deltaTime + playerVelocity * Time.deltaTime);
    }

    private void HandleMouseLook()
    {
        // Calculate mouse look rotation
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        // Rotate the player body horizontally
        transform.Rotate(Vector3.up * mouseX);

        // Rotate the camera vertically
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        // Apply camera rotation
        playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    }

    private bool IsUpsideDown()
    {
        // Raycast downwards to check if the player controller detects the bottom of a GameObject
        // Modify the raycast origin based on the player's current orientation
        Vector3 raycastOrigin = isGrounded ? transform.position : transform.position + Vector3.up * 0.1f;
        Ray ray = new Ray(raycastOrigin, -transform.up);
        return Physics.Raycast(ray, 0.2f);
    }
}```
leaden ice
slow fable
#

how would you suggest i fix it?

leaden ice
#

idk, it's kind of unclear what your flipping condition is actually supposed to be

slow fable
#

well my goal is to have it so that if the player's gravity is flipped, the player object's gravity is reversed therefore sending the player object into the sky unless it collides with another object and walks like how it originally did prior to the gravity flip

spice dew
#

Someone familiar with Netcode for GOs (specifically network animator) can help with a problem related to animator layers?

I’ve looked up quite a bit and can’t find anything (useful)

slow fable
# leaden ice idk, it's kind of unclear what your flipping condition is actually supposed to b...

im trying to make the gravity manipulation be like this
https://www.youtube.com/watch?v=QmiNMI2dYCU

Gravity Cat Gameplay PC 60FPS [PC Gameplay Let's Play] Gravity Cat Walkthrough Playthrough
Platform: PC Steam
Genre: Platformer, Indie
Game Release Date: 14 Jul, 2016
Developer: Quiet River
Download Gravity Cat Steam Game: http://store.steampowered.com/app/491000/
Website: http://store.santaclaragames.com/games/8days/

Subscribe for more gamepla...

β–Ά Play video
#

but in first person

slow fable
#

(ping me if you have an answer, i'll be inactive because i hav to go to bed soon)

soft shard
# slow fable but in first person

The perspective shouldnt matter in this case, since gravity is usually the same Y axis in both 2D and 3D, I could show you an example if youd like though the general idea would largely involve flipping the sign on your gravity on whatever your using to move your character, if its a rigidbody with its gravity, id suggest applying your own gravity instead, that way you can manipulate it - one way you can do this is have a bool track "isFlipped", and on input, or game trigger or however you want to "activate" it, call a function that flips the bool (someBool = !someBool), and use that bool to determine the sign of your y velocity, you can also use the bool to lerp the rotation if you also want the "flip upside down" in addition to the "fall upward" effect - as a side note just for organization, I would also suggest maybe putting that logic in its own script, and either initializing it in your player, or attaching it as another Mono script to your player, that way you can also easily decide to disable or debug its logic in isolation

smoky ibex
#

You can serialize a list of type float, int, MonoBehaviour, etc... But why cant you serialize a list of type list of type float, int, MonoBehaviour, etc... ?

leaden solstice
#

You can add wrapper [Serializable] type that holds list and serialize list of that type

vale wren
#

is there a way to convert screen coords to scrollbar coords? i want to tween a card on a scrollbar to the center of the screen

earnest gazelle
#

One question.
I have implemented my own nav voxel agent. It is similar to NavMeshAgent unity with same functionalities.
I use it for my npcs. Now, I have added a new behaviour falling. Should it be in a separate class? right?
I mean controlling if that character is on the ground or not and updating it

winged sphinx
vale wren
#

i have a StartCoroutine(...) in an OnPointerClick event. why doesn't it work twice?

#

it seems to break the entire method call, because if I set the coroutine to start on right clicks it makes left clicks break as well

gray mural
#

hello, is it possible to print where method was called? e.g.

void Bla()
{
    Foo();
}

void Foo()
{
    print("called in `Bar()`");
}
vale wren
#

it's supposed to tween a card flip

#

works the first time, breaks the next

gray mural
vale wren
#

trying to figure that out rn actually

gray mural
#

give your code

vale wren
#

figured out it works in one direction but not the other

#
public class CardFlipHandler : MonoBehaviour, IPointerClickHandler
{
    private Image currentImage;
    [SerializeField]
    private Sprite _frontSprite;
    [SerializeField]
    private Sprite _backSprite;
    private bool faceUp = true;
    private bool isTurning = false;
    private float tweenSpeed = 0.01f;
    private float degDelta = 10f;

    public void Awake()
    {
        currentImage = GetComponent<Image>();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        // Placeholder input, not sure yet
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            if (!isTurning)
            {
                StartCoroutine(FlipCard());
            }
        }
        Debug.Log("End of pointer click callback");
    }

    private IEnumerator FlipCard()
    {
        Debug.Log("Coroutine called...");
        isTurning = true;
        if (faceUp)
        {
            Debug.Log("faceUp");
            for (float i = 0f; i <= 180f; i += degDelta)
            {
                transform.rotation = Quaternion.Euler(0f, i, 0f);
                if (i == 90f)
                {
                    currentImage.sprite = _frontSprite;
                }
                yield return new WaitForSeconds(tweenSpeed);
            }
        }
        else if (!faceUp)
        {
            Debug.Log("!faceUp");
            for (float i = 180f; i >= 0f; i -= degDelta)
            {
                transform.rotation = Quaternion.Euler(0f, i, 0f);
                if (i == 90f)
                {
                    currentImage.sprite = _backSprite;
                }
                yield return new WaitForSeconds(tweenSpeed);
            }
        }

        Debug.Log("Coroutine loop ended");
        isTurning = false;
        faceUp = !faceUp;
    }
}
lean sail
gray mural
wispy grail
#
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;

public class playerMovement : NetworkBehaviour
{
    private Rigidbody2D rb;
    private float speed = 20f;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!IsOwner) {
            return;
         };
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        // Calculate movement vector
        Vector2 movement = new Vector2(moveHorizontal, moveVertical) * speed;

        // Apply movement to the Rigidbody
        rb.velocity = movement;
    }
}

vale wren
wispy grail
#

I can move as a host but not as a client

gray mural
#

then what exactly must be done but isn't?

vale wren
#

i have no idea at this point πŸ’€

#

i think ima just sleep and try again in the morning lol

olive mesa
#

real programmer grindset

#

hope you come up with the solution next morning

gray mural
vale wren
#

thats a little rude man :/ thats the reason i asked in the first place

olive mesa
#

we're programmers not the messiah lmao

vale wren
#

im at my wits end, as far as i can tell everything in the callback is covered, i was just asking here to see if i could cover my bases

olive mesa
#

we can't figure out where you've gone wrong without the information

vale wren
gray mural
vale wren
#

was just a hail mary wasnt looking to get grilled 😭

olive mesa
#

as a programmer you have to learn how to diagnose problems

#

figure out where your code is going wrong

gray mural
#

if I give you random code and say "it doesn't work", will you understand?

vale wren
#

yea man i stepped through the entire thing and couldnt find anything. its an annoying heisenbug, was just hoping if i was missing something glaringly simple

gray mural
#

how do you even know that it doesn't work if you cannot say what doesn't work?

#

that sounds like you need help, but you're too lazy to explain

vale wren
#

alright, to be fair, i didn't just post and say "sorry it doesn't work", i said "it doesn't work on the second try, i every step of the callback and it covers everything with no errors, and yet it breaks"

vale wren
#

yeah thats definitely on me

#

but dang dude im sorry for being inarticulate 😭

sleek bough
gray mural
#

don't lose your and our time and just say what you need to do

olive mesa
#

think of the rubber ducky

#

if you wanna solve your problem you gotta explain it

#

if you explain your problem you often times end up finding out the solution on your own

gray mural
#

I think bawsi has mentioned correctly that it should be done with System.Diagnostics

vale wren
sleek bough
gray mural
vale wren
#

like i definitely wanted to be more specific but idk man sometimes you just run into some BS heisenbug that you cant even replicate. sorry :(

olive mesa
#

what even is the issue i personally am not aware

vale wren
#

yeah, it's still broken, but in between this text convo i discovered the positions were looping around from 180 to -180 which may have a role in things breaking (which I didn't know when I typed this)

gray mural
vale wren
# olive mesa what even is the issue i personally am not aware

i'm trying to tween a card flip. i have a coroutine called inside an OnPointerClick() (from IPointerEventHandler). for some reason, it breaks on one side of the flip, but not on the other. i provided my code, and put print statements all throughout to trace the callback, and it ended just fine. couldn't tell waht else was going wrong

vale wren
gray mural
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

vale wren
#

it should rotate from 0 to 180, then flip back from 180 to 0. but once it hits 180, it wraps around to -180. thing is, the other card flip conditions starts at 180 and rotates back to 0. i don't think that should break anything because should be setting the rotation to 180 in the first place, but it's the only lead i've got

gray mural
#

wait. what

#

float in for loop?

vale wren
#

thats what im sayin dawg

sleek bough
gray mural
#

ok, no, that can be.

sleek bough
#

Then ask the full question here when you know what the problem is

vale wren
olive mesa
#

use the good old print out every variable you can think of method

gray mural
#

then back

#

on second click

vale wren
#

thats what it should do, but tracking the position in the inspector it jumps to -180

#

though that shouldnt break anything because it's setting the rotation

#

just some weird behavior i found ig

gray mural
#

your code should be ok

vale wren
#

ok cool πŸ‘ sorry for the headache lmao, been tearing my hair out over what seems like something really simple

#

goin to bed, gn

gray mural
vale wren
#

thanks!!

olive mesa
#

yo there's hyperlinks in discord now?

#

what

gray mural
#

there were

olive mesa
#

never knew lol

#

that's neat

#

thanks google

gray mural
#

and it gonna show calls

#

now I have exception every update

leaden solstice
leaden solstice
gray mural
gray mural
#

I don't know how I haven't mentioned it.

tranquil sleet
#

having a bit of trouble thinking out how to actually handle this
any ideas on handling creating spaced objects rotated around an object in a circle?

#

visualization, equally spaced objects with a set distance from the edge of a circle, handled dynamically

#

what kind of proc gen are you looking for?

vast wigeon
#

First normal terrain and later add things like buildings trees ands enemies

tranquil sleet
#

no I mean like what algorithm?

vast wigeon
#

Noise?

knotty sun
# tranquil sleet visualization, equally spaced objects with a set distance from the edge of a cir...
tranquil sleet
tranquil sleet
vast wigeon
weak crag
#

While building a game we import a lot of different packages. My question is, how does Unity build take care about it? Do we need to remove all the junk folders when the project is finished? Will it reduce the package size? Is there any good practice to follow related to this?

tranquil sleet
gray mural
#

does WaitUntil return frame anyway?

#

no, it doesn't

#

it's like while loop, I see

swift falcon
#

In my game there is an object which can bee either open or closed. In a level there will be one closed and one open. How should I add these object in game by making two prefabs as open and closed or are there any way that I can set them at the beginning of a level

latent latch
#

Using a single prefab is fine, you'll have to flip some flag for each prefab object you place on the scene

#

and if you've any additional logic you can do it in start

gray mural
#

are those lines the same?

yield return new WaitUntil(() => _textInfo.characterInfo[0].origin != 0);
while (_textInfo.characterInfo[0].origin == 0)
    yield return null;
#

they should do the same, right?

#

because second one with while does throw more errors than lines of code in my script

#

and wait until works (somehow) normally

#

I see, damn unity forums and chatgpt lied me about that, it's

do yield return null;
while (_textInfo.characterInfo[0].origin == 0);
winged mortar
#

You'd have to check the implementation in code in order to determine if they are the same

gray mural
#

basically everyone has told they're the same

winged mortar
#

The post that you highlighted?

gray mural
gray mural
#

I have just searched for that forum

#

anyway I think I'm enough with working with TMP_Text

#

it's done so badly

#

how can built-in class have more bugs than every beginner's script

winged mortar
#

If you look at the specified thread one user literally says that they aren't equal

gray mural
#

620 lines of code just to overcome those bugs of built-in namespace

winged mortar
#

And another reply suggests that wait untill always has a one frame delay

gray mural
#

I have mentioned it sooner

winged mortar
#

Baste, angusbjones

#

Baste suggests but doesn't know (and I've seen his name around the forums quite a bit) so if someone like that suggests something you should definitely dig deepers

#

And Angus in that thread has figured out that they weren't equal

#

And he was running into problems because of it

#

So idk how you read that thread but it's definitely in there

gray mural
gray mural
winged mortar
#

That's because do while is the same as just doing

yield return null
while(!condition) yield return null
gray mural
winged mortar
#

I disagree

gray mural
#

also it doesn't repeat yield return null 2 times

winged mortar
#

Cognitive load in order to process a do while is significantly higher than to just look at two statements

#

But that's an opinion thing I guess

gray mural
#
do yield return null;
while (!condition);
gray mural
winged mortar
#

Not a guess, an opinion

gray mural
#

wait.

#

it returns once

winged mortar
#

I don't know what you are doing but this doesn't make any sense

gray mural
#

nice.

winged mortar
#

And as you can see you haven't proven anything (the times are also not accurate)

#

9ms difference for such a simple operation

#

Wed be looking at a microsecond difference

#

If even that

gray mural
#

ok, that just doesn't matter

#

I just think I should let my trashy game for a few years

wide dock
#

Idk what you're doing if you're trying to measure performance difference between a simple do while and while. It probably doesn't matter at all even if there is a slight difference.
Anyways, everyone knows that while is better than do while when it comes to simple loops...

gray mural
wide dock
#

I see

wide dock
ashen yoke
#

if you want to measure performance you just look at IL

wide dock
#

Also true

fervent furnace
#

while and do-while are not interchangable actually

#

you need to change the codes both inside and outside the loop to turn while to do-while or vice versa

swift falcon
ashen yoke
#

the only difference in IL is that while starts and ends with a branch and do only ends with it

#

rest is identical

gray mural
tawny elkBOT
cedar rune
#

hey, adjusting editor tabs make them flicker for some reason, any ideas on how to make it stop?

#

have disabled NVIDA for unity, but problem still remains

#

dunno if my graphic cards is just outdated or if a fix is available

ashen yoke
#

its just a bug

#

present is some unity versions

cedar rune
#

weird, no way around it? using 2020.3.45f1
my other devices share the same version, but dont have the problem there

ashen yoke
#

dont know

#

manifests for me some times, but in different scenario

#

probably something to do with vertex buffers overflowing

mortal harbor
#

Unsupported
This version of Visual Studio is unable to open the following projects. The project types may not be installed or this version of Visual Studio may not support them.
For more information on enabling these project types or otherwise migrating your assets, please see the details in the "Migration Report" displayed after clicking OK.
- Assembly-CSharp, "D:\Unity_project\Cooking_mania\Assembly-CSharp.csproj"
- Assembly-CSharp-Editor, "D:\Unity_project\Cooking_mania\Assembly-CSharp-Editor.csproj"

No changes required
These projects can be opened in Visual Studio 2015, Visual Studio 2013, Visual Studio 2012, and Visual Studio 2010 SP1 without changing them.
- Cooking_mania, "D:\Unity_project\Cooking_mania\Cooking_mania.sln"

how to fix dis

winged mortar
#

you can probably regenerate your csproj from your preferences

#

@mortal harbor

mortal harbor
#

hmm UnityChanThink

#

this is happening when i clicked install unity for visual studio

winged mortar
#

Have you followed the instructions from !ide

tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

mortal harbor
#

this happened

#

ohh i have to install game development thing from installer

swift falcon
#

Im getting a nullreferenceexception on the Vector3 newPosition line:

//in Building.cs:
private void Start()
    {
        buildingManager = FindObjectOfType<BuildingManager>();
    }
public void Place(string buildingName, Vector2Int position)
    {
        Vector3 newPosition = buildingManager.CoordinatesToWorldPosition(buildableTerrain, position); //here
        ...
    }

There's a BuildingManager gameobject in my scene which has BuildingManager script attached to it. For some reason buildingManager is returning null, even though it doesn't return null when I test it in Start() with if (buildingManager == null) Debug.Log("null");

The Building script is attached to a prefab, which gets instantiated whenever the player left clicks. I've tried using Awake instead of Start but that returns the same result.

Full error:

Building.Place (System.String buildingName, UnityEngine.Vector2Int position) (at Assets/Scripts/Building.cs:44)
BuildingManager.PlaceBuilding (System.String buildingName, UnityEngine.Vector2Int position) (at Assets/Scripts/BuildingManager.cs:52)
BuildingSelectionBox.OnMouseDown () (at Assets/Scripts/BuildingSelectionBox.cs:34)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)```
winged mortar
#

Do you call Place() on the newly instantiated Prefab right after isntantiating it?

#

You should test if Start() is being called before Place() in your prefab, the docs only say that Awake() and OnEnable() are called when instantiating

#

@swift falcon

ashen yoke
#

they are also only called if the prefab was active

#

if the prefab was intantiated inactive they wont be called until SetActive()

topaz ocean
#

If I have a Monobehaviour script that I want to require transform children with components that I can reference, is it better to create a prefab and assign references there or to create those gameobjects inside of the main script?

winged mortar
#

If it is always the same set of components

#

you should probably make a prefab

topaz ocean
#

Right now how I have set it up is by having 3 scripts, one for the main and 2 for children, the child ones have "requirecomponent" and methods to reference the required components, it just feels weird to have 3 monobehaviours for one purpose I guess.

winged mortar
#

I mean if its 1 purpose

#

then it can be 1 monobehaviour

#

but if those 3 monobheaviours do 3 distinct different things

#

or don't align in functionality at all, in such a way that you'd probably re-use them somewhere else

#

Then they should be 3 different ones :)

#

But you can always split / merge them later

topaz ocean
#

ah, I suppose they could be used separately

#

thanks

swift falcon
winged mortar
#

Then

#

You should test if Start() is being called before Place() in your prefab,

swift falcon
#

when using Awake, Awake is being called before Place, which is what its supposed to do?

winged mortar
#

Yes

#

Does the null check still pass?

swift falcon
#

well its not producing any errors anymore (for some reason)

#

thanks anyway

winged mortar
#

Welcome!

neat echo
#

if theres a better place to put this then someone lmk :]
what is camera space?

#

(specifically im confused by what the cameraToWorldMatrix is actually doing)

#

the docs reference camera space but idk what it is and i can't find anything online about it

ashen yoke
#

technically afaik camera never moves, the objects are transformed by matrix mutiplication

neat echo
#

im fine with it being abstracted away like it is in the docs, but im not sure what camera space is supposed to mean

ashen yoke
#

there is view matrix, projection matrix and objects matrix

#

well camera space is the local space of the camera

neat echo
#

screen space?

ashen yoke
#

no

#

this is related to 3d coordinates

#

which is what matrix describes

#

among rotation, scale and various sqews and projections

#

if you explain what you want to achieve i can point right direction

neat echo
#

im not really trying to achieve anything, im just following a paper and the mention of camera space came up

ashen yoke
#

screen space/ viewport space are 2d coordinate systems, local space or camera space is a 3d concept, afaik

neat echo
#

so is camera space just the position local to the camera's origin?

ashen yoke
#

relative to camera, if you transform the object to the camera space you would get its offset from the camera

#

i assume, i never tinkered with it, and i learned the theory quite a while ago

neat echo
#

ye that makes the most sense

#

thanks :]

winged sphinx
#
List<RectTransform> transforms = new List<RectTransform>(cardDesinationsObject.GetComponentsInChildren<RectTransform>());
        cardDestinations = new Vector2[transforms.Count - 1];
        for (int i = transforms.Count-1; i > 0; i--) 
        {
            transforms[i].SetParent(canvas.transform,true);
            cardDestinations[i - 1] = new Vector2(transforms[i].position.x, transforms[i].position.y);
        }

I'm trying to store the positions of some gameobjects in a grid layout group. This returns the same position for all gameobjects.

latent bear
#

these are for entering the collider and exiting the collider. Im unsure why they're linked in this way

    {
        if (other.CompareTag("Player"))
        {
            interactPrompt.GetComponent<interactionUI>().Dino = Currentdino;
            isInteractable = true;
            interactPrompt.SetActive(true);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            isInteractable = false;
            interactPrompt.SetActive(false);
        }
    }
prime sinew
#

How do you assign interactPrompt

latent bear
#

Using

public GameObject interactPrompt;
#

both of the dinos have seperate assigned interact prompts

#

probably should've made a thread for it, sorry haha

shell scarab
#

why is hUnit unassigned on the 3rd line?

1 bool result = subUnit is Harvester hUnit && hUnit.Carrying < hUnit.resourceCapacity;
2 if (result)
3   command = new HarvestCommand(hUnit, target);
#

as I understand it, hUnit is not assigned if subUnit is not Harvester, but line 3 is only called if that is true, so why does it say it's unassigned?

earnest gazelle
winged sphinx
#

I'm saying it could or it couldn't, depending on the use cases for each. There's very little "should" about programming.

tight fjord
#

Why can I not access my second script from my main script?
the value I want from my second script tells in the debug mode:
The identifier `Load_Save_MyDatasSCRIPT` is not in the scope
But why?
I also made a breakpoint on my second script and its getting a value in his integer, so I have no clue why I still can't access it from my main script?

#

I also made that the onclick of the button will execute the Secondscript first with the Integer: [HideInInspector] public int CurrentPressedButtonNumber = 0; ...to make sure that the value was given, before I try to call this value from my Main script:

soft shard
tight fjord
#

Yes. That why I made this debug test. The variable is outside, its in the "Load_Save_MyData.cs"

#

But its getting the values from there and after thus script is done, it should try to access it.

cobalt crest
#

Does anyone happen to know if I can enable .editorconfig analyzers to break the build on error, when building in batch-mode (cli)?

tight fjord
#

it is "1" but I cant get it, even if its public.

gray mural
#

Do I need to unsubscribe from this? If yes, how do I? Just -= instead?

_moveAction.started += _ => _moveCoroutine = StartCoroutine(Move(_));
simple egret
#

You can't unsubscribe from lambdas, you need a full method

leaden solstice
gray mural
#

or do I just make a method from this?

leaden solstice
#

Sure making a method works too

gray mural
gray mural
leaden solstice
#

Not much difference

gray mural
simple egret
#

They both compile to the same thing, IIRC

#

+= new Action(Bla)

gray mural
#

should Actions be declared before methods or after?

#

cause fields are declared first, then methods

leaden solstice
#

Action is type of your delegate

soft shard
# tight fjord Is this a Unity Engine bug? Cause "CurrentPressedButton Number = 1" and I just t...

Well I dont think I have the full context of your script, though there are often 2 common ways to access variables across scripts (there are many others, but at least these 2 are most common) - either by a direct reference, usually assigned in the inspector:

public class A : Mono
{
public int variable;
}

public class B : Mono
{
public A aRef;

void SomeFunc() {Debug.Log(aRef.variable);}
}

Or through the class directly, as a static reference, which cannot be assigned through the inspector:

public class A : Mono
{
public static int variable;
}

public class B : Mono
{
void SomeFunc() {Debug.Log(A.variable);}
}

What you have, looks like you made "aRef" but you never actually assigned it, but your watching the "variable" from A, not from a reference in B (if I am reading your watch list correctly)

simple egret
#

Action is the type, so depends on if you make it a field or property. So, along your other fields is fine

gray mural
#

why I cannot use non-static fields, methods or properties with Action?

simple egret
#

You're getting an error message aren't you?

gray mural
simple egret
#

Something static cannot reference something that's not static

#

It's not restricted to fields of type Action, all members follow this rule

proven path
#

Is the Start method immediately called after enabling an object for the first time, so that the main thread works like this?

public class SomeClass : MonoBehaviour
{
    [SerializeField] private OtherMonoBehaviour _other;

    void Start()
    {
         _other.enabled = true;

         // Now _other performs start operation

         // Do something 
    }
}
gray mural
simple egret
#

No, it's not

#

You should post the real error message, and the code

gray mural
# simple egret No, it's not

then why?

private Action<InputAction.CallbackContext> bla = _ =>
{
    _moveCoroutine = StartCoroutine(Move(_));
};
simple egret
#

Ah, yeah it's almost the same thing as the static/instance error. A field cannot reference another field in its initializer (after =). You access moveCoroutine in it, which is probs a field

leaden solstice
#

Because you are defining it with field initializer

gray mural
#

so should I make a method instead?

tight fjord
# soft shard Well I dont think I have the full context of your script, though there are often...

Do you even can use the Scripts directly without making a variable of it?

    Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
    public void _Start_A_New_Game_OnThisSaveSlot()
    {
        ButtonAudio_shortcut();

        SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber].SetActive(true);

        print("TTTTTest = " + Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber);
        StartCoroutine("VerzoegertesAusfuehren");
    }
simple egret
timber jewel
#

public class Gyro_script : MonoBehaviour
{
Vector3 rot;

void Start()
{
    rot = Vector3.zero;
    Input.gyro.enabled = true;
}

void Update()
{
    rot.y =- Input.gyro.rotationRateUnbiased.y;
    Debug.Log(Input.gyro.attitude);
    transform.Rotate(rot);
}

}

Is it possible to use gyro for positioning an object, If so Does anyone know how I can take this gyro script and make it position instead of rotation? (IOS if that matters) I tried to edit the script but it just didnt work and this is the original one

languid pilot
#

Is there a way to predefine how rooms made in tilemap looks and then randomly spawn them on map?

gray mural
simple egret
#

This restriction is in place so the compiler doesn't have to determine which field requires another to be set, before it's set itself, avoiding potential infinite loops (a field references another, which references the first field)

tight fjord
#
public class PressSavingSlot_AndStartNewScene : MonoBehaviour
{
    [SerializeField] private AudioClip audioclip_LightPressingSound;
    [SerializeField] private AudioSource audio_ButtonVolume;

    [SerializeField] private GameObject[] SaveSlotButton_Redbar;





    private void ButtonAudio_shortcut()
    {
        if (!audio_ButtonVolume.isPlaying)
        {
            audio_ButtonVolume.clip = audioclip_LightPressingSound;
            audio_ButtonVolume.Play();
        }
    }

    ///////////////////////////////////////////////////
    Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
    public void _Start_A_New_Game_OnThisSaveSlot()
    { //Audio Button Sound - Pruefen, Audioclip-laden UND abspielen:
        ButtonAudio_shortcut();

        SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber].SetActive(true);

        print("TTTTTest = " + Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber);
        StartCoroutine("VerzoegertesAusfuehren");
    }

    private IEnumerator VerzoegertesAusfuehren()
    {
        yield return new WaitForSecondsRealtime(1f);
        SceneManager.LoadScene(2);  // 2 = World Scene
    }
}
  • I'm not sure why the colors don't work, but the lower script here is that script what needs to access "Load_Save_MyDatas", for his "CurrentPressedButtonNumber" integer...
timber jewel
gray mural
tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

timber jewel
#

was the =- stupid?

red verge
#

how would i program a car building game mechanic like the game my summer car or mon bazou?

timber jewel
simple egret
#

Nah, it's interpreted as = -x

#

Unary negation

leaden solstice
#

More like it should format your code properly

gray mural
soft shard
# tight fjord ```cs public class PressSavingSlot_AndStartNewScene : MonoBehaviour { [Seria...

So you have Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
This just declares a variable of type Load_Save_MyDatas, but because theres no = and because its not public, the value of Load_Save_MyDatasSCRIPT is null until you set it to something - you then use it SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber], I would imagine this would cause a "Null Reference Exception" cause Load_Save_MyDatasSCRIPT is null, meaning you cant access .CurrentPressedButtonNumber, is this whats happening in the Unity console for you?

timber jewel
gray mural
timber jewel
#

oh okay

#

Thanks

leaden solstice
knotty warren
#

im new too sort of building proper ai for unity3d everytime i build zombie hordes or smthing like that they end up pushing the player and each other no matter what obstacle avoidance i have them set too?

timber jewel
#

no

#

sorru

#

I must have bumped phone

timber jewel
ashen yoke
#

try not using += , -=

#

avoid them

#

for now

timber jewel
#

so is =- Okay?

ashen yoke
#

dont use that either

#

you dont have a clear understanding of what they are doing

#

so dont use them

#
int foo = 1;
foo = foo + 2;
#

use this syntax

somber nacelle
gray mural
jade phoenix
#

how can i detect if the player collides with only the up facing part of the ramp?

#

cause currently they can do some weird wallclimbing abilities on the sides of ramps

tight fjord
soft shard
# knotty warren .

You could look into "flock AI" as well as "obstacle avoidance", it sounds like your wanting a similar system, to prevent pushing the player, you can either disable the collision interaction between them, or make sure each AI maintains a minimal distance from the player so they never actually get close enough to physically interact with the player, some AI might also use a "target priority" (donno if thats the correct technical term), basically if that priority limit is say 5, and you have 7 AI trying to attack the player, the other 2 will simply justt sit around and maybe look at the player but wont attempt to move toward it, until one of the 5 units leave or dies, allowing them to take one of the priority slots, this makes it so the player realistically is only fighting 5 AI circling them at a time

compact spire
#

Is there anything I can do for a top down 2d game to where I don't have to fight with the coordinate system as to what vectors are considered forward and up?

#

"forward" is currently Vector.right (all of my sprites point upwards), and the 270/-90 angle offsets are annoying to have to keep track of.

#

If I left the coordinate system alone I could rotate all of my sprites before importing, or make a custom importer to rotate them on import...

chrome berry
compact spire
#

@chrome berry, so make something like a wrapper for vector3?

#

and vector2

chrome berry
compact spire
#

"Since the map screen uses tilted non-iso sprites" That's an interesting look

chrome berry
#

Thanks. Unity's Grid component unfortumately won't do this for you, so I had to just brute force it

compact spire
#

Couldn't this effect be done just by modifying the view angle of the camera? I'm guessing the problem there is it won't be pixel perfect.

chrome berry
#

Yeah, pixel perfect look is lost when camera tilting, and movement causes jittering and shifting of the sprites.

oblique spear
#

Does anyone know a way to detect a collision from a child separate from the parent without writing a new script for the child? I know that the parent can detect the collision from the child but I want different things to happen when the child or parent collides with a specific gameobject. I tried some stuff with thisCollider but that for OnCollisionEnter and not OnTriggerEnter.

simple egret
#

If I remember correctly, as long as the rigidbody is on the parent, and there are colliders on the children, they'll all be part of a single collider, and all collision events will be bubbled up to the rigidbody.
So you could have one script on the parent, as long as it's along the rigidbody.

oblique spear
#

Yes I know but I want different things to happen when the parent collides with a gameobject or the child does

#

The only solution I know is an extra script for the child

simple egret
#

You need one script per child object. Or a giant chain of if-statements that switch on collision.thisCollider to know what's the collider on this object that was involved in the collision

oblique spear
#

Hmm I see. I wish I could just give the collider I want as the parameter Sadge

tight fjord
#

Why is my Text color always yellow, if I enter the color code of green?
and why does the color work, if I use "color.green" instead of the color value?

simple egret
#

Color takes values ranged from 0 to 1, float

#

Use Color32 if you need to use bytes

#

(they convert to each other seamlessly)

tight fjord
simple egret
#

I mean new Color(255, 0, 0) is incorrect

#

It should be new Color(1, 0, 0)

#

You're just passing a very powerful green (HDR color), but you're not seeing it

tight fjord
simple egret
#

They accept 3 or 4

#

4th is the alpha

tight fjord
#

4 = Alpha

simple egret
#

But it's the exact same

#

You're just passing the wrong range of values in it

tight fjord
#

alpha is 255 what means its completly visible.

simple egret
#

Not for Color!

#

For COlor, alpha at 1.0 is fully visible

buoyant crane
tight fjord
simple egret
#

It's just wrong

#

It should either be Color32 here, or use values ranging from 0 to 1

buoyant crane
simple egret
#

Yeah, that's fully white, and if you have HDR enabled you just flashbanged yourself

#

(passing values greater than 1 I mean)

buoyant crane
tight fjord
#

255 is the highest number

simple egret
#

Actually, in that forum post, the very next answer points out the mistake - always read further

#

We're talkning about code here, not the Inspector

#

The Inspector probably uses a Color32 behind, or a Color that gets remapped in the back

tight fjord
#

but I try to get that color values and its the same like in the inspector or every other Drawing Software (16, 255, 0, 255) = green

simple egret
#

My dude

#

You're not getting it

#

Each color component is a floating point value with a range from 0 to 1.

#

It's the thread you linked, but scrolled further down

tight fjord
#

but why was it yellow?

simple egret
#

Because you passed very high values that are invalid for a color that's not a HDR one

#

It's not always yellow when invalid though, it might be because some numbers are higher than others, it takes a specific tint that tends to go towards some color

tight fjord
#

wow, a simple "32" on "Color" changed everything.

#

that helped a lot, thanks.

topaz ocean
#

If I have a script with a reference to a component, and I want to represent a variable of the component as a local variable that updates the component when the value is changed. Is it better to have an accessor to the component field or should I have some method to synchronize the component and the local value?

boreal condor
leaden solstice
#

Dot

pure cliff
#

Is it possible to have AnimatorController modify variables of a MonoBehavior? Specifically, after a chain of animations have played out, I want to set Busy = false on the MonoBehavior

lavish frigate
#

Would anyone experienced with 2d game dev and procedural generation be interested in hopping on a quick call or chat? I have a few questions about approaches for level generation for my hobby project.

pure cliff
#

or some varient of that where I can have my monobehavior check in "yo did you finish yet, AnimatorController?"

pure cliff
pure cliff
lavish frigate
#

Yeah wave function collapse seems good, but i dont know if it works for a 2d platformer

pure cliff
#

its a very generic algo that largely can be used to do a lot of stuff, and solve a lot of stuff

lavish frigate
#

would you recommend applying it to a tilemap, or instantiate prefabs of all tiles

somber nacelle
pure cliff
#

So was hoping I could do it with AnimatorController as that actually delegates under what conditions a given animation is the last in the chain

#

I suppose I could make a generic 1 frame animation that is the "not busy anymore" animation, which I staple to the end of both chains, so I could have

A-B-Z, or A-B-C-Z, and Z has the event πŸ€”

somber nacelle
#

it's unlikely that there is any functionality for the AnimatorController itself to do anything to a MonoBehaviour or anything like that. you can always ask in #πŸƒβ”ƒanimation if you want help with something like that though

pure cliff
#

but before I do something hacky like that, this seems like something unity outta have support for

kindred reef
steady moat
steady moat
#

C# is very broad and you will learn more than what is necessary by doing a standard course while also not learning everything that you need.

steady moat
kindred reef
lavish frigate
# steady moat I strongly suggest that you use Tilemap.

Thanks, ill look into wave function collapse combined with tilemaps. Any recommended tutorial or material to learn and implement WFC? Right now im looking at a tutorial by sunny valley studios but it seems pretty outdated.

steady moat
tawny elkBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

steady moat
pure cliff
steady moat
lavish frigate
pure cliff
#

Oh actually, does GetComponent work by chance with polymorphism?

pure cliff
#

Like I have abstract class EntityBase, and then the actual MonoBehavior on my GameObject is BatEntity, and then the GameObject also has an Animator on it, which has lets say DoTheThingSMB StateMachineBehavior script on a cell

Is it possible for me to GetComponent<EntityBase> so I can have 1 single StateMachineBehaviour script that will be compatible with all my various Entity scripts I make?

pure cliff
#

noice

simple egret
#

Yes, it'll get any derived class that's on there. Also works with interfaces!

pure cliff
#

thank god, thatll make this a lot easier

#

I presume theres an event I can hook into for StateMachineBehavior that will just fire off once on finish or like, on transition out? Lets see here

steady moat
#

The StateMachineBehavior works pretty much the same as a standard MonoBehavior.

pure cliff
#

Looks like OnStateExit is what I want

steady moat
#

Oh, you mean event in that sense.

pure cliff
#

yeah unity's weird pseudo magic string name "events" they like to use

steady moat
#

I though you were looking for a way to subscribe directly to the StateMachineBehavior OnExit/OnEnter.

pure cliff
#

oh wait, these ones are actual override methods

steady moat
#

I guess they didnt want to make the same mistake then previously.

pure cliff
#

yeah haha

steady moat
#

Pretty awkward how the MonoBehavior works.

pure cliff
#

Does unity support INotifyPropertyChanged in some way? Specifically, is there a way to bind property of <component> to a variable of <MonoBehavior>?

#

I have my GameState object which I can have as a singleton or monobehavior or whatever, and Id like to ideally not need to write a buncha code that just handles writing GameState.SomeProperty <-> UIElement.Property, for dozens of properties

steady moat
#

You want to do MVVM ?

pure cliff
#

effectively, or anything approaching it where you can just be like "Yo, bind Component.SomeString to MyScript.SomeString"

steady moat
#

Unity does not really have the notion of binding integreated in it's Engine.

pure cliff
#

dang

steady moat
#

I guess UITool kit may have it now though.

#

Not ready to be use for Runtime interface yet.

#

Also, I suggest that you use other approach then MVVM and data binding.

#

Not that suitable for VideoGame interface as they are most of the time unidirectionnel.

#

You just add a layer of complexity that is unneccessary.

smoky ibex
#

I have a gameManager which has a method thats called SwitchState(GameState newState). The newState argument is a public enum that is in the GameManager class. I also have a button. In the inspector when i try to set the onClick event to switch the state of the game, the SwitchState(GameState newState) doesnt show up when I put GameManager gameObject into onClick thing. Does unity just not allow enums and structs as arguments for serialized events?

steady moat
#

However, you should sparely use event in such a way.

smoky ibex
steady moat
#

They are hard to follow because they do not appear in most IDE reference tool.

smoky ibex
#

Isnt it part of the button component?

steady moat
#

You can also circumvent the issue by specifically define your event.

smoky ibex
#

I've tried it, but to no success

steady moat
smoky ibex
#

Where would I put that?

steady moat
#

There is also the option of creating a UnityObject that handles the data.

steady moat
#

If you use proper formatted code I can rearrage your code to show you

#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

smoky ibex
#

What should i send, the GameManager script?

steady moat
#

The code in the screen shot obviously.

#

πŸ˜›

smoky ibex
#

So yeah

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class GameManager : MonoBehaviour
{
    #region Singleton
    public static GameManager instance;

    private void Awake()
    {
        if(instance == null) instance = this;
    }
    #endregion

    public static event Action<GameState> OnGameStateSwitched;
    public static event Action<GameState> PreGameStateSwitched;

    [HideInInspector] public GameState State;

    private void Start()
    {
        SwitchState(GameState.GameOver);
    }

    public void SwitchState(GameState newState)
    {
        PreGameStateSwitched?.Invoke(newState);

        State = newState;
        switch(newState)
        {
            case GameState.GameOver:
                HandleGameOverState();
                break;
            case GameState.InGame:
                HandleInGameState();
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(newState), newState, null);
        }

        OnGameStateSwitched?.Invoke(newState);
    }

    private void HandleInGameState()
    {
        //Mb add later
    }

    private void HandleGameOverState()
    {
        //Mb add later
    }
}

[Serializable] public enum GameState
{
    GameOver,
    InGame
}
steady moat
#
    public void SwitchStateToGameOver()
    {
       SwitchState(GameState.GameOver);
    }

    public void SwitchStateToInGame()
    {
       SwitchState(GameState.InGame);
    }

    public void SwitchState(GameState newState)
    {
        PreGameStateSwitched?.Invoke(newState);
        
        State = newState;
        switch(newState)
        {
            case GameState.GameOver:
                HandleGameOverState();
                break;
            case GameState.InGame:
                HandleInGameState();
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(newState), newState, null);
        }

        OnGameStateSwitched?.Invoke(newState);
    }
smoky ibex
#

Oh~

steady moat
#

An alternative is to create a "SwitcherStateHandleComponent" which can then be use to switch the state.

#
public class SwitchStateHandler : MonoBehavior {
  [SerializeField] private GameState switchTo;
  
  public void Switch(){
    GameStateManager.Switch(switchTo);
  }
}
smoky ibex
#

In my case it would be SwitchState() right?

steady moat
#

Yes

smoky ibex
#

Also, how would this resolve my original problem?

steady moat
#

And you would need to either make the GameManage as a Singleton, retreive the Manager through reference or use static reference.

steady moat
#

So instead of using the GameManager -> SwitchState(GameState state) you would be using SwitchStateHandler -> Switch() which should be serializable.

smoky ibex
#

But now, would i need to switch the value of switchTo via another script?

#

Cause all im trying to do is;

#
  • Press button
  • Switch to state
steady moat
smoky ibex
#

OOHHHHH

#

I think i understand

steady moat
smoky ibex
#

So, i put this handler on the button, set the target gamestate, and then call switch in the onClicked event, right?

smoky ibex
#

Hold on

#

Thank you so much

#

This has been tormenting me for like 5 days now. Thank you

fervent crow
#

What is the best place to ask a question about Visual Code Studio? I'm not new to game dev, have been using GameMaker for several years, but recently decided to learn Unity. I have set up everything and even watched videos online, but cannot seem to get Intellisense or Code completion working on Visual Code Studio.

#

I have VS Code as the default editor in Unity and have these extensions installed following different guides

#

Like when I type transform.Rotate, then there is no autocompletion with transform

soft shard
fervent crow
#

Is Visual Studio available for Mac?

#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

soft shard
fervent crow
#

Hmm let me see the VS Code guide here, I'm used to VS Code and it's better for me since it's universal and works on all systems and not just for C# but other languages too

soft shard
fervent crow
#

Yea thanks. It's weird that my VS Code is not doing code completion when I followed the exact same steps in the tutorial videos.

soft shard
#

Maybe you missed a step? Have you also restarted VSCode, and set it as the "Exertnal Tool" to open scripts in Unity?

pure cliff
#

Anyone here familiar with Zenject? Its proving to be a pain figuring out how I get dependencies injected into a MonoBehavior that is already placed on my scene, is this straight up not possible and instead I need to instantiate it through zenject from the start, via a prefab or something?

late lion
pure cliff
rain minnow
rain minnow
native copper
#

Hello i have a question, i have a wall made out of legos in my game and i want to make it so the player can blow up the wall and when they do the wall object gets destroyed but a bunch of lego blocks go flying from the explosion. i am just having trouble figuring out how to do that

shell scarab
#

Hello. Why would this first struct work in moving the unit, but this second one would not work in moving the unit? The problem seems to be in MoveCommand on the second one, it's time float never increases, I believe its being set to Time.deltaTime instead of increasing, but only in the second struct?

HarvestCommand: https://hastebin.com/share/abezuluhul.csharp (working)
ReturnCommand: https://hastebin.com/share/hivunegego.csharp (not working)
MoveCommand: https://hastebin.com/share/mafejivivu.csharp

#

I also know it has its start and end points set correctly.

#

Also, the Progress() method is called in Update() for HarvestCommand and ReturnCommand.

#

at first I thought it was for some reason creating a bunch of ReturnCommands or MoveCommands for some unknown reason, but that does not seem to be the case.

#

Okay, i found out what's causing the weird behavior but I'm not sure why. HarvestCommand has moveCommand as ICommand, but ReturnCommand had moveCommand as MoveCommand. Changing it to ICommand fixes it. But why would having its type as MoveCommand cause MoveCommand.time to not be able to be updated/saved/set?

quartz folio
#

If it's marked as readonly how could you be modifying its members?

pure cliff
#

Welp, I got my whole round system working, but its sort of made my characters movement across tiles pretty clunky, as each round causes a small hiccup in movement as the next movement is queued up.

I think I need to tweak the way I handle rounds to instead pre-calc literally everything that is going to happen for the queued up n rounds, and then issue all the actions in an array

white gyro
shell scarab
white gyro
#

It should but I can't tell from your code

#

It's a bit weird to mark the field as readonly but you modify its members anyway.

rain minnow
#

yeah, that defeats the purpose . . .

white gyro
#

I would even say the commands should be classes instead of structs but idk what your codebase looks like

bright heron
#

this is totally a cinemachine question but a coding one too but if im switching between 2 cinemachine virtual cameras, how do i keep the mouse position the whole time. Im trying to get the character to switch forms and the two cameras are different but when i switch it just returns to that old cameras position not the current mouse posiition

compact spire
#

Want some opinions on this route I'm going for with stat modifiers. I have a weapon prefab with a scriptable object asset attached to it for it's base stats, and another asset for modifiers (or multiple assets.. depending..) . When the object awakes I instantiate an instance of the base stats so I have a copy just for this object. I then do whatever math between the original base stats and the modifiers, and apply those stats to the copy. All methods and such for the weapon reference the copy I just modified. Since they are all assets based off of the same scriptable object, I can just use some operands to add or multiply the base values with the modifiers..... thoughts?

somber nacelle
bright heron
somber nacelle
bright heron
#

ope my b

white gyro
# compact spire Want some opinions on this route I'm going for with stat modifiers. I have a we...

Do you mean doing something like runtimeStats = baseStats + modifierStats? Because you'd want to overload the math operators for the ScriptableObject to achieve that.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading

compact spire
#

Yep, basically like that

#

My question was more on the scriptable object shenanigans I was doing

white gyro
#

Oh then I personally treat ScriptableObjects as immutable objects. So I avoid making a copy of it and modifying its value at runtime

compact spire
#

Yeah.. I wanted to exploit that a little

#

as long as you instantiate copies

white gyro
#

I would make a Runtime class counterpart to the stats ScriptableObject

compact spire
#

but then the operator overload won't work

white gyro
#

It can still work

#
// BaseStats is the scriptable object
public static RuntimeStats operator+ (RuntimeStats a, BaseStats b) 
{
  var result = new RuntimeStats();
  result.Attack = a.Attack + b.BaseAttack;
  result.Health = a.Health + b.BaseHealth;
  return result;
}
compact spire
#

yeah I would have to write a seperate operator overload

#

and it means I would need to make sure both overloads (runtime + so) and (so + so) are updated

white gyro
#

There are many ways to fix that (such as using interfaces) but it's not a hard rule. Use scriptable objects however you wish.

compact spire
#

wait.. if I have both the SO and the runtime class off the same interface, I can make the same operator work for both?

delicate delta
#

How can i make vscode suggest code?

compact spire
#

suggest code?

quartz folio
tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

delicate delta
#

thx!

sleek wind
#

I currently have code that moves a 3D object with a mouse click and drag. Can anyone help me with code that will restrict the movement in the Y-Axis?

#

Vector3 mousePosition;

private Vector3 GetMousePos()
{
    return Camera.main.WorldToScreenPoint(transform.position);
}

private void OnMouseDown()
{
    mousePosition = Input.mousePosition - GetMousePos();
}

private void OnMouseDrag()
{
    transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - mousePosition);
}
leaden solstice
compact spire
#

@leaden solstice ahh.. bummer

gray mural
#

In the code provided, when dir is (1, 0, 0), it returns (1, 1, 0), not (1, 0, 0)

Vector3 dir = callback.ReadValue<Vector2>();

dir.x = Mathf.Sign(dir.x);
dir.y = Mathf.Sign(dir.y);
buoyant crane
gray mural
buoyant crane
#

Which is different from the actual c# math class