#archived-code-general

1 messages · Page 234 of 1

lean sail
#

If theres nothing else happening in update then you can remove the update method. Whether or not you keep it as a monobehaviour depends on its use, like if anything will be calling GetComponent in hope of finding it. If it's not a monobehaviour you'll have to still put it on one (or else how would it run) and new it up

oblique spoke
#

You can DIY faster per frame loops, but I really wouldn't worry about this too early

urban lintel
#

My plan was to just have it be a visual indicator of its hp, with possibly some animations when it changes for now

#

So with an event, I'd just add a listener to the event from the player's hp script with no update right?

#

And then have some function that renders the new hp UI

#

For some reason I was conflating update with monobehaviour, I guess it makes sense for it to be a mono behaviour but simply not have an update

lean sail
#

You can invoke it with the old hp and new hp if some other systems need to know the old one, or the difference

#

Whatever script is handling the UI would subscribe to the event on the player hp script

thorn quartz
#

Heyo, Ive been searching on this topic for quite some time now and I am close to saying "this doesnt work. dont waste your time!". I am working on a game in which the character has to be able to pickup multiple items and have multiple animations for holding these. I thought it would be a smart idea to make my own editor extension in which I use a selfmade FK algorithm to use collision checks to wrap the hand around an object. All of this stuff works. The problem now is that Im unable to capture the pose and to write it into a humanoid animation. I need to blend animations in the end. I dont want to have a generic animation for the entire rig only due to the arm movement being a completely seperate thing. I have tried many things to capture the pose of all the hand transforms to turn them into a keyframe for a humanoid animation, but non seem to work for me :/ I hope someone else could shed some light onto the hole topic.

cosmic rain
#

Hmm. Nevermind. It's not what I thought it is.🤔

neon plank
somber nacelle
neon plank
#

Oh, thanks

sharp blaze
#

Hey guys,

The type or namespace name 'HmsPlugin' could not be found (are you missing a using directive or an assembly reference?

I got this error but the problem is I actually do have HmsPlugin .-.
IDE sees it and everything, its just when I'm trying to build addressables?

dull glade
#

So the problem I have is, I want to play a sound when a gameobject gets killed, but when the object is destroyed so is the audio, what is the way to get around this issue?

dull glade
#

That worked

languid hound
#

Working with rigidbody movement. Everything is fine except camera movement. Anyone know why its jittery?

playerCamera.position = player.position + player.transform.up * 0.5f;

I tred Update, FixedUpdate, LateUpdate and the rigidbody is interpolate

#

Okay nevermind for some reason positioning it at a transform that's a child of the rigidbody makes it better

leaden ice
languid hound
#

It was interpolate and I tried all the updates I mentioned but moving it to a transform that was a child of the rb worked

leaden ice
#

It also depends on how your script works etc

languid hound
#

You mention that I just tried moving to the rigidbody's transform's position rather than the rigidbody's position and it seemed to work

#

I didn't know they were different

hard viper
#

they are super different

#

rigidbody interacts with physics system, and writes to transform (frequency depends on interpolation mode, I think)

#

moving a transform does NOT move colliders. Moving rigidbody position does

#
transform.position += Vector3.one;
Debug.Log(collider.bounds.center - init); // this is 0,0 ```
#
rigidbody.position += Vector2.one;
Debug.Log(collider.bounds.center - init); // this is 1,1 ```
#

for camera movement, I normally use a kinematic RB on the camera, with rigidbody.MovePosition, and interpolation on

#

.MovePosition queues up a rigidbody, so next physics simulation, physics will tell RB to move smoothly from point A to B. It is planned to reach point B at start of NEXT FixedUpdate after that. Physics system will smoothly change the transform as it goes along

#

make sense?

low harbor
#

Halo guys. Asking about voxel data. I'm using struct Block. For context i'm making an autotile level design tool. Some of the calculations are stored in each Block, which includes multi array like public int[][] Compatible; (for each tile type, for each direction)
This is WFC but made into a sparse graph using dictionary
My question is, I will need to init the existing collection of Block, and u gotta make a copy, init the arrays, then set it back in
Wouldn't this make wasted allocations upon get block, init array, set block? The tool is editor only for now but some functions will be for runtime in the future

#

Maybe the central autotile processor should keep track of these helper arrays, which is what the original algo does. I thought moving these to each struct Block would make things more easier to read but, basically if someone would throw a rock at me for storing big arrays in struct and modifying it n setting to the collection all the time, i'll rework it

#

Or actually when i do Compatible = new int[n][] in a Block, this is actually a reference so when a struct is getted, ref types members of the struct are not "copied" all the time in memory?

leaden ice
#

Do you need jagged arrays here btw? Or would a multidimensional array work?

low harbor
#

It's a jagged array, each layer is for something different. It's not like [x][y]

leaden ice
#

WHy not have separately named arrays for each thing then?

#

are you getting much benefit from a single jagged array?

low harbor
#
Block b = new Block();
b.Compatible = new int[5];
blocks[pos] = b;

Block c = blocks[pos]
c.Compatible[0] = 42;
blocks[pos] = c;

In this case memory wise, b.Compatible and c.Compatible is the same thing right?

low harbor
#

This is only 1 of several arrays

#

Ok2 cool that's good then

leaden ice
open charm
#

Hello

#

I seem to be having problems with a coroutine

#
public void PlayerReflected(InputAction.CallbackContext context)
    {
        if(currentState != 2)
        {
            return;
        }

        if (context.performed && !MissionLog.GetInstance().isUpdating)
        {
            currentState = 3;
            StartCoroutine(MissionLog.GetInstance().UpdateLog("Reflect bullets back at enemies"));
            if(spawnCoroutine == null)
            {
                print("No");
                spawnCoroutine = StartCoroutine(SpawnEnemies());
            }
        }
    }

IEnumerator SpawnEnemies()
    {
        while(PlayerManager.GetInstance().vialPoint != PlayerManager.GetInstance().vialMaxPoint)
        {
            print("Yes");
            // if(tutorialEnemy == null)
            // {
            //     tutorialEnemy = EnemyManager.GetInstance().SpawnEnemy(0, new Vector3(3, -10, 0)); 
            // }
        }
        PlayerKilledEnemies();
        yield return null;
    }
#

Whenever the playerreflected is triggered

#

the game jsut crashes

#

Im not sure why

leaden ice
open charm
#

In the spawnEnemies?

leaden ice
#

yes..

#

you have a while loop that doesn't change anything inside it related to the conditions

#

it will run forever

#

hence crashing your game

open charm
#

I was considering that to be the problem but i didnt think it would crash the game if it just print lol

leaden ice
#

of course it will crash the game

open charm
#

Im tryna make it so that the coroutine would constantly spawn enemies whenever the player kills one

leaden ice
#

there's something you need to realize about your code in Unity. While your code is running, the entire game engine is paussed waiting for your code to finish running.
If your code doesn't finish running, the game is frozen forever.

open charm
#

Alright

grim kiln
#

for starters you could drop a yield return null; into your loop so it takes a break every frame

open charm
#

It causes an error

leaden ice
#
  • why do you want to remove it?
  • what error?
open charm
#

Hold on im removing it so i can copy the error

leaden ice
#

right now you have yield return null at the very end of the coroutine, which is pointless

leaden ice
open charm
#

Oh u mean put it in

leaden ice
#

put it INSIDE the loop

open charm
#

Oh

#

I misread

#

mb

#

ok wow

#

I get how it works now

#

thx

#

Another question:

#

If I assign a variable to a gameobject

#

and later on i destroy the gameobject

#

How do make the variable return to null

somber tapir
#

you can set it to null in OnDestroy()

#

but you shouldn't have to in most cases

leaden ice
#

however - variable == null will already return true for a destroyed object

#

but cs Destroy(variable); variable = null; would be a good practice in general

open charm
#

The problem is that the variable is only gonna be used on this scene

#

cuz its a tutorial

leaden ice
#

I don't really know what that means or why it's a problem

#

variables live in code, not in scenes

open charm
#

Cuz if I write the variable = null in the OnDestroy function, the variable might not be there in other scenes

somber tapir
leaden ice
rigid island
#

variables don't live in a scene

open charm
#

Alright so let me just give the current situation

#

So I have an enemy script that is gonna be the base for all enemies in the future but at the moment we are planning to use it for the tutorial. In the tutorial there is supposed to be an event where we would spawn one enemy, wait for the players to kill it, then spawn another one.

Initially, in order to make sure that only one enemy spawns and only when that enemy dies would another enemy spawn, I make it so that when the enemy is instantiated, I assign it to a variable. The problem is when the enemy is killed and the gameobject is destroyed, the variable does not return to null. This is a problem because the way i prevent multiple enemies from spawning and spawn a new enemy is by checking the the variable is or is not null.

I could change the code of the enemy behaviour by adding that on Destroy on function, but the variable that the enemy is assigned to might only exist in the tutorial manager's code and nowhere else; therefore if I were to add a variable = null in the onDestroy function and if the tutorial manager is not there, then I am afraid it will cause some issues.

mellow sigil
#

Comparing a destroyed object to null does work. If it doesn't work in your case then you have some other issue in the code.

leaden ice
#

anyway in general the approach to this is to have some kind of centralized EnemyManager or something, and have the enemies notify the enemy manager when they spawn and when they die.

open charm
#

I found another way around it but i found it rlly odd

open charm
leaden ice
#

in general it's not that odd. It only works due to some Unity magic. But normally you cannot expect variables to "become null" unless you explicitly set them to null.

open charm
#

Alright alright

#

Thx

#

Ill try to improve my code with the enemy manger later one

#

Also I have one last question

#

Atm the player code is divided into two due to some msicommunications with the team

#

One code manages stuff like movement and controls wehre as the other handles health and stat points

#

Do u think it is better to jsut merge it?

leaden ice
#

not necessarily

#

probably better to have that as two different components

#

Each script should generally handle "one thing"

#

Movement might be one thing.
Stats may be another

open charm
#

Alright

#

thx

#

Cuz i heard from a teammate that we should minimize scripts in unity?

#

to make it less slow

open charm
#

Ok then

rigid island
#

what you do with the script is far more important than how many scripts you got

open charm
#

He said that he wanted to create an enemy manager that manages every enemy's movements

#

And Im not experienced with unity

#

But that sounds very wrong

tired robin
#

yo i have a problem is anyone able to possibly help me

rigid island
tall scroll
#
int[] directions = tile.GetDirections();
Debug.Log(tile.Visible);
if (tile.GetVisible() & directions.Length != 6)
{

so both of these should return .GetComponent<Renderer>().isVisible, however they always return false... even if I can literally see the object

open charm
#

Rlly

#

Wont it like slow the code down tremendously if there are too many enemies?

spring creek
open charm
#

Interesting

#

I still have a lot to learn then

#

Do u have examples of games that uses it and games that do not?

spring creek
#

It's fairly common though. Someone else may have examples

#

Consider this though. Unity loops through every update and runs them in sequence already

open charm
#

Ye thats true

mellow sigil
#

Just a tip: you're nowhere near the level where you should be thinking about how design affects performance. That comes much later. For now just focus on finishing a game

open charm
#

Alright thx

somber tapir
somber tapir
tall scroll
#

I figured it out, it was actually running so fast (which I didn't expect) that it genuinely wasn't visible for that frame

tired robin
#

btw im a massive beginner

#

its this

#

when i click on it it references the line of code which has the problem but i dont know what to put

#

this is the line

tall scroll
#

the first two means you're missing a ;, probably at the end of the line

tired robin
#

and this

quartz folio
#

Your !ide looks oddly unconfigured

tawny elkBOT
tired robin
tall scroll
#

the second two is that your parameters don't have types

tired robin
#

it says this now

quartz folio
#

You need a functional IDE to program properly

tired robin
tall scroll
#

mm doing that will help a ton

tired robin
#

okay ill quickly do that and come back

quartz folio
#

Also, you shouldn't multiply mouse input by deltaTime

tall scroll
# tired robin

all of these are that you've put whatever ' ' is in the wrong place, either you've added one or don't have it. The IDE being set up will make that super obvious imo

tired robin
tired robin
#

okay im gonna use vs studio community instead of vs code

hidden flicker
#

This code executes almost instantly and never actually deals any damage.

leaden ice
#

When you do something like Debug.Log(intervalTimer); you should really do Debug.Log($"Interval timer: {intervalTimer}"); to make the logs more clear

hidden flicker
#

Ok turns out I forgot to make the player mortal so the damage works fine

#

It still runs far too fast though

leaden ice
#

also it sseems like you're doing frame counting here for some reason

#

instead of time counting

#

intervalTimer++ per frame means you're counting once per frame, in other words, all your things are expressed in terms of frames rather than in terms of seconds

#

And this... if((intervalTimer % interval).Equals(0f)) is... kinda silly

#

what you want is something more like this:

float timer = 0;
float timeRemaining = duration;
while (durationRemaining >= 0) {
    timer += Time.deltaTime;
    while (timer >= interval) {
      Damage(damagePerInterval);
      timer -= interval;
    }

    timeRemaining -= Time.deltaTime;
    yield return null;
}```
#

notice the use of deltaTime which means we're working in seconds, not frames

finite prawn
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class AttackRangeTrigger : MonoBehaviour
{
    public UnityEvent<Collider2D> OnAttackRangeTriggerEnter;
    public UnityEvent<Collider2D> OnAttackRangeTriggerExit;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        OnAttackRangeTriggerEnter?.Invoke(collision);
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        OnAttackRangeTriggerExit?.Invoke(collision);
    }
}

i get an error here, saying UnityEngine.object cant be converted to UnityEngine.Collider2D
is there anything wrong here that one could spot instantly?

finite prawn
#

18

leaden ice
#

which is?

finite prawn
#

the one in the last funciton

leaden ice
finite prawn
leaden ice
#

you have set it up as passing in None right now

finite prawn
#

i thought the invoke function passes the argument

leaden ice
#

you have assigned your function from the static parameter list

#

and have set None as the parameter

finite prawn
#

and what do you mean exactly when you say, dynamic parameter list

leaden ice
#

in the dropdown

#

if there's a function that takes a Collider2D, it will show up under "Dynamic"

finite prawn
#

ah yes

#

now there is a different error

strange gate
#

Do yall have a Microsoft visual studio? is it really important?

finite prawn
leaden ice
#

Rider or Visual Studio are the best

hidden flicker
#

PraetorBlue can I ask why you spend so much time helping people here

#

Like, is it your job? Do you work at Unity?

leaden ice
#

This is where I go to procrastinate from doing my real job, which has nothing to do with Unity, no.

rocky jackal
#

why does the first one work but the second one doesnt ? i just want to controll the emission of a particle system

mellow sigil
leaden ice
#

In this particular case the compiler happens to be over cautious and it would actually work, but that's because Unity set this up in an unusual way

heady iris
#

Structs are value types, so you always get your own copy of them. barrelSmoke.emission is a property -- a method that looks like a field. The method returns a struct, so you get a copy of that struct. Assigning to that copy would be pointless, and the compiler complains.

But these structs also have properties on them. When you set one of the properties, it calls some code to update your particle system. So it would work just fine.

#

It's very unintuitive.

heady iris
#

If the struct actually held data, you would need to assign it back after changing its fields.

#

But it doesn't. It just knows how to get and set data from the particle system

glad jackal
#

I'm trying to assign an event handler to a Panel so that when it becomes active I can initialize the values of the components. VSCode complains about this:

    Panel p = GameObject.Find("Date Time Panel").GetComponent<Panel>();

Saying that Panel is inaccessible due to it's protection level. I understand the error, but how can I accomplish this?

leaden ice
#

Is that something you created?

#

That is not a built in Unity class.

#

If it's a class you created, you forgot to put public before it

glad jackal
# leaden ice What is Panel?

Its what gets created when I use Unity editor to add a UI component to a canvas. I right click on the canvas, then UI -> Panel.

My research seems to Indicate that there is no such class in Unity, that instead what is created is a GameObject with a few other objects in it...

leaden ice
#

all that creates is a GameObject with an Image component on it

#

Panel is just the name of that option in the UI

glad jackal
#

Okay, so my UI is basically a series of panels and I turn them on and off as the user clicks through the navigation buttons. When one becomes active, I need to initialize the values of the various components.

I can't figure out howe to attach a listener to the GanmeObject so I can do something when it becomes active.

rigid island
leaden ice
#

Alternatively, just start whatever action you want to do from the code that is actually activating/deactivating them

glad jackal
leaden ice
glad jackal
#

Which is why I'm doing this

glad jackal
leaden ice
#

You should drag and drop references to these things directly in the inspector

#

That's always the preferred method

spring creek
glad jackal
#

I didn't think the inspector gave me enough control. I have a UI that allows a user to change date abd time, and I want to init it with the system date and time when it becomes active

spring creek
#

If it is initialized, it will return a reference. You can pass that wherever you need
Type myThing = Instantiate(myPrefab);

leaden ice
glad jackal
leaden ice
#

make a script that has TMP_Text and Slider references

#

assign them in the inspector

#

and make an OnEnable function that populates them as needed

glad jackal
#

One function per script?

leaden ice
glad jackal
#

Oh I guess I could use the same one and check for null

leaden ice
#

What are you expecting to be null?

glad jackal
#

If I have say 6 public TMP_Text variables, each one with it's own OnEnable script, I thought I need to populate 6 different fields for a script

leaden ice
glad jackal
#

Each one, when run, will only reference one of the TMP_Text fields, or so I thought.

leaden ice
#

II would expect a script like this

#

for a single panel

#

You might attach it to 6 different objects if you want

glad jackal
#

Oh, I think i understand...

#

The scriupt is attached to the Panel with 6 fields... Not sure why I wa confused.

After years of writing code, I am struggling with this thing where part of the "code" is dragging references around in the editor and the rest is coding.

leaden ice
#

It's just a form of dependency injection

glad jackal
#

But in the Start() method, could I just do this.OnEnable(myMethod). ???

leaden ice
glad jackal
#

I would expect it to attach an event handler to the GameObject so when it is enabled it runs a function

leaden ice
#

there's no need to attach anything else

#

OnEnable is one of the special Unity functions

#

like Start or Update

glad jackal
#

Oh okay.

reef garnet
#

So what would everyone say is the best way to convert a Vector 2 to an angle 180degree or 360degree where I could also set the origin point (AKA the 0 degrees)

This is what I have for the pure conversion

    {
        float output = Mathf.Atan2(input.y, input.x);

        return output * Mathf.Rad2Deg;
    }```
glad jackal
#

So even easuer then? Just add an OnEnabled() and put my initialization cpde there?

glad jackal
glad jackal
tired robin
#

Hello does anybody know what is wrong with this?

deft timber
#

with what?

latent latch
#

maybe

tired robin
#

this code

deft timber
#

ow this code yes

tired robin
#

im new and not sure what is wrong

deft timber
#

well you got all the errors

#

in the console

#

saying whats wrong

tired robin
#

and i cant clear the console list

latent latch
#

looks like you dont have your editor set up correctly

spring creek
latent latch
#

oh it's vscode well I've no input for that except oh no

tired robin
#

i talked to somone on here before about it and im not sure how to set it up correctly at all

tawny elkBOT
tired robin
deft timber
#

never said that

tired robin
#

oh okay

spring creek
tired robin
#

ah ok

#

sorry

latent latch
#

vscode is fine and I use it, but I don't have it hooked up either. ;p

#

is support still going for it?

spring creek
latent latch
#

I should probably look into it then. VS actually starting to be a little too much on my mem

#

more that unity is taking like 6 gigs now

tired robin
#

i followed all the steps you said to set up the editor and i have already done them all

pine arrow
#

I am not sure if this is the channel to do it but I need help with my Game Scripting final

tired robin
#

and everyone keeps saying its not setup correctly

spring creek
tired robin
deft timber
#

hit the regenerate project files, and make sure vs code is selected as external script editor in external tools

spring creek
tired robin
spring creek
deft timber
#

Edit->Preferences->External Tools

spring creek
tired robin
spring creek
deft timber
#

can you show your external tools?

tired robin
spring creek
deft timber
#

then i'd suggest:

  • hit the regenerate button
  • close unity, close VSC
#

open unity, then Edit->Open C# Project

tired robin
#

okay im doing that now

deft timber
#

if it's still not working then you did something wrong, did you install the vsc extension for unity?

tired robin
#

is that the problem?

spring creek
#

Yes

deft timber
#

then you lied about following the ide configuing steps

tired robin
#

okay

deft timber
#

xd

#

you said you read it all

tired robin
spring creek
#

The Unity extension in vsc is what they meant though

tired robin
#

oh yes i have that then

spring creek
tired robin
#

oh ok

#

yes ive done that tho

#

its a problem with the actual code i think

deft timber
tired robin
#

my code is wrong

#

look

deft timber
#

that is not related to the fact that your IDE is not configured

tired robin
deft timber
#

with IDE configured you would have errors underlined

#

etc

tired robin
spring creek
tired robin
#

ive followed all the steps and tried to do it for ages

spring creek
deft timber
#

do what they suggest

#

they know what to do

tired robin
#

alr

#

this is the problem i think

spring creek
# tired robin

Remove the Visual Studio Code Editor package.
But that shouldn't be the issue

tired robin
#

okay

spring creek
#

Oh, you may have the Engineering feature, which will prevent you from removing it

tired robin
#

it wont let me remove anything

spring creek
tired robin
spring creek
deft timber
#

actually maybe forcing a recompile (fixing errors) will fix the IDE if he has done all the steps correctly 🤷

tired robin
deft timber
#

yes your code is wrong

spring creek
#

True. Just comment out all the code and try to compile it then

deft timber
#

but you need to configure your IDE anyway if you want to make your life easier

tired robin
#

i have made an error in my code according to the console errors

spring creek
deft timber
#

your code issues are not related

#

to what are we talking to you right now

tired robin
tired robin
spring creek
tired robin
deft timber
#

no, comment out your code

spring creek
tired robin
#

okay ive commented it all out

tired robin
spring creek
tired robin
#

yes

#

okay it lets me play

spring creek
#

Ok, now regenerate the project files one more time? Not sure

tired robin
#

okay

#

i click it and the button has the click animation when i click it but nothing appears to happen or change

deft timber
#

now click Edit->Open C# Project

tired robin
#

done it, it now opens vsc

spring creek
tired robin
#

okay

spring creek
#

If not, truly sorry, I just don't know

tired robin
#

ah alr thx

#

ima uncomment it one file at a time

#

found these errors after uncommenting the inputmanager

#

oh shit thats cos i need the other files lol

spring creek
spring creek
tired robin
#

yes

#

okay i uncommented playermoter and now i get these errors

spring creek
#

Show line 24

tired robin
#

alr

spring creek
#

Look at lines 14 and 15
But also, that is PlayerLook, the error is from PlayerMotor

quaint crypt
#

Hello,

I want to move my project from one pc to another.
I have git initialized in my project, pushed and pulled the code, everything is fine.
Until I try to open the project on my other pc, there are prefabs with broken links, scripts missing from gameobjects etc...

Why is this?

Am I perhaps missing some essential cache files or something? This is my .gitignore: https://paste.ofcode.org/3JBGJynzD7j8weGczYvjsK
Should I un-ignore some files?

What else could be the reason?

Thanks in advance!

spring creek
# tired robin

Oh, you also have a sentence outside any comment on lind 16 haha

tired robin
#

oh

spring creek
quaint crypt
tired robin
#

they are all from player look

spring creek
tired robin
#

should i just rewrite playerlook and start again

spring creek
quaint crypt
tired robin
#

there is still errors

spring creek
tired robin
#

okay i fixed the bracket error

#

so strange

#

everytime i add a comma here an error goes

spring creek
#

You should not have deltaTime in any of those lines there

tired robin
#

what should i use instead

spring creek
tired robin
#

still these errors

rigid island
#

!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

rigid island
#

configure your IDE

#

you're still missing a )

rigid island
#

line 20 also

tired robin
#

okay i only have these errors now

#

this is my code

#

not sure how to fix those errors

leaden ice
#

!ide

tawny elkBOT
leaden ice
#

right now VSCode is not showing you errors etc

#

this is going to make it nearly impossible for you to work efficiently

tired robin
rigid island
tired robin
leaden ice
tired robin
#

i have seletcted everything it told me to in unity

tired robin
spring creek
#

We made sure the package is correct, the extension is right, it is selected in external tools, and clicked regenerate project files

tired robin
#

yes

rigid island
spring creek
#

Also, they say there is no sdk error

tired robin
#

i click regen project files and nothing happens

rigid island
tired robin
rigid island
#

screenshot output windoow in vscode

tired robin
#

this shows up

spring creek
#

You said there was none

#

That is almost definitely the problem

tired robin
#

oh i feel so dumb lol

#

i was looking for the error in unity

#

okay im installing the .net thing

spring creek
#

Restart your computer after

tired robin
#

okay

#

okay i restarted and im back in unity

#

okay it is now highlighting errors

spring creek
#

Yeaaay.
If you hover over those errors, they will explain and maybe give a fix

tired robin
#

i still dont really understand the errors

spring creek
#

move is completely different than Move

tired robin
#

I have changed the capitalisation of move and it is still highlighted

#

i have no clue

spring creek
#

controller.Move
Not controller.move

tired robin
#

yes that has worked

spring creek
#

And that error you hovered over clearly says you can't have public there

#

So remove public

tired robin
#

so its just void

spring creek
#

Wait... what is happening there? I misread

#

Remove PlayerMotor.

tired robin
#

okay

#

should this vector be vector 3

#

because its not really referencing anything

spring creek
#

You need to just do a basic c# course.
Almost every single error is just not knowing the language
https://www.w3schools.com/cs/index.php

Method declarations need a type. Not just the variable name

tired robin
#

yea i am really new to programming

#

i have done a bit of python before

spring creek
#

To be clear, there needs to be two words for each item (between every comma), not just one

tired robin
#

alr

rigid island
tired robin
rigid island
#

eg.
you need to specify types when you make vars

spring creek
tired robin
#

its just that ive just started gcses and soon i want to use unity for once ive finished them

rigid island
#

you cant just do
function (3,"string")
end expect it to know what u need

tired robin
#

yea

rigid island
#

you need function(int myInt, string mystirng) <- not real c# code : )

tired robin
#

ah alr

#

yes i need a proper course on it

#

ima do everything on that w3 schools link

rigid island
#

yes def

tired robin
#

thankyou so much for your help though

#

brilliant community

fluid lily
#

Okay so I have a statically managed ID struct. I want to keep it's functionality for other structs, without having to copy it over and over. Right now I am thinking of just

public ManagedID{
    public int Value;

...


public struct MyID{
    public ManagedID Value;
}

and then add proxy logic from MyID to ManagedID. I am not sure if this would break the whole use structs for one simple type thing. Like what is the size difference of a struct holding a struct holding an int, vs just a struct holding an int?

Is there a better way of doing this?

maiden quail
fluid lily
#

Ah sorry the ManagedID is a struct also

#

As I can't inherit from a struct wrapping it seems the best approach.

#

Otherwise I could make converters.

#

I think keeping the logic inside of MyID is better than having external logic that connects the two.

maiden quail
#

Ah yes, then if ManagedID holds nothing else but a MyID then it is the same size as MyID and therefore the same size as int.

Yes I agree, keep the logic in one place. I'm not entirely sure what you're trying to achieve but be careful of over-engineering what might be a simple solution.

tall scroll
#

So I googled and found out that you can’t create gameobjects in anything other than the main thread, so no multi threading or async, but how does that affect coroutines? Are they also not considered the main thread?

somber nacelle
#

coroutines are on the main thread

tall scroll
#

Oo ok, I’ll have a play with those then

somber nacelle
#

also there are tools like unitask and unity 2023's Awaitable class that allow you to use async/await easier

#

and the jobs system for some multithreading stuff too

ornate perch
#

Question for general, I know custom editors exist as a concept you can do. But is there a way without using one to like create sections to block out my inspector for scripts

void basalt
#

the main bottleneck of unity applications exists in the random access nature of object oriented programming. dots fixes that, if you really need the speed.

soft shard
# ornate perch Question for general, I know custom editors exist as a concept you can do. But i...

Yes, depending on what you mean by "block out" - you can use the [Header] attribute to organize things, and [Space] attribute to add empty lines, both will be applied to the variable its used next/above, and you can also use [System.Serializable] on a class that does not derive from MonoBehaviour to display it, for example:

[System.Serializable]
public class Person
{
[Header("Basic Details")]
public string firstName;
public string lastName;
[Space]
public string job;

[Header("References")]
public GameObject prefab;
//etc...
}

public class SomeMonoForInspector : Mono
{
[SerializeField] Person someoneImportant;
}

You can also use public instead of [SerializeField] but with the latter attribute, someoneImportant can remain private and still show up in the inspector - the added bonus of using [System.Seriaizable] on a class as well, means you can collapsee itt in the inspector - beyond that, you may need a custom property drawer or Editor window

ornate perch
#

mmm that is what i was already using, was hoping there was at least subheaders or something

soft shard
# ornate perch mmm that is what i was already using, was hoping there was at least subheaders o...

No subheaders that im aware of at least, though you can also make your own attributes with just a few lines of code, maybe that is what you might be looking for? For example, if you wanted to make an attribute to have a field as "readonly": https://vintay.medium.com/creating-custom-unity-attributes-readonly-d279e1e545c9 - you could probably do something similar with the EditorStyles class to add subheaders, it is custom but may not require a full editor for it - with [System.Serializable] you can make sections collapsible, which maybe could also help

Medium

ReadOnly is a common name for an Attribute that makes a serialized field non-editable in the Unity Inspector, while still being visible.

ornate perch
#

hmm maybe

#

and yeah ive done some editor scripting

#

and i really like that you can make boxes and compact things into spaces

#

and was hoping it was possible to do that as well without needing an whole editor script

#

but maybe i just make one

soft shard
#

Yeah, sadly there isnt too much extra design functionality im aware of with GUI for the inspector, without getting into custom editor scripting - I THINK maybe you can do stuff with UIToolkit now, but I havnt looked into it in a while

ornate perch
#

ill take a look into it

rugged storm
#

Im making a noita/falling sand type game and currently each particle is a class, i want to render the map via a tile map but how do i reference a specific tile from the class?

latent latch
#

seems expensive

rugged storm
#

what other way should i do it?

latent latch
#

haven't actually played it but if I were to take a jab at it I'd do it like fluids

#

I'd expect there to be blogs about it, but ideally you'd want to render as much and fake/combine collision with larger groups

#

actually, sounds like something you'd attempt with the jobs system

#

and there's that

rugged storm
#

inparticulear here i was just currently trying to figure out a good way to (within unity) render a given array of tiles with either associated textures or simply just a color.

#

regarless of the underlying simulation stuff which i have been looking at things to produce, i just dont know the best way to show the resulting pixels to the screen in a efficient way

#

should i use a raw image or tilemap, etc...?

latent latch
#

Not too sure about tilemap, but sprite renderer does batch pretty well for individual GOs with similar sprites and materials

#

the problem beyond rendering independent quads is how you're going to batch it all. Ideally you need a way to cluster them instead of always being independent verts, using graphic instancing or such as an example

#

I'd probably do some compute buffers and combine verts when pixels are neighboring like he does in the video

#

Actually, it looks like he's simulating it all on the cpu. Pretty crazy, but I'd probably attempt it via compute to cluster it.

rugged storm
#

also btw my game wont be as large as noita, ill only be readering say.... how many units can a 2d camera with a size of 40 see? at any given time

tardy moss
#

How do you guys handle code changes between unity major versions ? Do you just accept that an asset is now dead and grief for it or you try to convert it to a new version if there are even some guides for upgrading code around or you just try to finish a project in a year so this is never a problem ?

rigid island
tardy moss
#

I always have this problem when I come back to unity of assets being gone in new versions, some big features (like the free controllers we used to have in unity 4 ot 5) being gone, some new big features replacing them (have to relearn) and most of the code not compiling between major versions

#

ALso if you upgrade an asset it's gone forever since the new version will rewrite the old one in unity cache so once you switch to says 2022.2 the 2020.3 versio of says playmaker is gone forever. basically I'm scared of returning to unity because of that but mostly because of hacving to upgrade all my old code and old unity store assets to the 2022.2 code api...

latent latch
rugged storm
#

I figured out the tile maps, (just having a single white tile and using set color on them as I can easily set a color in the constructor for each type of tile)

#

Plus I have no clue how writing shaders and such works currently

latent latch
#

Seems similar to sprite rendering batching. Keep it in chunk mode and it'll do most of the dirty work for you

ocean elk
#

Hey! I need to implement google account linking to my Unity app for Android so that all the data will be transferable from one device to another. What is the way to go here? I've watched videos about Unity Cloud system and Firebase Realtime Database but which way is better in my case?

rigid island
ocean elk
rigid island
ocean elk
rigid island
round violet
#

Is there a way to create "custom structures" ? (Like UE if anyone knows)

rigid island
round violet
rigid island
knotty sun
#

Ah, I think you may need ScriptableObjects in Unity

round violet
rigid island
#

oh true try SO

round violet
#

Im just asking if its only in c#

rigid island
#

visual asset idk what you mean by that

knotty sun
#

I'm guessing he means a physical asset with a custom structure, that would be a ScriptableObject

somber nacelle
earnest gazelle
#

For each point in 3d world, an icon, a text and a progress bar should be rendered.
They should be in world space.
How do you prefer to render them?
A world space canvas
Sprite + text mesh
?
The number of points can be large e.g. more than 1000. I want an efficient optimized way
If I choose canvas, I have to sort them correctly so that they can be batched. For example, first Images and then all texts

deft timber
#

Is this a job interview task or what?

lunar python
#

Anyone experienced in unity 2d can help me?

I am currently making 4 layers of Tiles in my game, which is ground, groundtops, groundcollidable, and ceiling, so that my characters can pass through the leaves of those trees. But I want all of the leaves of a tree to fade out when I inside those leaves. I am learning this because in the future I will have roofs, dungeons and stuff on the ceiling to create a realistic experience. I see videos on Youtube about fading a ceiling but the ceiling they design is a whole prefab not 9 blocks of tree leaves put together like mine. Is there any way I can do this? Do I need to find all adjacent leaves using a Disjoint Set to fade them out or is there an existing function in Unity which allows me to do it? Would setting up a Shader be tricky? Anyways thanks for your help.

deft timber
lunar python
#

well both code related and rendering related

#

i dont know where to put this question

rugged elbow
somber tapir
#

try putting FollowTarget() into LateUpdate()

surreal swan
#

Has anyone has this issue before ```Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/GraphicRebuildTracker.cs(24,32): error CS0117: 'CanvasRenderer' does not contain a definition for 'onRequestRebuild'

#

My unity ui is inside a package, I did not modify it or anything, so I don't know why I can't compile my project

#

This only occurs when I try to compile (Apple Silicon)

#

Does not occur when playing in Editor

#

My packages folder cannot be opened, nor I can search things in Packages

#

I am reinstalling Unity in hope it will fix my packages bug, it seems my packages are corrupted

wide mural
#

can anyone help with asynchronous scene loading, i know im doing it wrong but im rly struggling to understand
been looking at tutorials but yeh

nova turret
#

something that I usually do is request the active scene and put it in a variable before loading a new one

#

that way after I know it is loaded, I can just tell it to deload the variable

#

but you are also not waiting for the loading to be finished I think

#
  AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2");

        // Wait until the asynchronous scene fully loads
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
wide mural
#

Do i have to set the new active scene somewhere?

steady moat
wide mural
nova turret
wide mural
#

i've done this but it never unloads my first active scene

steady moat
wide mural
#

but i can try again

nova turret
#

what does your code currently do Lea? Does it not look like it does anything?

steady moat
steady moat
#

You do in the dotween

wide mural
#

But here it never unloads the first active scene

nova turret
#

okay yea

wide mural
#

it does load the new scene

steady moat
wide mural
#

why so?

nova turret
#

so at the top of your code where you transition save the current active scene before loading a new scene in a variable

steady moat
#

Because, you want to have an empty scene in between

nova turret
#

at the top of your routine*

steady moat
#

Unity is kinda dumb and only clear correctly memory with an empty scene inbetween

wide mural
#
    private IEnumerator TransitionCoroutine(string nextScene)
    {
        var scene = SceneManager.GetActiveScene();
        asyncLoad = SceneManager.LoadSceneAsync("TransitionScene", LoadSceneMode.Additive);
        asyncLoad.allowSceneActivation = false;
        LeftToRightAnimation();
        yield return SceneManager.UnloadSceneAsync(scene);
        yield return SceneManager.LoadSceneAsync(nextScene, LoadSceneMode.Additive);
        RightToLeftAnimation();
        yield return SceneManager.UnloadSceneAsync("TransitionScene");
    }

    private void LeftToRightAnimation()
    {
        fadeOut.gameObject.SetActive(true);
        fadeOut.DOAnchorPosX(-600, 1f).SetEase(Ease.InOutSine).OnComplete(() =>
        {
            fadeOut.gameObject.SetActive(false);
            asyncLoad.allowSceneActivation = true;
        });
    }

nova turret
#

oh yea I see

#

so it still doesn't work?

wide mural
#

nope

#

this is on a dontdestroyonload maybe its because of that? i dont know never touched async haha

wide mural
nova turret
#

nah if it was destroyed it wouldn't work

steady moat
#

And what exactly is happening ?

wide mural
steady moat
#

Because, it does not work can mean a lot of theings

wide mural
steady moat
#

What is the current loaded scene when at the end

wide mural
#

I can see the transition scene loading in between so that works and unloads fine

steady moat
#

What is the transition scene ?

#

Both scene are loaded ?

wide mural
wide mural
steady moat
# wide mural

At some point, both scene are in loading, it shouldnt happen.

wide mural
#

but isnt that the point of additive async?

steady moat
#

Also, we do not know what you current code is

wide mural
#

so its smooth?

#

I literally just sent my current code

steady moat
# wide mural so its smooth?

You do not want them to be loading at the same time, the loading of the next scene should only start after the transition

steady moat
wide mural
#

Yeah

steady moat
#

Is it possible that you execute the code twice ?

wide mural
#

Im not

steady moat
# wide mural Im not

Then remove part of your code till you have the minimum working. Then build one step at a time

desert blade
#

canon event of going back to old projects and cringing at them

#

i was a fool

rustic arch
#

Anybody willing to give a hand of help with the unity profiler please? 😭

#

Been looking at a lot of tutorials and can't understand a thing from what I am looking at

#

For example this spike where I was just looking around. I got no idea on what to look at

steady moat
rustic arch
#

So I'm trying to build with profiling but I'm getting tons of errors on shaders.

#

Don't really got any idea on what it means

rugged elbow
earnest gazelle
#

Is there any tool to convert digits 0-9 for a specific font (text mesh pro) to a sprite sheet?
I don't want to use text mesh pro component, instead I would like to have a sprite for it

steady moat
rugged elbow
#

I tried putting the suggested function in LateUpdate but the player becomes jittery instead instead of the UI

somber tapir
# rugged elbow

is the camera parented to the player, or the player parented to the camera?

rugged elbow
#

@somber tapir Also, the child camera is used by the crosshairs

fringe ridge
#

What approach would you guys suggest for this? I need to rotate players when dragging. When it was one - it was fine, i just added a collider on my second camera, and calculated the drags from there. Now i need to be able to do it for multiple players.

#

on each platform there appears a player

#

i was thinking to calculate the drags from player capsule colliders, but that doesnt seem to work

#

okay, nevermind 😄 figured it out

flat granite
#

did i put it in the wrong order? it should find anything more than 0 and less than 5 but i have this error instead

#
     for(int y = 0; y < VoxelData.ChunkWidth; y++){
      for(int x = 0; x < VoxelData.ChunkHeight; x++){
      for(int z = 0; z < VoxelData.ChunkWidth; z++){
        
        AddVoxelDataToChunks (new Vector3(x, y, z));
        
       }
     }
   }
  }
//makes sure the faces are drawn and arent drawing outside of the array //
   bool CheckVoxel(Vector3 pos){
    int x = Mathf.FloorToInt(pos.x);
    int y = Mathf.FloorToInt(pos.y);
    int z = Mathf.FloorToInt(pos.z);
     if (x < 0 || x > VoxelData.ChunkWidth - 1 || y < 0 || y > VoxelData.ChunkHeight || z < 0 || z > VoxelData.ChunkWidth)
     return false;
    return voxelMap[x,y,z];
   }

  void AddVoxelDataToChunks(Vector3 pos){
    for (int p = 0; p <6; p++){

    if(!CheckVoxel(pos + VoxelData.faceChecks[p])){
    for (int i = 0; i <6; i++){

      int triangleIndex = VoxelData.voxelTris [p, i];
      vertices.Add (VoxelData.voxelVerts[triangleIndex]+ pos);
      triangles.Add (vertexIndex);
      
      uvs.Add(VoxelData.voxelUvs [i]);

      vertexIndex++;
      
      }
    }
  }
} ```
#

this is my code^

leaden ice
rugged elbow
#

In case Gruhlum isn't here, can anyone else help me with my current camera issue above?

#

@somber tapir Any clues?

#

Sorry for asking often, I REALLY want to get rid of that jitter so I can advance

leaden ice
# rugged elbow

looks like your player object is moving via Rigidbody and does not have interpolation enabled.
Enable interpolation to fix it.

#

I will also say your camera script is weird as it seems to be moving the camera in both Update and LateUpdate. Why not just pick one?

#

Or better yet - why not just use Cinemachine?

knotty sun
rugged elbow
rugged elbow
leaden ice
leaden ice
somber tapir
leaden ice
#

I'd recommend LateUpdate but yeah

rugged elbow
#

Now both the player and crosshairs are jittery. Does that mean I'm on the right track?

somber tapir
leaden ice
#

well theoretically they're adjusting for framerate with deltaTime here transform.localPosition += new Vector3(x, y, 0) * speed * Time.deltaTime;

somber tapir
#

But it is still gonna be different. Imagine you have 1 fps vs 10 fps, after 0.5 sec with 10 fps the ship will have moved already a little while with 1 fps it is still standing still. Their velocity will be the same after 1 second, but not their positions.

leaden ice
#

If the speed is not constant, yes

#

However if they move in FixedUpdate they will need to do visual interpolation

#

it would be easier to use a Rigidbody at that point and rely on the built in interpolation

somber tapir
rugged elbow
#

Nope, the main camera is the only one that has the script

rugged elbow
#

I'm getting a little desperate trying to fix this stupid jitter with what little Unity knowledge I have

upper crow
#

ik this is unity but does anyone know anything about batch coding ?

flat granite
knotty sun
slim spruce
#

hi! i've made my own tweening library and i'm trying to get a 2d sprite to rotate clockwise, from 0/360--> to 180, and then, continuing clockwise, to 360/0, yet i can't exactly figure out how to do it. any ideas about what i'm doing wrong?
https://paste.ofcode.org/FxkGPdCU5m5CDUPnYx3hA5

leaden ice
#

"SecretLerp" isn't exactly illuminating, for example

slim spruce
#

right, so what's going wrong is the tween from 180 degrees to 360 / 0.
secretlerp isn't relevant for this problem, it's just a way to lerp between 2 values while also using different kinds of easings. it's a secret

sage latch
#

I'm trying to create a script to set a rect transforms size to the safe area, but cannot for the life of me get the scaling correct. This is what I have currently https://gdl.space/pojanuyida.cs and it's always slightly wrong (yellow is expected, red is actual)

leaden ice
#

it seems to be exactly what the problem is based on the explanation here

#

anyway i wouldn't interpolate euler angles, that's a recipe for sadness

#

I would interpolate the quaternions

#

using Quaternion.Slerp

slim spruce
leaden ice
#

why do easingFunction(t) three times when you could do it once and reuse the result 😜

slim spruce
#

i'll do that instead 😅

#

thanks for the help tho!

dense edge
#

hello, i need soem guidance ofr a little part of my project. i need to make a scene where you prepare a squad of units ina a 2d plane for a rogue lite style mission (darkest dungeon prep mission screen kinda). i think this need to be new scene. but problem is how do i send the selected units data to the scene that holds the combat mechanics?

#

a little resume:
scene where select units -> load combat scene based on units selected previous in other scene

rugged elbow
# leaden ice Or better yet - why not just use Cinemachine?

@leaden ice I think you are right. Looking back to the video where it all started, the camera indeed used a cinemachine
https://www.youtube.com/watch?v=JVbr7osMYTo

#

But I don't exactly know how it works

rigid island
#

alternative can also be a scriptable Object, or combine both

dense edge
dense edge
#

i need the untis to be persistant, they can have levels and traits

rigid island
#

thats what DDOL does though

#

it creates its own scene to put objects in that don't get destroyed until specifically told so

#

you would need them to be accessable through other scenes so Ideally a singleton

dense edge
leaden ice
dense edge
#

ok, so my plan is to have a scene taht only hold the unit list and its objects, starting the combat scene it will create copies of this objects from this list i nthe battle field, after combat is solved, i will apply the changes that happened(hp damage, permanent debuffs) on the units to the referenced objects in this "list scene".

Did i understood it correctly?

#

sorry im a bit anxious on planning my workflows

spring elbow
#

Guys do you know why the Process 1 game object is centered instead of on top? Panel contains a Vertical Layout group and Processes List contains a Scroll Rect, but the object in the list stays at the center of it instead that on top (i hope to be clear)

sweet raft
#

Looking for suggestions and/or examples of a good system to use for robust dialogue scenes. These are not full cutscenes, per say. And using Timeline won't work because advancing the scene requires player input (if I was to use a timeline the character's idle animations wouldn't be able to loop while waiting for player input).

I need to be able to display dialogue, have characters move/rotate, and transition between Cinemachine cameras. All of these things I can do individually; but I'm trying to find a generic way of doing all of it, without having to hardcode every scene.

simple egret
#

I've seen a devlog a few months ago on something like that, basically the person just created their own "programming language" to encode the actions of the dialogue into a text file
I'll see if I can find it, but it might be slightly overkill

leaden ice
#

That's basically the command pattern

#

pretty sure it wouldn't be too hard to incorporate waiting for user input into Timeline though

#

other options are things like NodeCanvas

hidden flicker
leaden ice
#

all it does it calculate a new Vector3

#

if you want to move an object you'll need to actually assign that new position back to some object

#

e.g. transform.position = Vector3.MoveTowards(...);

hidden flicker
#

got it

sweet raft
#

But yeah a Node-like system is what would be the "norm" for what I'm looking for today. I've no experience making one though, so was seeking other avenues first (before I learn how).

simple egret
#

I haven't been able to so far :/

dense edge
#

maybe i can put the units as childd of hte singleton? not sure if that would work

rigid island
#

probably should read more on what a singleton can do

leaden ice
#

the units themselves are not.

dense edge
#

oooooh ok

tardy moss
#

Is there any use for a gameobject without a transform component ? Is it even possible the transform component to say attach a singleton to it later or some kind of manager afterwards ? Or do I need to make sure those gameobjects are way off the camera with the transform component and not visible ?

sweet raft
hidden flicker
#

How do I make lerp accelerate slower but still take the same amount of time

sweet raft
spring creek
tardy moss
#

Someone said something about the link betwene gameobjects and components yesterday (differences between them). And I realized I thought I knew what a gameobject was then I started to asks myself, ok but what if the gameobject has no components, not even a transform component. Which led to the this question

naive swallow
#

All GameObjects have a Transform

tardy moss
#

Ok that is what I thought too. Gameobject are to show things so mnimally it need to have a position in a scene

sweet raft
rigid island
lean sail
hidden flicker
#

That would be very helpful

rigid island
# hidden flicker How would I use that

Its tricky because I haven't tried this myself with a lerp, but would throw in the animationcurvle.evaluate there and have it ramp up from like 0.2 to 1 or something

sweet raft
lean sail
# hidden flicker How would I use that

You just make a animation curve on your script, then in inspector play around with the lines to get the acceleration you want. If you want it as a remapping of the T parameter that you wouldve used in the lerp then you can use the curve with values from 0 to 1. then evaluate the curve at the T you wouldve used in the lerp, and use this new value in your lerp

sweet raft
lean sail
#

That thread ends up suggesting what I wrote above

rigid island
#

yup, thought of doing the same thing

tardy moss
#

I asked bots and searched but I'm not sure if I can disable GOs before a scene is initializer so their start() isn't called so you can enable them (and have their start called automatically??) after the scene start ?

leaden ice
spring creek
tardy moss
#

yeah but when I reactivate them by code will their start() be called then ? I don't want their start() to be called until I decide it can be

leaden ice
#

why wouldn't it?

#

You can also use OnEnable

#

OnEnable is probably more appropriate.

tardy moss
#

yeah that seems to make more sense semantically and if I look at the code months later it will be more obvious. Great suggestion thanks!

spring creek
tardy moss
#

I guess at this point this is more and more and X=>Y question and I should say what problem I am trying to solve...

#

Im doing a fief simulation game and I need a bootstrap/managers to load assets at the start and generate the world with a lot of npcs. So There would be a generation with a manager, then the manager gets disabled another manager gets enabled and generate their part and so on. Another manager would store the list of everything that was generated for the lifetime of the game

gray mural
#

Hello.
EventSystem.current.currentSelectedGameObject shows the currently selected GameObject.
The problem is that it doesn't show the UI Image that was clicked on. I want it to be "selected".
Is there any alternative to achieve the behavior I want or do I have to implement the full logic myself?

leaden ice
#

Image is not a Selectable component

#

if you want it to be selectable, attach a Selectable to it

gray mural
# leaden ice Can you explain exactly what you're trying to accomplish?

Yes. I have a game which has a targetsSafe boolean. Basically user shouldn't be able to use some Shortcuts when any UI is being target. Like the Space shortcut shouldn't be called when user is typing something in the Input Field.
Although some shortcuts can (even have) to be used when user selects e.g. a GameObject with a tag Build Panel.

leaden ice
gray mural
#

I see. I've attached an empty Selectable with a interactable enabled. It does work now, guess it's what I need. Thank you 😄

gray mural
#

so it should be a selectable

#

I have to add it to every panel I want to be selected now

lean sail
leaden ice
#

Absolutely agreed with this^

floral kiln
#

Hey guys, I have a question about just overall good coding practice.

Let's say I have a script called MapGenerator that is used strictly to generate maps, and it's independent, and I want it to stay indenpendent.

But at one step, the MapGenerator decides to spawn a chest in its maps, but the condition to spawn a special chest is if the player has a legendary sword.

What's the best practice to do this?

Should the MapGenerator have a line of code, like if (player.hasLegendaryItem()) then spawn legendaryChest();?

leaden ice
#

then you can do e.g.

public void Generate(GenerationParams parameters) {
  ...
  if (parameters.includeLegendaryChest) {
    // spawn the chest
  }
}```
floral kiln
#

My question mostly is like, if I do this line: if (player.hasLegendaryItem()) then spawn legendaryChest();?
then MapGenerator class now needs a reference to player, and it feels like it's no longer an independent sword

leaden ice
#

yes exactly

#

in my example that dependency is gone

floral kiln
#

While the parameters thing is generic, which is good, the bool includeLegendaryChest

#

Hmmm, I see what u mean actually

#

I like it, but how do I then check if the player has the sword given that code?

leaden ice
#

that depends on the rest of your code architecture

#

but presumably some code will build the GenerationParams and call Generate

#

that code can have a reference to the player, or maybe there's an event that is triggered setting some other value when the legendary item is acquired

floral kiln
#

To make it simpler and let my architecture adapt it quick, I could just pass in a condition Action<bool>?

leaden ice
#

sure

#

well

floral kiln
#

And if that passes, it will generate, and if not, no, and that condition could be passed in or obtained from somewhere

leaden ice
#

it would be more a Func<bool>

floral kiln
#

Oh yeah, sorry that

floral kiln
#

Okay thanks! I feel much better about doing it this way

#

Keeping my system-type scripts independent

sweet raft
sterile elm
#

I just used local Velocity and works

#

ITS JUST PERFECT

#

Works exactly like in tf2

hard viper
#

Is there a way to temporarily pause a coroutine?

#

like, StopCoroutine, I still have a ref to it, and then StartCoroutine to start again where it left off?

leaden ice
#
yield return new WaitWhile(() => isPaused);```
hard viper
#

maybe more info helps.
My camera moves using different coroutines. Each coroutine is a unique type of following motion, but only ONE is allowed to be going off at once. I use cameraMovement = StartCoroutine(myCoroutine); for this

#

what I want to do now is a PauseAndPanCamera method. Where we: 1) stop the current movement, 2) start moving in a specific way via coroutine, 3) continue old movement coroutine where we left off

leaden ice
#

I think you probably want to implement a more robust actual state machine here

hard viper
#

hmm, right now I only have a few different states, so it's hard for me to visualize the state machine until more states are added

lean sail
hard viper
#

I don't disagree that a state machine is a smart idea

#

actually, maybe I could use a simple enum

sterile elm
#

Vector3 Localv = transform.InverseTransformDirection(rg.velocity)

hard viper
#

btw what happens if I have a coroutine that Stops itself in one block without yield returning?

#

I assume it just goes off, and takes the coroutine out of the list of IEnums that are actually running.

leaden ice
#

what it will do is the same that any StopCoroutine call will do

#

That is - the coroutine that is stopped will not continue after hitting its next yield statement

#

if you want to exit a coroutine from within the coroutine the correct way is yield break;

terse turtle
#

I recently noticed that my few days project became almost a 2 month project. The issue is that I didn't put good practice in making my code easy to manage. Now that I want to edit stuff it's hard. So I need to change it, however I am very scared to mess with the web of public variables that use each other. Is there a way you guys go when this happens?

leaden ice
#

access to the internal state of a class should be judiciously controlled and only allowed by deliberately curated public methods and properties.

hard viper
terse turtle
tardy moss
#

They are basically saying that public variables that mess with each other should be private if you control the API and a public class should control access to it instead

leaden ice
# terse turtle Can you give a side by side example difference please?

Bad way:

public int HP;
public void TakeDamage(int damage) {
  HP -= damage;
  if (HP <= 0) Die();
}```
Good way:
```cs
private int _hp;
public void TakeDamage(int damage) {
  _hp -= damage;
  if (_hp <= 0) Die();
}```
In the first example another script can easily bypass the TakeDamage function and directly change the HP field. If they do that, we will neglect to call the Die() function, which means whatever we do in there won't happen. For example playing a death animation and sound, etc.

By making the field private we can make sure that if external code wants to change the hitpoints, they aporopriately go through the TakeDamage function which does all the right things.
tardy moss
#

or you should make an intermediary Interface class to access it so you avoid that mess if you don't control that public classes mess

hard viper
#

setting public int HP is a really terrible idea

tardy moss
#

I said that because Im not sure if the other code is something they dont control like a plugin or a unity asset store asset..

fervent forum
#

Guys i have this code in my Update function, but for some reason the ray doesnt hit stuff
i have checked via a debug ray that it points in the right direction, end the thing it shjould collide with has a collider

        {
            Debug.Log("Boden");
            leftLineRenderer.SetPosition(1, new Vector3(0, 0, lefthit.distance));
        }```
tardy moss
#

Is it allowed to used visual studio 2022 instead of 2019 in unity 2022.2.15f or it will have negative side effect ? I just noticed it's 2019 so it doesnt have github copilot

sharp blaze
#

Hello guys, randomly within 1-2h of playtime my game randomly freezes and crashes without any error logs. I am 90% sure that this function maybe somehow enters an infinite loop. This function is being called every minute automatically + player can also feed the character by holding a right click button which gives it xp. Anyone know what should I do?

public void AddXp(float xp)
    {
        if (CurrentLevel >= Constants.DEFAULT_MAX_LEVEL)
            return;
     
        CurrentXp += xp;
        
        while (CurrentXp >= NeededXp) //neededxp is a propetry that auto calculates next xp based on the currentlevel
        {
            if (CurrentLevel >= Constants.DEFAULT_MAX_LEVEL)
                return;
            
            CurrentXp -= NeededXp;
      
            CurrentLevel++;
        }
    }
deft timber
hard viper
#

like, if it actually closes, there is a log

sharp blaze
deft timber
#

then its 90% infinite loop

hard viper
#

did you check the console log?

#

not in unity, but on your OS

soft shard
sharp blaze
deft timber
tardy moss
hard viper
sharp blaze
hard viper
#

that's where the log will be

tardy moss
#

so if unity SaS hasnt made one for visual studio 2022 it can't be used for live debugging

hard viper
#

it will probably say stack overflow, and point you to a specific line of code

sharp blaze
#

Well you see the problem is, I've only noticed it happening in a build, not in the editor

soft shard
deft timber
#

in %appdata% -> local low

sharp blaze
#

player.log?

deft timber
#

%appdata% -> local low -> your company folder name -> logs in there

hard viper
#

Player.Log would be when you are in builde

soft shard
hard viper
#

Editor.Log is the log for when in Unity editor

sharp blaze
#

I've also installed the Sentry plugin which like tracks crashes, errors, etc... But this is all I get from it:

Sentry.Unity.ApplicationNotResponding: Application not responding for at least 5000 ms.
#

Also this

deft timber
hard viper
#

look into the player.log. We need the stack trace

soft shard
soft shard
tardy moss
#

hopefully copilot knows unity a bit 😄

terse turtle
leaden ice
hard viper
#

I have a little issue with a script I’m making that pauses my game (which pauses physics simulation), pans camera, and then unpauses at target destination.
Spawning/Despawning in my game is based on my camera’s hitboxes colliding with enemies or spawnpoints.
I would like to smoothly obey this as I pan my camera, but my physics isn’t simulating while I do this.
Is there a way to try to send trigger callbacks intelligently?

deft timber
hard viper
#

pausing my game: 1) stops timescale, 2) disables many behaviours, 3) stops physics simulation

#

actually, I may be able to do this by manual calls.

quick elbow
#

Can I have a non-Monobehaviour listen to Unity Events?

#

I have just a regular C# class that I need to doing some stuff when the Unity Event fires. Basically I'm trying to inject a Monobehaviour as a dependency into my C# class and set up a listener. Can I do this? Is this a code smell?

vagrant blade
#

Does seem a little odd I suppose. You need a mono anyway to hold the instance of the class, so you can listen for events and pass it onto the class to handle something.

quick elbow
#

Hmm... yeah. I might need to re-work my code. I'm not a fan of the current structure.

#

Basically i have a class that really doesn't need to know about Unity at all except for the current game time... which I have being updated in an update loop in a Monobehaviour that controls the game time. And that monobehaviour has an event called TimeTicked that has the current time.

#

I'm just having a hard time with dependencies since Monobehaviours don't allow for constructors 😦

terse turtle
#

I'm trying to learn top down 2D ai pathfinding. Does anyone have advice on this topic?

tardy moss
#

I tried to help you but the server wont let me says the algorith name and blocks it 😦

spring creek
#

Because just saying "a*" without anything else would probably be too short and blocked

tardy moss
#

yeah but it got blocked 😦

#

oh . Not sure what I could have added to make it longer seems like a complete sentence to answer an algorithm name... anyway

spring creek
#

Messages that are too short are filtered with regex

tardy moss
#

afaik besides voronoi which is more advanced a star is pretty much THE main 2d maps pathfinding/navigation algorithm

latent latch
soft shard
loud wharf
#

"See A*" UnityChanThumbsUp

hard viper
#

is there an easy way to go find all instances of a given Component at a given time?

latent latch
#

FindObjectByType?

#

rather, objects

proud fossil
#

How can I deactivate a component that is Singletoned?

#

I´m trying the .enabled = false but doesn´t work

cosmic rain
#

Well, it should. It being a singleton doesn't change how components work.

proud fossil
#

well im confused then

cosmic rain
#

Either you're reenabling it, or confusing what enabled is supposed to do.

proud fossil
#

enabled "unchecks" the component, right?

cosmic rain
#

Yes.

heady iris
#

it doesn't deactivate the game object

#

perhaps you are confusing the two

proud fossil
cosmic rain
proud fossil
#

A null exception error pops up

heady iris
#

well, that's important information

cosmic rain
#

Well, that would definitely prevent it from being disabled.😅

heady iris
#

look at the line the exception points to

#

something on that line is null.

proud fossil
#

yeah haha, but I don´t get whu

heady iris
cosmic rain
#

Read the error, check the callstack. Look at the throwing line.

heady iris
#

or GameManager is a variable and it's null

#

but syntax highlighting suggests that it's a type

proud fossil
#

Oooooh okay

#

thanks a lot

#

stupid question, im sorry, it was so obvious

#

wtf

#

it still pops up

#

and none of them are null

heady iris
#

prove that it isn't null by logging GameManager.InputManager before you try to use it

#

also ensure that the exception is still coming from the same line

proud fossil
#

sorry im noob

heady iris
#

you're already doing it :p

#

Debug.Log

#

You can pass whatever you want to it

#

Debug.Log(this);

proud fossil
#

ooooh ok

heady iris
#

Debug.Log(GameManager.InputManager);

#

etc.

rigid gull
proud fossil
#

this pops up

heady iris
proud fossil
#

but they are both active

heady iris
#

you said this is a singleton. how does it work?

#

Perhaps this is a timing problem.