#💻┃code-beginner

1 messages · Page 137 of 1

rich adder
#

and yeah FSM is fine

slender nymph
#

again, it only shows the editors you actually have installed. if you are using Visual Studio 2019 then you should be following the instructions for visual studio and not visual studio code.
there is absolutely no issue with it only showing the editor you actually have installed

weary summit
#

I use the StopAllCoroutines method but the ai seems to be chasing the player but at the same time following the path of its patrolling waypoints, it doesnt chase in a straight line

rich adder
#

but if you want to clean up your behavior def go with FSM

#

you still should learn how to manage coroutines properly

weary summit
weary summit
rich adder
#

There is nothing diffcult about them

#

its just a method, the only thing you have to keep in mind is that every StartCoroutine creates a new coroutine regardless of how many are running

weary summit
#

youtube tutorials do help but they arent really complete but I will still search

weary summit
polar acorn
#

It will not stop the previous one and restart it

rich adder
#

or put a bool

weary summit
slender nymph
weary summit
#

anyways thank you people, I will continue to try to get a hang of them but I will also use state machines for my AI because ive been trying different things for 3 days and I dont think its that hard to make an AI

slender nymph
#

state machines and coroutines are not mutually exclusive. in fact you can think of a coroutine as individual state machines

weary summit
#

because I definitely havent seen worse

amber nimbus
#

I dont know if u care, but in case you do the projectile was too fast for the trigger to register. So all I did is use an OverlapSphere to check for all triggers hit when it got destroyed by the the actual Collider

ancient island
#

hey guys, can someone please help me find where is the setting to mask 2d trail renderers? i need to set it to 'visible inside mask' but I cant find the option in the inspector

neon fractal
#

not enough information to understand what's wrong, you probably don't have the conditions for it to NOT switch back

slate gale
#

obviously bcs the tutorial person has other IDE's installed, is my guess

#

The Red Class needs a reference to whatever class that Red function (the 'void' is in).

#

There's different ways to go about it, but easiest is probably to make a SerializeField in your class:

// (top of your script)
[SerializeField] ThatClassNameWithTheRedMethod colorChanger;

private void Start() {
  // Your stuff...
}

private void Update() {
  // Execute the 'Red()' method inside the specified instance of the class that contains the method, from this script.
  colorChanger.Red();
}

Now you can drag and drop any object carrying the class containing the 'Red()' method, in the editor, when selecting the object carrying the class above ^.

In your other class, make sure the 'Red()' method is set to 'public'!

public void Red() {

}

If you don't want to have the class containing the method to be on an object, look into static classes or methods in C# and Unity.

warm condor
neon fractal
warm condor
#

no that is not it, it has only one arrow pointing at it. Is it maybe because of the animation being too short, or maybe because of a setting in the arrow?

gusty hazel
#

can prefabs mess with movement that works like this

#

``` step = speed * Time.deltaTime;``

neon fractal
gusty hazel
#

because im using them in a different script to change the multiplier for an enemies health and the speed is somehow sped up

neon fractal
gusty hazel
#

press on your animation file, its in the inspector

slate gale
gusty hazel
#

just transform

slate gale
#

And is the value of 'speed' the same in both instances?

gusty hazel
#
transform.position = Vector3.MoveTowards (transform.position, target2.position, step);```
#

this is how its used

slate gale
#

Unity overwrites the script value with the editor value, in case you set it from the editor.

gusty hazel
#

it doesnt change in the inspector

#

but the thing just flies accross the map

slate gale
#

3d or 2d game?

#

actually nvm, thats not relevant

gusty hazel
#

i did it in the editor first but then i hard coded it

#

its 2d

#

neither way works

slate gale
#

do they both run on the same script i assume?

gusty hazel
#

no

#

thats the thing

slate gale
#

theres no other script on them also causing movement?

#

oh

#

so they dont have the same script on them

gusty hazel
#

it was fine then i introduced difficulty chosing and it broke movement if difficulty is selecred

gusty hazel
#

then ive got this in the player controller

#
if (PlayerPrefs.GetString ("Difficulty") == "Easy") {
            mult = 1;
        }
        else if (PlayerPrefs.GetString ("Difficulty") == "Medium") {
            mult = 1.5f;
        }
        else if (PlayerPrefs.GetString ("Difficulty") == "Hard") {
            mult = 2;
        } 
        else{
            mult = 1;
        }```
slate gale
#

where do u use the mult var

gusty hazel
#
    if (other.gameObject.CompareTag ("basicEnemy") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 10 * mult;
            StartCoroutine (Red ());
        } else if (other.gameObject.CompareTag ("advEnemy") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 20 * mult;
            StartCoroutine (Red ());
        } else if (other.gameObject.CompareTag ("Spikes") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 30 * mult;
            StartCoroutine (Red ());
        }```
#

ive been told its poorly formatted but this is the best that the auto format does on monodevelop

slate gale
#

ah but mult only changes the damage so it shouldnt impact speed

gusty hazel
#

yeah

#

but the speed only ever messes up when i use the difficulty porefab and works fine without

slate gale
#

can you send the code of your entire script on difficulty prefab

#

or is it rly big

neon fractal
gusty hazel
#

ill send it in 2

ivory bobcat
warm condor
gusty hazel
#

public class PlayerHealth : MonoBehaviour
{
    public float currenthealth;
    public float totalhealth;
    public SpriteRenderer sprite;
    public bool dead;
    EnemyController enemyscript;
    PlayerController playerscript;

    public Slider HealthSlider;

    float mult;

    void Start ()
    {
        totalhealth = 100;
        currenthealth = 100;
        dead = false;
        enemyscript = GameObject.FindGameObjectWithTag ("basicEnemy").GetComponent<EnemyController> ();
        playerscript = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerController> ();

        if (PlayerPrefs.GetString ("Difficulty") == "Easy") {
            mult = 1;
        } else if (PlayerPrefs.GetString ("Difficulty") == "Medium") {
            mult = 1.5f;
        } else if (PlayerPrefs.GetString ("Difficulty") == "Hard") {
            mult = 2;
        } else {
            mult = 1;
        }
    }

#
    void Update ()
    {
        if (currenthealth <= 0) {
            dead = true;    
        }
        /*Healthbar code*/
        HealthSlider.value = currenthealth; 
    }

    public IEnumerator Red ()
    {
        sprite.color = Color.red;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.white;
    }


    private void OnCollisionEnter2D (Collision2D other)
    {
        if (other.gameObject.CompareTag ("basicEnemy") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 10 * mult;
            StartCoroutine (Red ());
        } else if (other.gameObject.CompareTag ("advEnemy") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 20 * mult;
            StartCoroutine (Red ());
        } else if (other.gameObject.CompareTag ("Spikes") && (playerscript.voulnerable == true)) {
            currenthealth = currenthealth - 30 * mult;
            StartCoroutine (Red ());
        }
    }

    private void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.CompareTag ("Healing")) {
            currenthealth = currenthealth + 20;
            StartCoroutine (Green ());
            Destroy (other.gameObject);
        } 
    }

    public IEnumerator Green ()
    {
        sprite.color = Color.green;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.white;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.green;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.white;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.green;
        yield return new WaitForSeconds (0.1f);
        sprite.color = Color.white;
    }
}

#

thats the whole thing

eternal falconBOT
slate gale
neon fractal
rich adder
#

use links for large code

slate gale
#

damn

slate gale
#

my boy was waiting to say that haha

#

np

#

haters these days

warm condor
neon fractal
neon fractal
broken hill
#

!code

eternal falconBOT
warm condor
#

what is it for?

gusty hazel
neon fractal
broken hill
ivory bobcat
warm condor
#

well thank you

slate gale
#

nothing much\

slate gale
#

i think u need to put step in update

#

timedeltatime gets the time between past frame and current

visual hedge
#

what can cause those artifacts? It has something to do with player follow camera. THis thing looks like a sphere and everything on it's edges is getting blurred or distorted and it also gives everything within a metallic shine

slate gale
#

maybe that void start runs at another time e.g. when u instantiate it and the frame time will be different and cause issues

#

@ivory bobcat the guy was just lurking chat to run the !code command, is what im talking abt

eternal falconBOT
slate gale
#

kinda extreme imo

neon fractal
spring skiff
#

What can be the issue if my game crashes on startup but didn't crash on another binary?
My game works as windows x64 on my Windows ARM64 PC, but using the Windows ARM64 version of my game on my Windows 11 arm64 System make it crash in the mainmenu after 0.1 seconds.

Any idea why?

visual hedge
timber tide
#

ya got some ghost sphere haunting your scene

gusty hazel
#

god bless you @slate gale its worked

timber tide
#

not really a coding question though

slate gale
#

gg mate

#

happy programming

neon fractal
ivory bobcat
neon fractal
slate gale
#

but yes it was a long code snip

#

couldve been shortened or put in link but since it wasnt busy at the time i didnt think it rly mattered, is all

charred field
#

anyone know a good tutorial or fourm post on snowboard movement?

tawdry totem
#

it isnt readind the magazineSize and bulletsLeft, but it displays at a 0.

tawdry totem
#

same

vestal adder
#

Hello

#

how come the first enemy i instantiate works fine, but the ones i instantiate after its death dont do anything

wintry quarry
#

Why is the enemy behavior on the script that spawns them

polar acorn
vestal adder
#

i am kind of winging it lol

#

okay so if i just do one enemy, it may work?

vestal adder
queen adder
#

here is my code

fierce shuttle
queen adder
#

why does WasPressedThisFrame() return nothing all the time?

polar acorn
vestal adder
#

why

polar acorn
vestal adder
#

oh ye thats because i wanna spawn two enemies

polar acorn
#

You are only calling Destroy on the second one

slender nymph
queen adder
#

wait a minute

#

ah nevermind

#

it actually works

#

its just the output that doesnt work

#

for some reason

lavish tinsel
#

I think I have an issue with an option or selection unchecked, but maybe it's my code?

My problem is that I have a UI button that, if I click it, then become the "target" of my character's Interact action until I click on the gamemap to "unset" the button somehow being selected.

    public void OnBuyCropButton(CropData crop)
    {
        if(money >= crop.purchasePrice)
        {
            PurchaseCrop(crop);
        }
    }

    void TryInteractTile ()
    {
        RaycastHit2D hit = Physics2D.Raycast((Vector2)transform.position + facingDir, Vector3.up, 0.1f, interactLayerMask);

        if (hit.collider != null)
        {
            FieldTile tile = hit.collider.GetComponent<FieldTile>();
            tile.Interact();
        }
    }

    public void Interact ()
    {
        if(!hasBeenTilledAlready)
        {
            Till();
        }
        else if(!HasCrop() && GameManager.instance.CanPlantCrop()) // if you don't have a crop and you can plant a crop
        {
            PlantNewCrop(GameManager.instance.selectedCropToPlant);
        }
        else if (HasCrop() && currentCrop.CanHarvest()) // if you have a crop and it's ready to harvest
        {
            currentCrop.Harvest();
        }
        else
        {
            Water();
        }
    }
#

is there some setting to "unselect" a button after you have pressed it?

#

maybe it's a quirk with the new input system and choosing <Space> as the interact button?

slender nymph
# queen adder for some reason

how do you know? specifically what debugging steps have you taken to see whether your moveSpeed variable is the value you expect it to be?

queen adder
#

i used debuglog the waspressedthisframe return value every frame

tawdry totem
queen adder
#

and it returns some trues when i spammed shift

vestal adder
#

i would just like to know how to have the new enemies i instantiate work

queen adder
#

so now i know its actually giving input

#

it just doesnt change the speed

#

i gotta figure out why

#

WOW

#

my dumbass set sprint speed and walk speed to the same variable

polar acorn
#

But honestly why does this script actually provide functionality to the enemies? It should just spawn them and they should have scripts that handle their own behavior

vestal adder
#

i have been having issues with scripts attatched to enemies

#

dont know how 2 manage it this is my solution

polar acorn
vestal adder
#

lol

polar acorn
#

So maybe you should do the one that makes sense and fix that

#

instead of trying to fix the one that doesn't

vestal adder
#

if i were to attatch this script to the enemy

#

how would i do the references in the editor on its prefab

polar acorn
vestal adder
#

i know that part

#

i am so close to making my script work tho so i wouulld like to fix that if its possible instead

fierce shuttle
tawdry totem
#

the magazine size updates on the inpector

fierce shuttle
#

Are you calling that logic from Update?

tawdry totem
neon fractal
tawdry totem
#

the 3th one here

fierce shuttle
# tawdry totem i dont think so

Ah, if your changing the value from the inspector, youll also need to update your text, unless your initially setting the value before entering play mode (you also seem to have many clones today)

tawdry totem
#

humm let me try it

tawdry totem
polar acorn
#

Does that even compile

slender nymph
#

it's gross to look at, but it is perfectly valid

tawdry totem
#

its not how that look on the code

polar acorn
tawdry totem
wanton hearth
#

Can anyone who knows DOTween help me?

I'm super confused about some unexpected behavior. The first tween works as expected, however the next two somehow SKIP the index (if the first one tweened index 0, the next 2 tweens index 1), even though I've verified i = 0 before and after all three of those tween statements.

for(int i = 0, i < numNeeded, i++)
{                 
   objectToTween[i].transform.DOLocalMoveY(myTargetVector3, delay); 
   DOTween.To(() => objectToTween[i].transform.position, x => objectToTween[i].transform.position = x, newPosition, delay);
   DOTween.To(() => objectToTween[i].Color, x =>  objectToTween[i].Color = x, newColor, delay);
}

#

Yes I know I'm using the generic way in the last 2. It's because I'm actually tweening values that aren't supported in DOTween's shortcuts way' (Vector3 and a Color value not attached to a MeshRenderer). I changed the two because I thought that would be too confusing to see in the code

short hazel
#

Ahh, good old lambda variable capture fooling people again

swift crag
#

oh I know what this is

#

yeah it's The Thing

polar acorn
#

I will never stop stepping on that rake

swift crag
#

there's a single i variable and it lives for the entire duration of the for loop

polar acorn
#

The bane of my existence

swift crag
#

everyone is capturing the same variable

#

i remember writing a long post on the unity forum explaining why this is totally impossible and there must be something else wrong

#

then i tested it

#

egg, meet face

sacred egret
#

Really? my canvas is always way bigger then the camera size

slender nymph
#

yes, that's because it is a screen space overlay canvas and has nothing to do with the world size. a screenspace overlay canvas will draw directly to the screen and does not rely on the camera's size or viewport

tawdry totem
slender nymph
#

make your camera a normal size again

#

and check the docs pinned in #📲┃ui-ux to learn how the canvas works

wanton hearth
swift crag
#

it's a surprise tool that will hurt us later

wanton hearth
#

I need to get around to properly learning what the heck lambdas really are

#

All I know is I get angry when I see people using them, because I feel they're ugly and I don't understand them lol

sacred egret
slender nymph
#

dear god no. normal is around like 5 assuming you are referring to orthographic size

polar acorn
slender nymph
swift crag
#

orthographic size is just how much can be seen by the camera at once

swift crag
#

If your game makes sense when your camera view is 200 meters wide, then use 200

#

But I doubt that's the case here.

sacred egret
swift crag
#

again, the apparent size of an overlay canvas is not meaningful

#

it's getting drawn directly onto your screen; your camera's position and size is not involved at all

#

It's a common error to try to move the camera to "see" it

ruby ember
#

guys is is possible in unity to change the HDR and Fog color setting using dropdown you choose a different color and it changes

timber tide
#

You can serialize a Color on the editor

ruby ember
timber tide
#

Serialize the color then plug it in

#

oh you want it in game eh

ruby ember
#

yes

ruby ember
timber tide
#

Is the drop down box your implementation or an example that you're aiming for

ruby ember
#

example

#

i didn't add system yet

timber tide
#

You'd want to use the drop down via UI

#

make yourself a set of colors and plug those values into it

swift crag
#

you will be using a TMP_Dropdown

ruby ember
#

that's what i did

swift crag
#

you give it a list of options; you can then check the currently-selected option and make a decision based on that

empty dagger
#

how do I access a bool variable from a different script? nothing seems to work

queen adder
#

how do i code health in a game?

polar acorn
queen adder
#

like, how can i make global variables

#

throughout scripts

polar acorn
queen adder
#

oh youre right

#

hmmmmm well

ivory bobcat
#

Lookup a tutorial. It depends on what your task is.

queen adder
#

i was thinking how can i access a variable in another script?

swift crag
queen adder
#

oh

#

thanks fen

#

and ah i should say thank you to you two digiholic and dalphat for helping regardless

swift crag
#

The big idea is that you need to get a reference to the object you want to get a value from

#

you might set this up in the scene by dragging an object into a field in the inspector

#

or you might find it at runtime with GetComponent

#

if the component I want to get a value from is called Foo, I might do this:

#
[SerializeField] Foo myFoo;
#

and then drag an object from the scene into the "My Foo" field in the inspector

#

then, if I want to get a value that Foo has ...

public class Foo : MonoBehaviour {
  public float money;
}

...I can just write:

myFoo.money
eternal falconBOT
sacred egret
ivory bobcat
#

Show us the console tab

sacred egret
ivory bobcat
#

So score incremented five times.

#

Either they were different instances or reset multiple times.

sacred egret
#

all 5 times are diffrent instances its flappy bird game

ivory bobcat
#

So every instance would have their own score and each would have a starting value of zero.

sacred egret
#

yeah

polar acorn
polar acorn
ivory bobcat
polar acorn
#

So they all have 1

sacred egret
ivory bobcat
#

They are different instances

polar acorn
#

If I have a dollar and you have a dollar do either of us have two dollars?

sacred egret
polar acorn
sacred egret
#

i want it to increase each time it exsits the collision

ivory bobcat
#

Decouple the score variable to a different script and reference the single instance. A new score should not live with each of these five instances of this script.

polar acorn
ivory bobcat
#

Either that or the dirty solution of a static variable Score

sacred egret
queen adder
#

how do i make it so that there is only one instance of a class that can be accessed across scripts?

#

i want to do this so that i can implement a health system

polar acorn
polar acorn
queen adder
#

how should i handle health?

polar acorn
#

On the object that has health

ionic zephyr
#

Is the static property that turns GameManager global for all scripts or is it the acessor (get return)??

ivory bobcat
sacred egret
# ivory bobcat Decouple the score variable to a different script and reference the single insta...

Sorry to be still still bothering you but are you talking about something like this https://www.youtube.com/watch?v=hKGzSYXPQwY he starts talking about the points in about 4: 40

Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH

Make flappy bird with this quick Unity tutorial. We'll even manage to squeeze in a highScore system by the end!

Download The...

▶ Play video
ionic zephyr
polar acorn
ionic zephyr
#

hmm sorry I dont understand what it says

#

like get okay to get the property value of instance

polar acorn
# ionic zephyr hmm sorry I dont understand what it says

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors. This feature enables data to be accessed easily and still helps promote the safety and flexibility of methods.

ivory bobcat
ionic zephyr
#

who is the member

ivory bobcat
#

The variable (property)

buoyant knot
#

he pays $50/yr for VIP access

#

top tier member

kindred pawn
#

What does Argument2: cannot convert from ‘UnityEngine.Vector3’ to ‘float’ mean

ivory bobcat
ionic zephyr
ivory bobcat
ionic zephyr
#

maybe what I am missing is what is the acessor exactly

ivory bobcat
#

To prohibit others from changing it but give others access to it to see if it's null or use it.

buoyant knot
ionic zephyr
polar acorn
ionic zephyr
#

what, really?

#

private and public are accesors?

polar acorn
#

Yes

#

Oh, actually, they're access modifiers

ionic zephyr
#

oh okay

polar acorn
#

I got my terminology wrong, ignore me

ionic zephyr
#

I was loosing my mind

polar acorn
#

Accessors are the stuff inside the get of a Property

ivory bobcat
ionic zephyr
ionic zephyr
#

which I THINK is this part
static public GameManager Instance
{ get { return instance; } }

slender nymph
#

that is the entire property

ivory bobcat
sacred egret
ivory bobcat
ionic zephyr
polar acorn
ionic zephyr
#

okay, im starting to get it

#

and what does the getter do

ivory bobcat
ionic zephyr
#

but wasnt a variable a property?

slender nymph
polar acorn
ionic zephyr
#

example?

slender nymph
ionic zephyr
#

the whole line?

ivory bobcat
#

Everything

polar acorn
ionic zephyr
slender nymph
#

that property is the equivalent of this:

private static GameManager instance;
public static GameManager GetInstance() { return instance; }
#

but instead of using a method called GetInstance, you just use the property which-again-is just a method that looks like a variable

ionic zephyr
#

oh oh oh okay okay

#

Im starting to see it

#

and why not directly using a public static GameManager

ivory bobcat
#

They look like fields but are actually functions under the hood. They can have backfields as well (with certain setups) making them functions plus fields, all in one.

ivory bobcat
slender nymph
ivory bobcat
#

Consider asking yourself, why should you ever have private members?

ionic zephyr
#

Because I don´t want that everyone could change my code

ivory bobcat
#

And why's that?
||Because something wasn't meant to be changed and can break everything if changed||

soft steppe
#

does the order of scripts in a gameobject matter when calling (saying i call b's functions (being second script) from another object ,does script A get called first even tho another object called B (A is being called every frame)?

slender nymph
#

no

ionic zephyr
#

Okay so by doing this I have made instance accesible from any script?

nova swift
#

Anybody know a fix for an object's rigidbody returning wrong y velocities when they are moving on a composite tilemap? Or if there's an alternate known method out there that can create a physics collider shape via a script, without directly using a composite collider.

ivory bobcat
ionic zephyr
slender nymph
ivory bobcat
#

Game Manager etc

ionic zephyr
#

okay and then why is static used?

ivory bobcat
#

The class owns the member not the new instances

buoyant knot
#

another way of saying it, is that static members are a part of the definition of what constitutes the class

ivory bobcat
#

Without static, every new instance of the class would have their own instance of every member. Not with the static modifier.. with the static modifier, there's only one member and it belongs to the class (the type - part of its definition)

ionic zephyr
#

with member you reffer to

buoyant knot
#

example; Circle class might define radius (which is different for every instance), and static pi. Pi is just part of the definition of a circle, and is not owned by any one individual circle

#

radius (not static) is separately owned by each individual circle

nova swift
ivory bobcat
nova swift
#

It's particularly annoying when I need to do physics check that require it to be 0 or under, but the rigidbody "returns" incorrect values.

#

It shows 0 on regular colliders that aren't part of the tilemap's composite one, so I'm pretty sure it's the tilemap

slender nymph
ionic zephyr
buoyant knot
#

yes

ionic zephyr
#

so what is the purpose of this?

buoyant knot
#

i assume you’re making a singleton?

ionic zephyr
#

yeah

nova swift
buoyant knot
#

ok, that is how you make a class with exactly one instance

#

so you keep a reference to the ONE singular instance

#

which is better than making the whole class static if you want to be modifying variables

slender nymph
buoyant knot
#

most of the things in my game where I need lots of things to access it, and there is guaranteed to be exactly one at all times, I make it a singleton

nova swift
slender nymph
#

yes. you need to verify your assumptions

nova swift
#

Give me a sec then

ionic zephyr
soft steppe
#

wht is wheel colider

slender nymph
# nova swift

look at that, the velocity is such a small number it is effectively 0. now show the code where it isn't doing what you want it to

ivory bobcat
# ionic zephyr so what is the purpose of this?

Don't use it if you don't know what it is 😆
Other than that, if you are only ever wanting one instance of something, you could restrict it with the Singleton pattern. Having pseudo global access to the instance field is just an extra - often abused and fine in game development.

nova swift
buoyant knot
#

Then my menu (or whatever) can tell EnemyManager to kill everything (like when I’m unloading an area)

#

there should never ever be 2 EnemyManagers. We are keeping a single log of eveery enemy, and we don’t want to mix and match and get two logs that aren’t properly synced

#

and it should not be static, because that has a ton of negative side effects we don’t want to get into

#

make sense?

slender nymph
# nova swift Really just the part that checks rb.velocity.y <= 0: if (rb....

!code 👇 and also why do you need to check that the velocity is less than or equal to 0 here on just the Y axis? knowing that could help improve what you are actually doing. but if you just want a bandaid fix without addressing the root of the actual problem, just use a slightly bigger number to compare it to like 0.001 or something tiny like that

eternal falconBOT
ivory bobcat
#

If it were a spawner and you're wanting multiple instances, you'd want to not opt for a Singleton but simply pass references or subscribe to callbacks. It's necessity is purely if you're wanting single instances. Ease of access should really ought to be a secondary charm.

ionic zephyr
#

okay so

#

to sum up

#

static private GameManager instance. I make this private variable

nova swift
# slender nymph !code 👇 and also why do you need to check that the velocity is less than or eq...

Thanks for the code command thing, didn't know about it. I'll try using a slightly larger number, but the reason I am making the check is the following:
Sonic's charatcer uncurls from the ball state when they land on ground. The player can also jump onto one way platforms where they will be grounded for a short period. I need to check if their y velocity is smaller or equal to 0, so they only uncurl from the ball state on the way down, and not up.

ionic zephyr
#

GameManager here is a class? an instance of the class?

kindred pawn
#

what part of this code is causing unity to say "Assets\playerMovement.cs(22,57): error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector3' to 'float' " and how do i fix it?

ionic zephyr
slender nymph
eternal falconBOT
kindred pawn
#

ive tried but i cant find the error squiggles setting

#

i spent like all of yesterday tryng to, it sucked

slender nymph
#

if you cannot follow the simple instructions to configure vs code, then consider switching to a real ide like visual studio which is easier to configure and less likely to randomly break. but it is required to have a configured ide in order to get help here

kindred pawn
#

yeah, im trying

nova swift
slender nymph
#

it's just some floating point precision issues. same reason you should never compare a float is exactly another float, there may be some super tiny difference like what you were seeing where the Y velocity was 0.00000007 instead of just 0

ivory bobcat
# kindred pawn yeah, im trying

Once you get it done, all of your syntactical errors will magically go away (it ought to even prohibit you from making mistakes by not being able to provide suggestions). Poorly copy and paste results will be underlined with squiggly marks. It saves everybody a lot of time.

kindred pawn
#

yeah, thats cool and all but i just cant find where to enable it, ive tried every combination of google search it just does apear

ivory bobcat
#

Follow the guide. Determine which step you've gotten stuck at.

kindred pawn
#

the guide hasnt helped, i can get to my setting n stuff, but it doesnt show the setting i need to enable

#

it gave me autofinish, but not error squiggles

ivory bobcat
#

Is this VS or VSCode?

kindred pawn
#

i thing VSCode

ionic zephyr
#

So guys what makes that i can se the variable in other scripts is the get return public or the static????

kindred pawn
#

ye VSCode

ionic zephyr
#

so in a singleton pattern

gaunt ice
#

Public is access modifier it has nothing to do with static

ivory bobcat
# kindred pawn ye VSCode

Did you do those three steps? I'm assuming the first two were completed (installation of Unity and VSCode - differs from VS)

kindred pawn
#

yep

ionic zephyr
ivory bobcat
kindred pawn
#

ye

slender nymph
ivory bobcat
gaunt ice
#

Ignore the static here, can you access private outside the class (usually)

kindred pawn
slender nymph
#

where's the unity one

ionic zephyr
#

so you store the class in "instance" but how does that make that there is only one instance of the class?

#

i dont see the relation

ivory bobcat
kindred pawn
#

also there

buoyant knot
gaunt ice
#

Static wont change the accessibility of members

kindred pawn
#

it told me to get those the first time i opened it

ionic zephyr
#

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

public class GameManager : MonoBehaviour
{
static private GameManager instance;
static public GameManager Instance
{ get { return instance; } }

// Start is called before the first frame update
private void Awake()
{
    if (instance == null)
    {
        GameManager.instance = this;
    }
    else
    {
        Destroy(gameObject);
        DontDestroyOnLoad(gameObject);
    }
}

}

slender nymph
#

!code

eternal falconBOT
ionic zephyr
ivory bobcat
slender nymph
distant veldt
#

creating an instance allows you to access it from anywhere. you only need/want one instance of it or you can get errors that why you check if the instance exists and destroy it so you dont make two of them

ionic zephyr
#

what could happen if "instance" was part of the instance and not the class

slender nymph
#

i was not answering your question, i was legitimately asking what you think those two lines are doing together like that. why are you passing the gameObject to DontDestroyOnLoad right after you destroy it

ivory bobcat
teal viper
kindred pawn
#

i think so

slender nymph
#

remove the highlighted package

ivory bobcat
#

It should be "Visual Studio Editor"

kindred pawn
#

yeah

#

thats right below the highlighted one

teal viper
# ionic zephyr what?

I think you need to go over the OOP basics in C# context. You need to understand what type, instance, reference and static are.

ivory bobcat
#

Remove the older code one above

gaunt ice
#

Static members are members of class not the members of instances of class

teal viper
kindred pawn
#

k, it did tell me some other thing needs it tho so ¯_(ツ)_/¯

ionic zephyr
teal viper
#

Because singleton implies static access to an object.

kindred pawn
ionic zephyr
gaunt ice
#

You can ask the class to return an instance of that class for you and you dont care where the instance comes from

ivory bobcat
kindred pawn
#

it already uses that one, and when i go to remove the VSCode Editor, or the VS Editor it wont let me cuz they're necicary for some other thing

slender nymph
#

unlock the engineering group then you can remove the vs code editor package

twilit pilot
ivory bobcat
ionic zephyr
#

but it should have its explanation right?

ivory bobcat
#

It's not a pattern isolated to unity itself. Searching should give you lots of results.

kindred pawn
ivory bobcat
kindred pawn
#

nope, theres still no error squiggles, and i have the same error msg

ivory bobcat
#

Well, we know where the error is, it's very obvious. Were there any issues when restarting VSCode?

#

Any pop-up in the bottom right?

kindred pawn
#

yeah, these

ivory bobcat
#

Right, so Net SDK is missing

kindred pawn
#

thx

round scaffold
shell herald
#

can someone help me out here? what i want to achieve is that the Instantiate snippet of the code gets done once the "Fire2" Axis is released. what am i doing wrong?

round scaffold
#

i think get axis raw gives u vertical and horizontal inputs

#

are u looking for GetMouseButtonDown?

ancient island
#

when I use a camera to render a texture, how should I handle camera size? I was trying camera.orthographicSize but even if I set a default value on inspector, it sets back to 5 when I hit play

ivory bobcat
#

I'm assuming it happens immediately or all of the time.

eternal falconBOT
rich adder
#

I cant read screenshot image well 😦

shell herald
ancient island
#

nop

shell herald
ancient island
#

As I said, when hitting play 'Size' jumps back to 5

#

well that screenshot was taken in play mode

slender nymph
#

if it happens when you enter play mode then you probably have some component assigning it to 5 in Start or Awake

rich adder
ancient island
slender nymph
#

show the entire inspector for the camera object that is being affected by this issue

ancient island
rich adder
ancient island
#

not really useful because script should set it to 10.2777

slender nymph
ancient island
shell herald
ancient island
slender nymph
ancient island
#

ok

slender nymph
#

how did you manage to find a bin site that terrible

ancient island
#

i can remove camera shake component from the affected camera

slender nymph
#

in the future please use a site that has line numbers and syntax highlighting. the bot has several in the !code embed below 👇

eternal falconBOT
rich adder
slender nymph
# ancient island lol

but try changing the camera's tag. i'd bet you'r accessing Camera.main somewhere else and it's affecting this camera since it has the MainCamera tag

ancient island
#

anyway I did it

#

nothing happened

slender nymph
#

wdym nothing happened? nothing as in the issue persists or nothing as in the camera's orthographic size was not changed to 5?

ancient island
#

issue persists

#

idk where else to check

rich adder
#

check anything that references it

slender nymph
ancient island
slender nymph
#

well then i guess there's nothing wrong. good job fixing it

ancient island
#

basically I just cloned main camera

#

but I think it has something to do with render texture

#

because camera becomes square

#

and it's the only thing that differs from main camera

slender nymph
#

so then like i said "the aspect property of the camera is not what you are expecting it to be"

#

and that means your math is wrong

ancient island
#

this is weird

#

where is the enable button?

rich adder
#

eg Update/ Start etc

shell herald
ancient island
#

what does MB mean?

slender nymph
#

Awake is not affected by the enabled state of the MonoBehaviour

rich adder
ancient island
#

so is it wrong?

slender nymph
#

is what wrong?

ancient island
#

should I change it to start instead of awake?

slender nymph
#

why

kindred pawn
#

its probably a super simple fix that im not seeing but how am i sposed to fix this?

slender nymph
kindred pawn
#

thx

rich adder
kindred pawn
#

yeah, i do, im just kinda dumb

rich adder
kindred pawn
#

my thoughts exactly, i only started trying making games yesterday, and i think its going well so far

rich adder
kindred pawn
#

i only just did that like 15 min ago

rich adder
#

every victory counts 💪

kindred pawn
#

fr

obsidian needle
#

I'm working on a small state machine, and I'm struggling with understanding how to pass one variable between different files. do you need a new instantiation of the class the variable comes from in each file it's used? And would I need to use the same name across files?

Also I'm not really understanding when you need to use the new keyword. how come sometimes I see someone set
SomeClass name = new SomeClass();
but sometime I see someone write only
SomeClass name;

kindred pawn
#

all the struggles will be worth it when i make some really cool thing down the line, i mean just getting a white bean to move was cool

rich adder
obsidian needle
boreal tangle
#

is it possible to stop the animator from animating a gameobject on a certain layer?

swift crag
#

"on a certain layer"?

#

like, when the GameObject is put onto a specific layer?

#

(rather than animator layers)

boreal tangle
#

I mean the animator layers. I know theirs stop playback but that stops all animations

rich ember
#

Hey guys. Quick question. I have a unity script on my player for player movement. Everything is stored in methods. Well I call the methods and using a Debug.Log I determined the methods do get called but. chaning my velocity variable doesn't actually change the variable. However if I reload the script BUT LEAVE GAME RUNNING it will work? It is like the script is not loading properly. is there something I can do to make sure a script loads properly or what am I doing wrong

slender nymph
#

show relevant code and logs

rich ember
#

Ill post in a bit. I am away from my unity. was just wondering if maybe this was a common issue

#

thanks anyway though

weak tiger
#

Can I get suggestions to learn c# scripting

slender nymph
#

there are beginner courses pinned in this channel

weak tiger
#

I think it is not necessary to just learn and remember everything we need to just understand the code

#

Because I am having a lot of problem in writing script

#

Although I have cleared by basics of c#

#

Every time i get something new and I don't know how to remember it

rich adder
weak tiger
#

Okayy

polar acorn
#

There's really not much remembering. There's understanding and reassembling the blocks yourself every time since you know what they all do

fierce shuttle
# weak tiger Every time i get something new and I don't know how to remember it

Also try taking notes, having a notepad open as you follow tutorials or script in Unity, and write down things that confuse you, things you search up etc so you have a reference point that makes sense to you that you can refer to, I find as you work on code its less about memorizing, and more about recognizing patterns, like seeing "null reference exception: object reference not set to an instance of an object" ive seen enough times I usually know what "object" is null and why

queen adder
#

Hey everyone i have a problem with my code that only happens when i run it twice

#

typeWriterAnimation = LeanTween.value(0, text.text.Length, text.text.Length * 0.05f / _text_speed).setOnUpdate(length => text.maxVisibleCharacters = (int)length).setOnComplete(_ => hasTextRolledOut = true);

#

I get a NRE but only when i play it twice

summer stump
queen adder
#

Im guessing it has something to do with the lambda expression

#

!code

eternal falconBOT
queen adder
teal viper
queen adder
polar acorn
teal viper
#
typeWriterAnimation = LeanTween.value(0, text.text.Length, text.text.Length * 0.05f / _text_speed)
            .setOnUpdate(length => text.maxVisibleCharacters = (int)length).setOnComplete(_ => hasTextRolledOut = true);

I'd guess that text is being destroyed at some point while the tween is still running.

queen adder
#

Oh that might be it

#

Let me check

runic rivet
#

So I've got two scripts, one is the player script and the relevent code from it is

        audioManager.PlaySoundFX(deathSFX, deathVolume);
        level.LoadGameOver();
        Destroy(gameObject);
    }```
Now the level.LoadGameOver(); it is referring to has this following code.
```    public void LoadGameOver(){
        //SceneManager.LoadScene("GameOver");
        StartCoroutine(GameOver());
    }
    IEnumerator GameOver(){
        yield return new WaitForSeconds(1);
        SceneManager.LoadScene("GameOver");
    }```
The problem is that when Death() runs I get the following error.
```Coroutine couldn't be started because the the game object 'SceneManager' is inactive!
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Level:LoadGameOver () (at Assets/Scripts/Level.cs:10)
Player:Death () (at Assets/Scripts/Player.cs:108)
Player:ProcessHit (DamageDealer) (at Assets/Scripts/Player.cs:102)
Player:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/Player.cs:94)```
#

I've tried adding debug's and a debug in any method other then the coroutine shows up just fine. Additionally if instead of using a coroutine to delay the scene load I just load the scene from the LoadGameOver() method everything runs fine. I have also tried using

    Debug.Log("Scenemanager received the command to start the coroutine");
    if (gameObject.activeSelf) {
        StartCoroutine(GameOver());
    } else {
        Debug.Log("The scene manager is not active for some reason");
        // Additional error handling or alternative action if needed
    }
}```
And the first Debug.Log will get logged but then it's like unity ignores the rest of the code and throws the exact same error. I've been stuck for a while and would appreciate any ideas.
ivory bobcat
runic rivet
#

Second line of Death()

ivory bobcat
#

Show us the console logs. You've got some race conditions with objects already destroyed attempting to run coroutines.

runic rivet
#

Everything the console logs other then my Debug.Log statements is posted. or did you want the Debug.Logs as well.

polar acorn
runic rivet
#

No

polar acorn
eternal falconBOT
runic rivet
#

alright

polar acorn
# runic rivet https://gdl.space/lopocoweza.cs

Add this code to the Level script:

void OnDisable(){
  Debug.Log($"{gameObject.name} has been disabled");
}

Keep all the other logs you put in. Then show the console leading up to the error

runic rivet
#

I don't think the scene manager is actually ever disabled. The disabled message only showed up when I stopped the game

#

Thinking about it, this script setup was working just fine until I moved some of the Players stats out of the player script and into a PlayerStats script. Could that cause something like this?

polar acorn
#

If so, disable it and make sure the order is what you think it is

runic rivet
#

it was enabled, I disabled it but got the same results

polar acorn
#

Are you sure you're not triggering the coroutine twice? If so, one of them would finish and change scenes while the other coroutine is still running

runic rivet
#

Would that result in a scene change? If so then that's not happening. If it is happening, the only cause I can think of would be if the player is getting OnTriggerEnter2D called multiple times at the same time. I could use a bool check in process hit to make sure of wether this is the case or not I guess

polar acorn
#

If the scene isn't changing then it definitely seems like the object is disabled when the coroutine tries to start

#

Did you try logging gameObject.activeInHierarchy before attempting to start the coroutine?

runic rivet
#

I had not, I can try that

#

it says false

polar acorn
#

Completely unrelated to any of the code here, the object is just simply off

runic rivet
#

enabled and disabled is the little check box to the left of the object name right?

polar acorn
#

Yes

runic rivet
#

Then I have no idea what I'm doing I guess, cause that box is checked on, and while testing it I never see it get unchecked.

runic rivet
#

in order to remove them as a variable I took it out of it's parent and got the same results. but the parent is never inactive as far as I know anyway.

polar acorn
#

Send a screenshot of your full unity window, with this object selected and the hierarchy visible

runic rivet
craggy oxide
#

are there any specific tutorials you'd recommend, that you'd feel beginners could learn a lot from

misty spruce
#

imo Brackeys is the best unity youtuber for beginners. He makes everything very approachable and easy to digest. But, his stuff could be outdated, and he doesn't really go in depth. Once I felt like Brackeys wasn't cutting it, I watched Code Monkey instead. He's extremely active and makes a video on almost everything. He also goes very in depth and a lot of his code is good enough for production

raw crater
#

What can I use Interfaces for?
How is it in relation to a struct?

charred spoke
#

No youtube code is good enough for production

charred spoke
eternal needle
misty spruce
# eternal needle Definitely not, there's a ton of errors, misinformation, and just a lack of room...

Assuming you're talking about Brackeys. From what I've seen, his videos are targeted for beginners, so there's definitely going to be a lot missing. I've noticed that his code can be improved on, but I can personally look past that if I'm a beginner. He's a great introduction and explains everything in a way that even a complete beginner can understand. Having millions of views for beginner Unity tutorials is impressive and imo seems to prove that he is very skilled at teaching beginners

charred spoke
#

It simply proves the all mighty algorithm chose him. Imho Brackeys teaches many wrong practices that stick with beginners

eternal needle
# misty spruce Assuming you're talking about Brackeys. From what I've seen, his videos are targ...

on top of what Uri said, he makes decent quality videos (visually) where it seems like he knows what hes talking about, this helps with the views. beginners wont be questioning anything because they dont have the knowledge.
Ive taught beginners, and i have doubts that anyone would really learn from his content. It will be people copy pasting then assuming they've learned. Imo if someone wants to truly learn, they should start with c# alone and not even do unity. Otherwise all "learning" will be fragmented pieces of code without understanding the fundamentals

gilded pumice
#

just a question, is learning json and data persistence for the first time supposed to be overwhelming? It feels like a lot of information was thrown very quickly and that perhaps I won't fully understand it for a very long time lol

eternal needle
languid spire
#

learning json? JSON is a data format, very little to learn about it

gilded pumice
#

using the syntax within c# to store and retrieve information

#

is what I meant

languid spire
#

as for File IO, the simplest of C# console programs should teach you most of what you need to know in an hour or so

gilded pumice
#

well the concept seems simple, the execution just seems a bit laborious. Creating classes and instances of those classes across multiple scripts and then memorizing the json syntax on top of it. I guess it's just a matter of using it over and over to get familiar, I was just caught off guard with the sudden influx of information compared with the rest of the course lol

languid spire
#

I'm sure no one ever told you that designing and building computer systems was easy. It does require you to absorb vast amounts of information and concepts of which you will be unfamiliar

#

it just takes time and practice, eventually it may become as natural as breathing

eternal needle
languid spire
#

tbf you don't even need to do that, Saving/Loading to and from json is pretty standard so you write your own utility method to do it then you only need to remember that you wrote it

#

many possible reasons
ANY compile errors
script not attached to an active game object
to name but 2

#

of course, how else would it run?

#

did you attach the script to the object it is cloning?

#

Think about it
CloneObject->Start->cloneobject->start etc etc until Unity him go bang

#

objects should not clone themselves

#

you put the cloning script on any gameobject except cloneObject

plush cave
#

is it more efficient to find by tag or by layer? or is there a better way?

languid spire
#

better way is not to use Find at all, dependency injection springs to mind

#

not sure what your question is, explain

eternal needle
# plush cave is it more efficient to find by tag or by layer? or is there a better way?

Realistically this shouldnt even be a consideration, if you're doing this on a LARGE amount of gameobjects then performance could be a consideration. In that case, attach the profiler and see for yourself exactly what the difference is.
You might not want to use a layer purely for the purpose of searching because then you must consider other things like camera and physics for every single layer.
Another thing is you shouldnt really need to do either of these as Steve wrote

slender nymph
#

typically your "original object" that you spawn clones of would be a prefab asset not in the scene at all

languid spire
#

are you expecting the cloned object to be in the same position as the original?

slender nymph
#

also you should 100% start with some basic courses to learn unity. the pathways on the unity !learn site are a good place to start

eternal falconBOT
#

:teacher: Unity Learn ↗

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

languid spire
#

that is prefabs as @slender nymph mentioned

plush cave
shrewd swift
#

i am doing a procedural generation level manager

should i make an another class for my custom window, or is it ok to use the same class where the generation logic is ?

languid spire
#

custom inspector?

shrewd swift
#

yes

#

well i just realized you have to use EditorWindow

languid spire
#

seperate class and put the script into an Editor folder

shrewd swift
#

i'll do that
but this means that from my LevelGenerationManager class, i need to get the value of myWindow

because the goal is to trigger specific methods or set parameters from the custom window

for example:

in generate() inside LevelGenerationManager, there is a debug bool set to false by default, i want that before executing it get the values for the custom window

idk if its possible or even if its the good way

#

using the context menu was also another way, but i wanted to have a custom window rather that clicking on the 3 dots on my script component

languid spire
#

that wont work, editor scripts do not exist at runtime.
what I tend to do is to use a ScriptableObject as a go between i.e. EditorWindow->ScriptableObject->Runtime class

shrewd swift
#

i see what you mean, but i dont understand how i would do this

#

do you have any recommended ressources or page doc i could start to look at ?

languid spire
#

sorry, no, I just do it

shrewd swift
#

no worries ty for the help

slender nymph
languid spire
#

of course, you set cloneObject to your prefab in the inspector instead of the game object from the scene

shrewd swift
#

btw box ty for running the array test

halcyon geyser
#

Ye

languid spire
#

yes

burnt vapor
#

Can you please learn basic c# and stop asking here

last igloo
#

o damn

burnt vapor
#

These type of questions should not be needed. The point of this channel is helping you with starting with Unity, not figuring out how c# works. There are courses for that.

#

Please try to !learn these things

eternal falconBOT
#

:teacher: Unity Learn ↗

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

burnt vapor
#

Wrong one, but you can also check the pinned messages for courses 😛

last igloo
#

@queen adder this youtube will help he does c# in unity

uncut bay
#

How can I make a wall go down like a door in 2d unity?

#

so when the player touches the key, the wall on the right goes down in a smooth manner

#

I already got the OnTriggerEnter2d method for the key but what code will make the door move?

slender nymph
#

lerp its position

uncut bay
#

what does "lerp" mean

slender nymph
uncut bay
#

I tried google

#

wasn't helpful

#

thx tho

slender nymph
#

try spending more than 10 seconds using google next time 🤷‍♂️

#

alright, guess you don't want help then

uncut bay
#

I do, but I spent a large portion of time yesterday trying to find a solution, I even tried solving it on my own, and I spent like 10 minutes today googling again, it's pretty annoying when someone just tells you something like "try spending more than 10 seconds using google next time", I don't know about you but I don't like it when people talk to me in such a condescending tone, especially strangers

burnt vapor
#

Finding out what lerping is is the most Googleable question I have seen in here so far

#

It's rude to say but very needed considering the amount of questions that come in these channels

uncut bay
#

oh lerping, I'm talking about googling the wall issue

#

mb

#

Thought he was telling me that I shouldve found about lerping through google

#

sorry

burnt vapor
#

So the idea is that you trigger the wall however you want, and then adjust its position. Then using lerping you want to move the wall to this new position.

uncut bay
#

👍 thx

burnt vapor
#

This could be done with a Coroutine

uncut bay
#

alr

vast vessel
#

guys, can you tell me how to fix this error?

timber tide
#

Does your previous class, or those before it have a constructor

timber tide
#

you need to include those params into all inherited classes via base keyword for each constructor they're included in

vast vessel
#

its there tho

timber tide
#

usually if you right click on the error it'll do it for you

#
public CastableAbility(ICastableAbilitySO storableObject, IEntity entity) : base(storableObject, entity)
vast vessel
timber tide
#

Yeah, it'll have an option to implement them for you

#

similar to how you let the IDE auto implement interfaces for ya

vast vessel
#

nope. not here

#

look at the code. you can see that i have implemented it

timber tide
#

Ah, maybe because you've edited the constructor already

vast vessel
#

wdym i still have the error

timber tide
#

yeah, you still need to add base keyword

vast vessel
timber tide
#

it's a c# thing where inheriting from previous class that has a constructor other than the default

timber tide
vast vessel
#

nvm got it

agile trail
#

Is there a way to easily get global co-ordinates of specific points within a scene?

I want to be able to easily place points within a navmesh (but within a certain boundary of said navmesh only),

Meaning maybe something like:

+--------------+
| A | | B | | C |
+--------------+

Maybe in phase 1, I only want points to be placed in region A. And in phase 2, only points be placed in region B (and so forth).

I am planning on raycasting from a greater z-axis to intersect with the proper z-axis on the floor and thus place points on the navmesh that way. But I'm having difficulties getting the global co-ordinates.

As an aside, are there better ways of going about this?

twilit pilot
eternal needle
swift crag
#

yes, the raycast hit is already in world-space

#

"global coordinates" would be world-space positions

#

what is the problem you're actually having? are things spawning at the wrong spot?

gritty notch
#

anyone know why this happens when using IDragHandler?

code:

public void OnBeginDrag(PointerEventData eventData)
{
    Debug.Log("Begin drag");
}

public void OnDrag(PointerEventData eventData)
{
    m_RectTransform.anchoredPosition = eventData.delta / canvas.scaleFactor;
}

public void OnEndDrag(PointerEventData eventData)
{
    Debug.Log("Eng drag");
}

public void OnPointerDown(PointerEventData eventData)
{
    Debug.Log("Pointer down");
}
timber tide
#

It happens because something is off with your OnDrag I'd assume ;p
Not sure what dividing by a scale here does for ya

keen crescent
#

A bit of a general question: How valid is the approach of using a static "Game Manager" vs. using delegates/events for my game? Is it strictly better to implement events? If so, why?

timber tide
#

Why not use both

#

they arent exclusive

gritty notch
cosmic dagger
agile trail
timber tide
agile trail
agile trail
#

maybe i will spawn 5 points randomly in A during phase 1

#

then 20 in B during phase 2

#

etc.

twilit pilot
#

how do you know what A,B,C are?

agile trail
#

wdym

#

they're regions in a navmesh

#

i have no idea how to get their coords

timber tide
agile trail
#

I have a visual idea of where I want A,B,C to be

#

but idk how to derive it in the code

dusk acorn
#

Hi Pals,
I'm a beginner with some experience in coding. I would like to know what's the best way to create a simple 2D board game like Rummikub with draggin cards feature and having a board which allow to placement from the player hand board the cards?

twilit pilot
polar acorn
agile trail
#

how??

twilit pilot
#

create a position and bounds that defines them

agile trail
#

like dude my navmesh is just 1 contiguous plane

polar acorn
agile trail
#

yes magically

#

i don't know what to actually do can i have some keywords

polar acorn
#

You need to formalize the rules, not just "I kinda feel it out"

twilit pilot
agile trail
#

ok

twilit pilot
#

and now you can get the position of that cube

#

or whatever shape you want - you define the bounds

polar acorn
#

Like, is it dividing a mesh into thirds? Is it three regions of equal spacing starting from some point? What are the regions?

agile trail
#

so i get the location(s) where that cube intersects my navmesh and assign that as the 'limits' for A,B,C?

polar acorn
#

You need to decide what they are

agile trail
#

this is an oversimplification

#

it's a navmesh

#

i need to divide my navmesh into 3 areas

#

which spawn 'pointobjects' during different phases

#

but idk how to get the boundaries for A,B,C

polar acorn
# agile trail it's not equal thirds

Okay cool so that's some information on how you're determining the region, just keep coming up with more of those until you actually know what you want

agile trail
#

dude

#

i just want to know how to define it

#

in the code

#

or in the editor

#

why are you being condescending like this

timber tide
#

do you know how to make a navmesh

polar acorn
swift crag
#

your problem is kind of ill-posed

timber tide
#

if you do then make navmesh 2 more times

swift crag
#

So yes, one option is to just make multiple nav mesh surfaces

polar acorn
swift crag
#

The first thing that comes to mind for me is to just make some box colliders

#

and to sample a random point inside the collider

agile trail
# timber tide do you know how to make a navmesh

i just followed this tutorial

https://www.youtube.com/watch?v=CHV1ymlw-P8

Learn how to create AI pathfinding using the Unity NavMesh components!
This video is sponsored by Unity.
● Watch on Unity's website: https://goo.gl/jUsU8D

● Example project: https://github.com/Brackeys/NavMesh-Tutorial

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

·································································...

▶ Play video
#

it doesnt say how to divide the baked navmesh into the separate regions

swift crag
#

yes, because that's a very specific task you're trying to accomplish

#

you probably won't find a tutorial that does exactly what you want

swift crag
#

Normally you just have walkable + non-walkable + "jump" areas

#

You would use nav mesh modifiers to assign different areas to different parts of your mesh

#

However, I'm not sure what would be an easy way to then randomly sample points within a specific area.

agile trail
#

the player character/agent needs to traverse A,B and C

#

so i don't know if having different areas is the solution

#

they need to be able to cross A,B and C

#

but the points must be spawned inside those specific boundaries only

swift crag
#

explain what you're actually making your game do here

#

not "spawn things on a nav mesh"

#

like, what's the gameplay here?

agile trail
#

it's for determining randomized movement

swift crag
#

no implementation details

agile trail
#

i literally don't know what you want from me

swift crag
#

I want an explanation of what gameplay you're trying to create.

agile trail
#

it's not gameplay

#

i just want to be able to spawn points, maybe programmatically, maybe randomly, such that it can direct specific placement of some agent int he navmesh

#

the player agent can move through A,B and C regardless

swift crag
#

"gameplay" means anything the player experiences in your game. the way goombas walk around in a mario game is part of the gameplay

agile trail
#

but the other agents should be limited to A,B,C

swift crag
agile trail
#

at the specific phases

agile trail
#

like randomly may be strategyA

#

then linearly strategyB

#

then some other programmatic implementation strategyC

#

and so forth

buoyant knot
#

sounds like a strategy pattern

#

you even said the word lol

swift crag
#

a lot of things sound like a strategy pattern :p

agile trail
#

so what am i actually supposed to do to divide the navmesh

swift crag
#

and you need to be able to pick points within that area

agile trail
#

no, you do not pick

#

the computer/script picks

swift crag
#

by "you" I mean you, the programmer

agile trail
#

the programmer doesn't pick

#

the computer picks

buoyant knot
#

lord help us

swift crag
#

do you want to be helped

agile trail
#

it should spawn like 20 points in a certain space

#

honeslty fuck you guys you are just trolling me for real

buoyant knot
#

Lord give me the strength to not to throw a javelin through this man’s chest, for he does not understand the trials he puts us through, Lord

swift crag
#

this is ridiculous. we're trying to help you and you're being combative.

twilit pilot
toxic latch
#

If I have a function that I want to increment a value on a prefab, how should I go about referencing the prefab? Do I pass the name of the prefab into the function when I call it, and then change the value on the prefab within the function?

swift crag
#

It's not invalid, but it is unusual

buoyant knot
swift crag
#

you definitely won't pass a name in, though -- you just reference the prefab through a serialized field, as you would an object in the scene

buoyant knot
#

and since you instantiated it via code, you also already have a ref to the prefab

polar acorn
toxic latch
swift crag
#

imagine intersecting the navmesh with a cube

#

That's actually an interesting question. It would be useful for the game I'm working on right now.

buoyant knot
#

and then use different strategies to define different movements on that navmesh

polar acorn
toxic latch
swift crag
buoyant knot
swift crag
#

thingPrefab is as reference to a prefab with a Thing component on it
myThing is a reference to the freshly instantiated Thing

#
var enemy = Instantiate(enemyPrefab);
enemy.health = 100;
polar acorn
toxic latch
swift crag
#
[SerializeField] Enemy enemyPrefab;
#

enemyPrefab is a field on our component.

#

it's a variable that's stored in the component.

#

the prefab could be named "Enemy" or "Glorbo" or whatever

buoyant knot
#

enemyPrefab is the prefab

#

it’s the blueprint to make a gameobject that you keep as an asset file (not in the scene)

#

the gameobject is the actual instance that lives in the scene during runtime

swift crag
#

A field of type Enemy can refer to any Enemy component

#

it could be one on a prefab, or one on an object in the scene

twilit pilot
swift crag
#

basically sticking the enemy on a leash

#

Intersecting a navmesh with a volume would be really neat, though

#

I have an AI routine that searches for the player after losing sight of them

#

right now, it fires a bunch of navmesh raycasts in a circle and then randomly wanders inside that area

#

I guess I can just randomly sample points within a box to get the same result as some fancy intersection-with-a-volume, though

#

but that would stop the enemy from taking a long path out of the room into a neighboring room, since there'd be no path to the other room

polar acorn
buoyant knot
#

they want the computer to figure out how to do it for them

toxic latch
swift crag
#

It tells Unity that it should show that field in the inspector and remember its value

#

Unity automatically serializes public fields. You have to be explicit for anything else

#

Leaving fields private reduces the amount of clutter you see when other classes use the component

#

(To “serialize” is to turn a code object into data.)

buoyant knot
twilit pilot
buoyant knot
#

not serialized = not saved in file

buoyant knot
#

by default, public fields in Monobehaviours and ScriptableObjects are serialized. non-public fields are not. If you want the behaviour to be different from this, you need to use SerializeField or NonSerialized

toxic latch
swift crag
#

var is a keyword to save some typing

buoyant knot
#

var is a keyword to declare a variable without showing the type

swift crag
#

When the type of a local variable is obvious, you can write var instead of the entire type

buoyant knot
#

you should not use it, at all. Until you have a lot more experience

swift crag
#
var x = 3; // x is an int
#

I think it's good to understand exactly what type you have, yes

swift crag
buoyant knot
#

i basically never use it.

swift crag
#

It's handy in foreach loops

#
foreach (var module in modules) {

}
#

I sure hope I know what module is

buoyant knot
#

i did that once. i thought module was of type IMyInterface, but i forgot module was of type SerializableInterface<IMyInterface>. Which didn’t throw a compiler error, but then makes everything super wrong

#

never again

swift crag
#

splat

bright zodiac
swift crag
#

var is also useless if you need a less specific type, of course

languid spire
buoyant knot
#

i used to love that about python, that you don’t need to declare types. that was 15 years ago. Now, I prefer the handrails

swift crag
#

much more, even

languid spire
#

I don't

polar acorn
#

I have used enough python to know that I never want loose typing ever again. Keep var the hell away from me

swift crag
#

Although I would not say var is in the same boat

languid spire
#

absolutely, var should never be used

swift crag
#

It's exactly the same static typing that you get from an explicit type.

#

it's not dynamic

buoyant knot
#

it’s ok in Python when learning, and you don’t know much. then it’s time to move on to more controlled typing

swift crag
#

which does punt type-checking to runtime

languid spire
#

except your code is less readable, not a good thing

polar acorn
#

You look at a function in Python and you have to go through a call stack like eight functions deep until you find the function that originally set the variable to determine it's type

or

You look at the type in the parameter line of the function

#

Option B seems much better

#

Down with var

buoyant knot
#

agreed

polar acorn
#

#varisoverparty

swift crag
#

you're describing a lack of static types

buoyant knot
#

that is literally the issue that var causes

polar acorn
swift crag
#

var is only legal when declaring a local variable

whole sapphire
#

how do i get a variable from another game object

#

like how do i get the run speed from another script

buoyant knot
swift crag
#

🐢 all the way ⬇️

buoyant knot
#

we’ll cross that bridge if he asks

#

anyway, I would not teach beginners about var, at all

distant robin
#

!code

eternal falconBOT
buoyant knot
#

they have enough to learn, without having to learn something that will actively screw them over

whole sapphire
#
public GameObject statsManager = GetComponent<ScriptableObject>();
#

sth like this..?

#

im dum]

swift crag
buoyant knot
#

btw is there a simple plugin to get keyboard input for a string?