#💻┃code-beginner

1 messages · Page 679 of 1

fervent abyss
#

there are 3 parents

#

armature

#

model

#

and the prefab top

naive pawn
#

use pivot mode instead of center mode

polar acorn
fervent abyss
#

in a sec

fervent abyss
real grail
# fervent abyss there are 3 parents

Here is very simple radar script you could utilized to detect enemis just make sure you give the monster tag enemy or just rename the tag to what ever.

using UnityEngine;

public class Radar : MonoBehaviour
{
    [SerializeField] Transform playerLocation;
    [SerializeField] float detectionRange = 50f;

    void Update()
    {
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

        foreach (GameObject enemy in enemies)
        {
            float distance = Vector3.Distance(playerLocation.position, enemy.transform.position);

            if (distance <= detectionRange)
            {
                Debug.Log($"Enemy '{enemy.name}' is {distance:F2} units away.");
            }
        }
    }
}

And dont use singeltons for this.

naive pawn
naive pawn
# fervent abyss

select the monster and each of its parents and make sure they're what you expect

polar acorn
#

My guess: The location you're printing is where the monster is. The value you see in the inspector is the local position, which is this object's position relative to the parent

sour fulcrum
#

if you debug a instance of MonsterLocation's position. you have a MonsterLocation at that position, full stop. it might not be where you think it is or where it should but the log wont be lying

polar acorn
#

You're logging global position, which is the position of everything all added together

fervent abyss
#

oh so what do i do then

sour fulcrum
polar acorn
fervent abyss
#

i js want the monster pos and player pos distance 💔

#

still why does it work just fine and as intended when equipped before the round

#

and doesnt after the round started

#

💔

polar acorn
# fervent abyss i js want the monster pos and player pos distance 💔

Run this code on your player:

Debug.Log($"Player {gameObject.name} is at {transform.position}, Monster {MonsterLocation.instance.gameObject.name} is at {MonsterLocation.instance.transform.position}, and the distance between them is {Vector3.Distance(transform.position, MonsterLocation.instance.transform.position}");
#

And show what it prints

fervent abyss
#

okay

slender nymph
#

don't forget you can add the object as context in the second parameter so it is highlighted in the hierarchy when you click the log

fervent abyss
polar acorn
fervent abyss
#

boiiiiiiii but it works fine if you equip it before the round or aka the monster spawns

polar acorn
#

Does that track with what you see if you have your handles set to "pivot" and select them each individually in the hierarchy

sour fulcrum
#

probably unrelated but is additive scene loading involved here?

sour fulcrum
#

whats your networkobject settings for the monsterlocation

polar acorn
#

Show a screenshot of both Radar and Bone selected in the scene window. The whole unity window, inspector, hierarchy, scene view, etc.

#

With your handles set up like this:

sour fulcrum
#

thats the transform

#

show the object

fervent abyss
#

oh k

fervent abyss
#

Oh m g

sour fulcrum
#

mhm?

fervent abyss
#

i do this

#

void Update(){
if (HasStateAuthority)
{
Body.position = new Vector3(LocalPlayer.instance.Head.position.x, LocalPlayer.instance.Head.position.y + bodyOffset, LocalPlayer.instance.Head.position.z);
if(distanceRotation){
Body.localEulerAngles = new Vector3(xRotation + LocalPlayer.instance.Head.eulerAngles.x, LocalPlayer.instance.Head.eulerAngles.y, 0);//Quaternion.Euler(xRotation + LocalPlayer.instance.Head.eulerAngles.x, LocalPlayer.instance.Head.localEulerAngles.y, LocalPlayer.instance.Head.localEulerAngles.z);
}
Head.rotation = LocalPlayer.instance.Head.rotation;
}
}

#

in rig player body

#

to offset the Bone transform

#

but i dont check for HasStateAuthority

#

basically each player sets it to themselves?

#

ima try

sour fulcrum
#

oh yeah thats totally what i was checking for

fervent abyss
#

wdym

sour fulcrum
#

my lead was a dead end but im glad you found that 😛

polar acorn
#

(Potentially a reason to avoid using singleons since it being accessible from anywhere means it can be modified anywhere)

fervent abyss
#

it works

#

💀

grand snow
#

My god make a local var for head fuck

#

Repeating the same access to the instance 5+ times isn't a good idea

past yarrow
#

But doesn't reloading the scene resets everything and recreate everything, including my GameManager ?

polar acorn
polar acorn
#

Well, the component will destroy itself. The Object will still be around

lucid geode
#

Hello world !

Sorry if my question is silly : I try to import on my script Cinemachine
The library is well installed with the unity registry, pretty sure of that
I add at the top of my script using Cinemachine; and this is not reconized : Assets/Move.cs(3,7): error CS0246: The type or namespace name 'Cinemachine' could not be found (are you missing a using directive or an assembly reference?)
I try a lot of things : reimport, reimport all, refresh, but nothing worked
Do you have an idea ? (i use Unity 6.1 on Linux Mint 22.1 Cinnamon)

Thx

polar acorn
slender nymph
lucid geode
#

No i don't have one (or i didn't see it ?)
I am on the latest version of Cinemachine, i've didn't take the official docs but i look on the internet and i found nothing (i'll go now on the official docs)

past yarrow
polar acorn
rich adder
slender nymph
#

that's also not quite right, but at least they can look at the documentation and see the right answer

naive pawn
#

also, are you perhaps using Start to initialize the board? that's only gonna be called once

lucid geode
rich adder
#

I'm just as lost as you now sorry lol

slender nymph
lucid geode
slender nymph
#

it's what you should have already done when i suggested it the first time

naive pawn
lucid geode
#

No joke, i was on the wrong docs, so i didn't find any info about that, and internet is not full of info outside the official doc, but sorry to bother

rich adder
naive pawn
lucid geode
#

Yep, it is Unity.Cinemachine, thx for the help (the doc link will serve a lot !!)

rich adder
#

holy hell I'm blind...I'll see myself out 🚶‍♂️‍➡️

rich adder
frail hawk
#

we will ignore all the helpfull answers you provided from now on

slender nymph
#

the UnityEngine namespace typically covers things built into the engine while the Unity namespace is typically used for packages

lucid geode
rich adder
slender nymph
rich adder
#

You click here you get the scripting part

past yarrow
rich adder
naive pawn
past yarrow
acoustic belfry
#

Hey, how StateMachines work? Or how to do so. I mean cuz im making an enemy and a lot of ppl say their code must need statemachines

slender nymph
#

there are many ways to implement a state machine. it could be as simple as a bunch of if statements or switch statement with something like an enum to differentiate between states, or something more complex like the animator (which is a state machine). there are dozens, if not hundreds, of tutorials covering how to implement a state machine

polar acorn
acoustic belfry
#

Oh, but also, why? I mean. What difference is between using functions with Ifs and with using statemachines?

rich adder
polar acorn
polar acorn
acoustic belfry
#

O h

#

Got it

#

If i have all system cored and coded into the "silly" (if and function) method, how hard would be to change it into statemachine?

polar acorn
#

Depends on how you designed it

acoustic belfry
#

Makes sense

#

Well, thanks

past yarrow
polar acorn
past yarrow
naive pawn
#

anywhere where it'd make sense

polar acorn
naive pawn
#

attached to a button, attached to onsceneload, done wherever the actual loading is, etc

past yarrow
polar acorn
past yarrow
past yarrow
past yarrow
ember tangle
#

How can I make the debugger only step through my scripts and never ever ever go into the engine files?

rich adder
ember tangle
#

I only want to see my own scripts, I dont need to see inside the engine

#

I want to disable this and 'step through' only what I have written.

rich adder
#

unless you mean Continue to hit the next breakpoint without going "Deep"

ember tangle
#

I need to go through my complete code without ever touching anything that unity provided

#

im tracking down something horrible, I probably have to make 50+ steps to find it, and I can handle moving 50+ steps through unity code that is not my scripts

naive pawn
#

if you're stepping manually, you can Step Out of a function or Step Over a function call

ember tangle
#

can I step out of a class? sorry im new to this type of debugging

naive pawn
#

you don't step out of classes
debugging, and arguably how code works in general (at a low level) is based on function calls in a stack

#

each function call creates a new context - that's the context you can step in/out/over

#

step in to a function call starts debugging each line of that function as it's being called
step over on that same function call skips debugging that function and goes to the next line in the current function
step out stops debugging the current function and goes to the line after the previous function call

random turtle
#

im having trouble programming damage dealing upon entering a box collider, each tutorial has the enemies sharing one big script, but mine have separate scripts so that they can have unique stats, how can i program lowering a variable from a collided objects script without the script name of the collided object always being the same

polar acorn
#

You should probably have a shared parent class that contains all the shared functionality of an enemy

#

But also, if the only thing that's different is stats, that should probably just be public fields you set in the inspector for the same script

eternal needle
eternal falconBOT
hallow sun
alpine crystal
#

Hi all

potent garnet
#

having trouble getting this to work

#

This is firing out of an empty gameobject, which is parented a little outside an enemy

slender nymph
#

you shouldn't be multiplying your forces by deltaTime, and if that is supposed to be some sort of projectile you wouldn't want the force applied to be time dependent anyway, it should be a FoceMode.Impulse force

potent garnet
#

but for some reason, the prefab I use (a cube) is not being launched out, instead it becomes stuck

potent garnet
#

It is launching out now, but now it's not even going towards the player, but rather in the same direction (to the right in this case)

slender nymph
#

it's going foward along the world z axis because that is the direction of force you have applied

potent garnet
#

Oh also why shouldn't I be multiplying by deltaTime? Wouldn't that make the forces run by frame, which is usually better?

potent garnet
slender nymph
potent garnet
#

Oh ok

slender nymph
potent garnet
#

alr i'll remember that

#

thanks for the help 🙏

umbral bough
#

!code

eternal falconBOT
queen adder
# random turtle im having trouble programming damage dealing upon entering a box collider, each ...

Along with the other suggestions, you can also use a C# Interface to have a damage function that any class can use.

public interface IDamage
{
    public void Damage(float amount);
}

And then you can use this interface in any class

//This can be an enemy class
public class AnyClass : MonoBehaviour, IDamage
{
    public float health;
    public void Damage(float amount)
    {
        health -= amount;
        //You can put anything you want here
    }
}

And then to call it from somewhere else:

if (other.transform.TryGetComponent(out IDamage d))
{
    d.Damage(damage);
}

If the object has a script thats using IDamage, the Damage function will be called in it. This is personally how I do damage/health in my projects most of the time.
I hope I am not misunderstanding the question, since I don't see anyone else suggesting Interfaces

acoustic belfry
#

Hi, for make my enemy current code into an statemachine, do i have to make other script or just use the one i have?

idk cuz i saw two tutorials and in the start they have two different scripts ._.

#

and seems...complex

polar acorn
acoustic belfry
polar acorn
acoustic belfry
#

and i felt that maybe using states would make it more easier to read, to modify and replicate for the other enemies i want to make, help me to understand better code, and fix the animation hierarchy issue.....

acoustic belfry
#

and i dont know how to make hierarchy for my anims, cuz they always overlap

polar acorn
polar acorn
acoustic belfry
acoustic belfry
#

what i do for the other enemies i copy my original enemy script and paste it on a blank script

acoustic belfry
#

huh?

polar acorn
#

Don't try to do complex animation logic using entirely .play

#

Use the animator. It's a powerful tool

acoustic belfry
#

define complex animation logic

is a 2d sprites game

polar acorn
acoustic belfry
#

ou

#

i mean cuz i have to make the enter and the out transitions, set them all to zero, etc

#

i dont know wich animation should conect to wich

#

is frustating

polar acorn
#

Think about what animation is playing, and what needs to happen for it to play something else

acoustic belfry
#

like the hierarchy?

polar acorn
#

No, like the Animator

acoustic belfry
#

no but i mean, for make the animator web i should think how i want my animations hierarchy to be

#

thats it?

polar acorn
#

What is a "hierarchy"

#

in regards to animations

acoustic belfry
#

two animations plays at the same time

#

i want the higher rierarchy one to play and shut the lower

polar acorn
#

Start thinking about what animations can play when, what conditions need to be for it to switch from one to another

acoustic belfry
#

i only need the animations to play when patrols, player distance reaches a radious, chases, shoots, hurts and dies

#

i thought the webs were only for 3D stuff

polar acorn
#

So start actually thinking it through.

#

Start with one state, consider what other animations could be played from that one

#

and when

acoustic belfry
#

idk i just need them to play inside an if, i dont know how to explain it ;-;

acoustic belfry
acoustic belfry
#

ou

#

then what i should do for make animation and events to match?

polar acorn
acoustic belfry
#

that instead of using a coroutine i use animation events

polar acorn
#

Start with a list of all animations you're going to need, then pick one and make a list of all the stuff that animation can transition to, and what needs to happen for that to occur

acoustic belfry
#

for example

patrol -> sight -> shooting

any state -> hurt -> dead

polar acorn
acoustic belfry
#

the distance of the player is below an specified float value

polar acorn
#

So, you'd make an animation parameter that is the distance, and make a transition between patrol and sight that checks if it's less than a given value

#

Then, in Update, set that parameter to the distance

acoustic belfry
#

o h

#

like a kind of if

#

but they both are fine

what trouble me is the hurt part for example

it fights with the patrol

#

hurt must be played when enters the state TakeDamage, to wich the enemy must wait still until the animation wich is less than a sec ends

polar acorn
acoustic belfry
#

o h

#

so thats the hierarchy

#

i mean

#

if we dont put a bridge

#

it will not go

polar acorn
#

no, it's a state machine

#

like the animator is designed to do

#

It's in one state. You specify which states it can go to next

acoustic belfry
#

i think makes sense

ember tangle
#

This line if (body.transform.position.y != 0) Debug.LogError($"{body.gameObject.name} position.y is non zero, {body.rigidbody.position}, {body.rigidbody.position.y}");

produces this console message:

#

And I do not understand it

#

why is the y coord different between the two?

slender nymph
#

it's rounded in the Vector3 display

#

or not rounded, but it only shows the first two digits after the decimal

ember tangle
#

well, the in game position of the objects matches the vector3, but the inspector shows the y value:

#

y is 0 for all intents and purposes in game

#

and in the math its impossible for y to not be 0

past yarrow
slender nymph
ember tangle
#

its to the power of something then?

#

i read it as 2

slender nymph
#

never use equality when comparing floats, use Mathf.Approximately if you need to compare them

slender nymph
ember tangle
slender nymph
#

how have you confirmed that the Y is always 0?

#

and even if you have confirmed that the Y is always 0, you should still never rely on equality when comparing floats

ember tangle
#

its a simplified Newtonian 2 body system, where all bodies have 0 on the y axis to start and initial forces are also y = 0. If its so small, I might just clamp it and hope nothing blows up later.

#

I only did the 0 check because I saw the y value change in the editor, forgeting about floating point math

potent garnet
#

I have an object pool script (that I wrote from a brackeys tutorial) that I'm trying to work with. The objects that I use that are pooled aren't reused properly though whenever I try to spawn them through the script's method

#
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;

public class ObjectPooler : MonoBehaviour
{
    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }

    public List<Pool> pools;
    public Dictionary<string, Queue<GameObject>> poolDictionary;
    #region Singleton 
    public static ObjectPooler instance;

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
            Destroy(gameObject);
    }
    #endregion

    void Start()
    {
        poolDictionary = new Dictionary<string, Queue<GameObject>>();

        foreach (Pool pool in pools)
        {
            Queue<GameObject> objectPool = new Queue<GameObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject prefab = Instantiate(pool.prefab);
                prefab.SetActive(false);
                objectPool.Enqueue(prefab);
            }
            poolDictionary.Add(pool.tag, objectPool);
        }
    }
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            throw new System.NullReferenceException("The referenced tag " + tag + "does not exist" );
        }

        GameObject objToSpawn = poolDictionary[tag].Dequeue();

        objToSpawn.SetActive(true);
        objToSpawn.transform.position = position;
        objToSpawn.transform.rotation = rotation;

        //Remove this with OnEnable later
        IPoolable pooledObj = objToSpawn.GetComponent<IPoolable>();
        if (pooledObj != null)
        {
            pooledObj.OnObjectSpawn();
        }

        poolDictionary[tag].Enqueue(objToSpawn);

        return objToSpawn;
    }
}
ember tangle
potent garnet
#

alr let me explain that in a second

slender nymph
#

i'm curious why you immediately enqueue the object back into the pool as soon as you get it?
also is there a reason you've followed a tutorial to write your own object pool instead of using unity's built in objectpool class?

potent garnet
#

so, if I set a maximum size for the pool, such as 5, there can only be 5 instances of that object that are continuously reused, that works. But whenever those objects are reused, they are not properly set at the position or rotation specified, and their events that should run on onEnable time do not run

slender nymph
#

well what does the OnObjectSpawn method for those objects do?

#

and by that i mean, please show the actual code and do not just provide a vague description of what you assume the code is doing (clarifying because too many times i've had that happen)

potent garnet
slender nymph
#

it's had it since 2021

potent garnet
#

first is the method from the class and the second is the case of usage

slender nymph
#

!code

eternal falconBOT
potent garnet
#

lemme get smth else

slender nymph
#

but again, we need to see the OnObjectSpawn method

potent garnet
#

yea that

#

The onEnable method just does this

#

it calls a seuqnces of tweens to animate the object

slender nymph
#
  1. #💻┃code-beginner message
  2. still need to see that OnObjectSpawn method
  3. i imagine that you probably want those sequences to start after you've set the position and rotation, so consider setting the object active after assigning those properties
potent garnet
#

so far, I'm going over the API for the built in object pool class, I think that might help me more if this doesn't work out

rough sluice
#

Which namespaces and classes I should have to learn first to create a basic 3D game?

slender nymph
#

that's a nonsensical question. you should learn how to use c# then learn the basics of just using the engine. you won't be learning specific "namespaces and classes", you'll be learning how to use the unity API.

twin pivot
#

also unity has some materials you can !learn from

eternal falconBOT
#

:teacher: Unity Learn ↗

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

slender nymph
#

there are beginner c# courses pinned in this channel and the pathways on the unity learn site will teach you how to use the engine

silver echo
#

does anyone know by chance how to write in collision between two spheres if im coding a 2d playformer with pygame

slender nymph
#

this is a unity server, perhaps go find a pygame related server and ask there

silver echo
#

i cant find one lol, thanks tho

slender nymph
#

also don't crosspost

soft turtle
vital zodiac
#

hii

#

whats the best unity editor version for my non gpu ryzen 5 5600GT build? i just want to make 3d simulator game for android

slender nymph
vital zodiac
#

ok

#

are you a mod

#

its confusing

#

who should i ask

#

the docs is not specific

teal viper
vital zodiac
#

is there any help channnel

past yarrow
#

How with this code in the code https://paste.mod.gg/jhlpgdozxjze/0 I keep sometimes getting a -1 tile on my first click please ? 🤔

private void OnMouseDown()
{
    if (GameManager.GameOver) return;
    if (Revealed) return;

    // Make the first tile never be a mine
    if (!firstClick) {
        print("firstClick");
        firstClick = true;
        if (Value == -1) {
            print("firstClick && Value == -1");
            Value = 0;
        }
        OnFirstTileClicked?.Invoke();
    }
    RevealTile();
}
keen dew
#

because it checks the tile's value before it has generated the mine locations

acoustic belfry
#

hey, how i can make an static script? I mean cuz i want to keep the life and other values of my player from scene to scene, and my plan is to send those values to a referenced static script, the thing now is. How

sour fulcrum
#

You probably want singleton manager class that's marked as dontdestroyonload

acoustic belfry
sour fulcrum
#

You don't have to, you can mark a class as completely static, but generally it's preferable to use a live instance for various benefits (being able to inspect it's properties, running coroutines etc.)

acoustic belfry
#

oh, makes sense

sour fulcrum
#

your also free to make a majority of it's usage static aswell (eg. its public functions and all that) where the code inside of them might point to the instance if necessary

eternal needle
# acoustic belfry hey, how i can make an static script? I mean cuz i want to keep the life and oth...

there is also this method https://docs.unity3d.com/6000.1/Documentation/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html or just putting the player in DDOL. The only downside would be having to manually destroy the character later
static itself here isnt required depending how u want to set it up. you likely have some script responsible for scene changes. around that logic is where you could copy values you want from the player, spawn a new player in the new scene, write the values.
lots of options

sour fulcrum
#

dontdestroyonload

acoustic belfry
#

oh

sharp bloom
#

Screenshot from a tutorial, I didn't quite understand the point of interface.

He said it's a contract for all weapons to require those methods, but doesn't the abstract class itself already do that?

sour fulcrum
#

the short answer is yes

the longer answer is that having the interface be the bottom foundation rather than the abstract class in a lot of cases is more flexible because your don't need to define it's class (eg. base, monobehaviour, scriptableobject) and that in a lot of cases you may want completely different "trees" of inheritance both spanning off the same base interface, or even having that interface come into play in the middle of the inheritence tree etc.

#

Based exclusively off that screenshot it's not the best example for why you would want a seperate interface for IWeapon but imagine if you instead had a IDamageSource interface, where that might be used on your weapons, environmental props, global things etc.

#

Same with the fact that it's equipable

burnt vapor
#

But it really depends on a lot of things

#

The easy answer here is that your abstract class is very likely to be enough. Anything using the IWeapon inferface likely uses the abstract class.

#

The point is that IWeapon is a small contract indicating a specific feature, whereas an abstract class is somewhat the same, but also allow for implementation of that feature (like reusable code between weapons)

clear juniper
#

generally you'd use a base class when there is shared functionality, and the child class "is a" base class. So a sword is a weapon - and all weapons have a sprite and display that sprite in the ui when they are equipped

interfaces are more about describing what something does. They are really good when you want a bunch of different things to have a common set of methods. In this case, maybe you've got a fireball, which inherits from SpellBase - but it's not a weapon, and doesn't need to do the same things as a weapon. However, it can still be equipped and used!

burnt vapor
#

An interface is commonly used for specific features which a class needs to implement. A good example is IDamageable, which would implement a Damage method. I can then check if this interface is implemented using pattern matching, and damage the given object.

#

Another important note, a class can have multiple interfaces, but only inherit from one abstract class. The latter is likely solvable with composition.

burnt vapor
#

If not, then an interface is just a lot easier. Your player likely just checks for this interface, then from there call one of its methods.

sharp bloom
#

Okay, thanks 👍

sharp bloom
#

Bruh why did I learn only just now about static event System.Action<T>, this shits so useful

#

I have been using UnityEvents but they're not that good if you need to pass any arguments

burnt vapor
#

UnityEvents allow you to pass arguments

#

Depending on your use case you can use Action, Func, EventHandler or UnityEvent. The only difference is that UnityEvent is not technically a delegate I believe

#

But UnityEvent does get serialized and can be used in the inspector

sharp bloom
#

Oh they do huh, ok mb

north kiln
burnt vapor
sour fulcrum
north kiln
#

I don't know what that means

sour fulcrum
#

like you dont need to do myAction?.Invoke()

#

the ?

north kiln
#

You would if the Unity event was null

sour fulcrum
#

yeah but doesnt System.Action throw if its not null but has no listeners?

sharp bloom
pallid nymph
#

saving typing a ? isn't all that much really 😄

sharp bloom
#

I guess it's more that if you forget it for some reason, it won't throw an error?

naive pawn
north kiln
#

Generally wouldn't be but that's besides the point

sour fulcrum
#

so you never know 😄

naive pawn
north kiln
naive pawn
#

delegates are ref types right thinkies

north kiln
#

Yes

past yarrow
grand snow
#

UnityEvent should not be null if serialized by unity.
delegate events can be null if there are 0 subscribers

#

hence why people do the ol event?.Invoke()

keen dew
queen adder
#

something weird about this tutorial
first this is not advanced im still a very beginner and this piece of code is for moving left and right in a 2d platforming
Now with the exact piece of code showing in the ss, the OP could move the character left and right what confuse me is there's no code line like "Input.GetKey" or "KeyCode.D"
I used to understand the code before I smash it into my VS sooo I wanna understand this

#

Note; I know in Unity 6 it's "LinearVelocity" not "velocity" our dude clarified it in the comments

grizzled crag
#

if you're holding down a key to the left, like the A key, it returns -1

#

if you're holding down a key to the right, like the D key, it returns +1

queen adder
grizzled crag
#

it's a defined thing in unity

queen adder
#

Alriiiiiiiight

queen adder
grizzled crag
#

"The meaning of this value depends on the type of input control, for example with a joystick's horizontal axis a value of 1 means the stick is pushed all the way to the right and a value of -1 means it's all the way to the left; a value of 0 means the joystick is in its neutral position." - unity docs

#

conversely, if you use the Vertical axis, it's gonna listen for the W and S keys

#

this also applies actually to the arrow keys

#

so if you try that code and hold down either the left or right arrow key it should still work

#

though for good practice you should use the new input system, there are a lot of videos online regarding it

queen adder
#

I see that Unity does thing by its own with no need to code it by the user Oh that's why it's called game engine

queen adder
grizzled crag
#

also! there's this 10 hour course on youtube, for free. Teaches you a lot of the basics and even some intermediate stuff. I suggest once you watch that course, you try to rely on your own programming so that you don't end up in tutorial helll

#

learn how to read the docs

queen adder
grizzled crag
#

everything should be in here

polar acorn
grizzled crag
#

it's project based which I really like

polar acorn
#

"Horizontal" is one of the default axes already set up

grizzled crag
# queen adder Alright what's the name of this course or the yt channel? + Are these docs avail...

💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
❤ Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🎮 Play the game on Steam! https://cmonkey.co...

▶ Play video
polar acorn
#

You can change or define more in the input manager window

queen adder
grizzled crag
#

I'm not very familiar with 2d in unity but I believe you're gonna have to just make a spritesheet outside of unity

wintry quarry
#

You'll need to decide which one you want to use first then find a tutorial

queen adder
clear juniper
#

you can't use skeletal animation with pixel art

#

well ok you technically can but it would look terrible and it definitely wouldn't be pixel art

oak mountain
naive pawn
#

seems that toolScript is null

#

if you want to share code, do so as shown below, not as a video
!code

eternal falconBOT
oak mountain
naive pawn
#

find out why it's null and make it not null

oak mountain
# naive pawn if you want to share code, do so as shown below, not as a video !code
#

the way i have it setup on the scene is, the tool script is on the tool prefab itself, weapon follows the same logic (but I havent tackled that one just yet), the tool prefab is inside of an empty object called "ToolsVM" and it's inside the main camera

#

(VM being viewmodel just for clarification)

past yarrow
#

Is there an equivalent to "OnMouseDown" but for right click please ?

oak mountain
past yarrow
pulsar helm
#

I don't think the function exists, but to achieve this, you can use the OnMouseOver function and then check if the right button is inputed with GetMouseButton(1)

#

Check this forum on this, someone made a video and there are even more workarounds if you need

cosmic dagger
#

Wouldn't it be easier to just use GetMouseButtonDown or GetMouseButton?

pulsar helm
#

In Update yeah it also works

naive pawn
oak mountain
naive pawn
#

i have no idea what you're referring to

#

i don't know what the context of your game is

#

assign to what?

oak mountain
polar acorn
oak mountain
naive pawn
oak mountain
naive pawn
#

it's a single slot, you can't have multiple tools in the single tool slot

oak mountain
#

thats exactly the problem

naive pawn
#

use an array or a list if you want to have multiple tools

wintry quarry
polar acorn
polar acorn
# oak mountain i dont follow

So, you have a script that has a variable ToolScript and you want to assign a Tool to a bunch of them at once, is that right?

oak mountain
polar acorn
polar acorn
# oak mountain ^^^??

The thing you're telling them you want to do and the thing you're telling me you want to do are different things

oak mountain
#

no it aint

polar acorn
#

So you're getting two different answers because you've asked two different questions

oak mountain
#

when did I ever ask two questions?

polar acorn
#

Here you say "I want to assign the same tool to multiple scripts that reference them" which is what I answered.

naive pawn
#

@polar acorn they asked a single ambiguous question and you answered without asking for clarification lol

polar acorn
#

Here you are saying "I want this one ToolScript to reference multiple different Tools" which is what Chris answered

naive pawn
polar acorn
#

These are two different situations

polar acorn
oak mountain
polar acorn
oak mountain
polar acorn
#

Because we each assumed a different thing you were doing, gave an example of it, and you said "Yes I want that one"

#

So how about instead, you say what you actually want to do

#

and then we can start from zero on the actual question

oak mountain
#

im going to ask again

how can I assign multiple objects with the same script on the player controller to avoid the null?

oak mountain
naive pawn
#

how you interact with them

oak mountain
polar acorn
oak mountain
oak mountain
#

i answered @ivory bobcat 's question to the context

naive pawn
polar acorn
oak mountain
eternal needle
#

A list and swap out what your primary tool is?

naive pawn
oak mountain
#

which i still dont know in this context

eternal needle
#

Dear lord I see multiplayer components here too.

naive pawn
#

@oak mountain you aren't being precise in your statements - "assign" isn't a valid action on its own, you assign to something

naive pawn
#

sounds like you need to step back and go through some c# fundamentals?

#

you're lacking the understanding to properly explain the issue or understand our answers

oak mountain
eternal needle
oak mountain
oak mountain
eternal needle
oak mountain
teal viper
eternal needle
oak mountain
oak mountain
frosty hound
#

There are multiple types of collections , which is what you're referring to.

#

Lists and arrays are just two.

oak mountain
#

i dont have the terminology fully down yet, apologies

polar acorn
# oak mountain how???? its a single slot script

So then it's assigned. It's not null. What is it that you want to do? You want to avoid the null reference exception - you've done that. If you add another copy of this script somewhere, assign a Tool to that.

eternal needle
#

The basics to what you'd be solving here is really any collection of Tools. Then you swap out what your active tool is

oak mountain
polar acorn
naive pawn
# oak mountain its almost as if we're in the beginner chat

we know and expect askers in this chat to not fully understand what they're doing - that's what a beginner is
the problem i'm referring to is that you're getting in too deep for yourself right now, and your issues are at a higher level than your understanding

oak mountain
polar acorn
#

You've assigned a value to the variable. It is not null.

oak mountain
eternal needle
#

I'm fairly certain they're thinking about this in the opposite way. Instead of null, its just nothing is referencing those other tools that may exist on the same GO as the player.

#

Unless I'm misunderstanding here

naive pawn
#

step back and think about the design first

polar acorn
oak mountain
eternal needle
polar acorn
polar acorn
#

When do you want that to happen?

oak mountain
#

i think both end up going for the same goal no?

polar acorn
#

You'd just change which Tool script that variable holds

oak mountain
#

so if I assign my tool for slot 1, when i press 1, it'll activate the game object that matches what i assigned in the inventory's quick slot and disable every other object

#

and since every prefab has the tool.cs, but the player controller is the script that controls the inputs, how can it control inputs of prefabs that aren't even active in the scene? thats why i wanted every tool to be assigned in the playercontroller's tool.cs field

polar acorn
oak mountain
#

so you're saying that its best to assign which tool the script is referring to through the quick slots?

acoustic belfry
#

what diferences a statemachine with a behaviour tree, and wich one is better for enemy ai?

naive pawn
#

they're pretty similar structures

rich adder
acoustic belfry
#

but what diference they have?

#

i mean, i already made four enemies with the if + function method but i dont like how i write them, so im seeking a way to convert them into a more profesional readable script

cosmic dagger
#

Have you searched what either of them do?

acoustic belfry
#

statemachine yes, tree no

#

cuz i just heard of it

#

now i did

naive pawn
#

you should probably google then

rich adder
#

most cases you will get away with a simple statemachine

acoustic belfry
#

makes sense

frosty hound
#

How does that suddenly make sense? lol

#

You asked a question that nobody has yet deep dove into (for good reason, it's a big topic) and now it makes sense. 🤔

acoustic belfry
unreal wigeon
#

So I have a problem. If My player triggers the warppoint it warps back and forth without break. I have this Code for the warppoint ```cs
[RequireComponent(typeof(Collider2D))]
public class Passage : MonoBehaviour
{
public Transform connection;
private void OnTriggerEnter2D(Collider2D other)
{
Vector3 position = other.transform.position;
position.x = this.connection.position.x;
position.y = this.connection.position.y;
other.transform.position = position;}}

past yarrow
#

I have all these errors and I don't understand where it comes from knowing that it doesn't give a script name nor a line where I can check 🤔 Could anyone tell me what could the issue be please ? https://paste.mod.gg/fjslcyeiaebl/0

rich adder
#

try restarting unity

#

when the namespace is UnityEditor in most cases its not your code per-se

polar acorn
#

Basically, if the place throwing the error is some gibberish mashup of numbers and letters instead of a script name and line number, it's internal

acoustic belfry
#

Hi, btw

what diference is using a timer (substracting a value using Delta.Time) or a Coroutine? wich one's better?

frosty hound
#

Using a manual timer by accumulating/subtracting time gives you more control. You can pause it, slow it down, speed it up, or modify it at any point.

acoustic belfry
#

o h, interesting

#

coroutines is more like when i want something to happens after something, right?

#

like, i want to shot 3 bullets consecutive, a timer may do the trick but may be too elaborated

frosty hound
#

They're powerful for sequencing things, yes.

acoustic belfry
#

nice

#

so is
actual timers = time
sequence = coroutine

frosty hound
#

They both use time, since you can yield to time in a coroutine.

nova bison
#

it starts unity project like unreal and doesnt have any highlighting

eternal falconBOT
green copper
#

how can I apply force to a 2d object from a specific point, instead of just perfectly along the center of mass?

I'm trying to acheive a 2d driving model that "feels" nice and weighty and "real" without going so far as trying to do real tire physics which would be a big scope increase

past yarrow
#

I have an issue. For some reason when I click on a tile that's zero (the tile with no number), it shouldn't be a zero tile if it has mine(s) next to it like in this screenshot example you can see in the second screenshot that I clicked on a mine that's next to the zero tile, so it's shouldn't be "0" by any mean but it's the case and I don't understand why 🤔 https://paste.mod.gg/vzhnlratqmtw/0

green copper
#

oh, that looks like it'd work perfectly, I don't know why I thought to google tire solutions but not that specific thing lol. I feel a bit silly, oops.

looks like a perfect solution, I can use it to push the car sideways at the front axle

green copper
#

if I have a tank I'd like to define, and I'd like to split the functionality into multiple scripts for readability, what would be the best way to structure that?

Ideall I'd like to be able to call Tank.setControls([control state data])

and Tank.fireGun()

but have setControls() and fireGun() in two scripts, one that handles driving physics and one that handles weaponry

Is that acheivable, or will I always need to call it like Tank.Controls.setControls()

and Tank.Weapon.fireGun()

rich adder
idle grove
#

im sorry, but i dont know what this error means, i dont remember switching anything called input handling, i dont know how to fix that, the video i found show a different situation that isnt mine

cosmic dagger
idle grove
#

im trying to set the player movement following a tutorial

slender nymph
cosmic dagger
green copper
#

im not sure whether to thank or curse you

#

because I can't not do it now

#

just unsure whether I'll make it a game mechanic or keep it just a dev tool

rocky canyon
#

why not bolf?

idle grove
#

there is no create action, what i do ?

slender nymph
#

it's not there because you already have an input action asset assigned

slender nymph
#

what was not clear about what i said?

idle grove
#

when was a input action asset assigned, the one that is outdated?

green copper
#

Ooo, I could split every vehicle into a locomotion type and a turret type, and then have smaller addon modules

The control script for addons can just be tweaked a little to send universalized inputs, so it goes from like, scanner.activate()

To just utilityslot4.activate() and make sure every utility script has an .activate() function

idle grove
#

how do i place it there, how do i update it

#

how do i do it

slender nymph
#

you already have one assigned. compare the two screenshots, but ignore the circled bit

idle grove
#

oh ok

#

i didnt knew it was created from the start

slender nymph
#

this is why people should be using the same editor and package versions as the course(s) they follow because little changes like this when you have 0 idea what you are doing and don't know enough to actually look at your own screen make following the courses difficult

idle grove
#

its hard to find something you want the way you want on the version you want man

#

should i delete the default one and make another? because the guide has this block of text which i have no idea how to follow when the thing is already created

#

should it be important?

#

i dont know

#

because unity's tutorial isnt following the same logic as my recently created project

slender nymph
idle grove
#

on a file i created today

#

or unity is outdated?

slender nymph
#

if you are following a structured course, then use the same version that the course teaches.

idle grove
#

well

#

then unity is outdated on their own tutorials then

#

i will try finding out what to do

slender nymph
idle grove
#

oh

#

you're right!

#

i was 2 versions under

#

now im on it

#

im sorry

nova bison
#

!IDE

eternal falconBOT
nova bison
#

VS still doesnt have any intellisense after I reinstalled it. Using latest unity and VS versions

#

It worked normally for anything else. I also went back and installed docs for the unity version I was using. Still no intellisense

naive pawn
nova bison
#

all of what is in this site tells me to set parameters that were already set by default and check updates that are already installed because i installed latest versions 5min ago

slender nymph
#

did you go through the troubleshooting steps in the link that i sent

nova bison
#

yes, i am going trough a different link now and its starting to work, i am restarting solution explorer solutions with dependecies

#

Is it possible to make it not say 0 references when the engine is referencing it with the movement component and starting it

naive pawn
#

what do you mean by "it"?

nova bison
#

"0 references" above method headers

#

and then it grays out my function

naive pawn
#

well i mean yeah they aren't referenced

nova bison
#

I am using it inside the editor

rich adder
#

the other ones get called by unity (they are messages like events so they get invoked by unity by method name)

nova bison
#

is there a way to make OnMove not grayed out (no color filter)

slender nymph
#

the 0 references refers specifically to your code. you are not using that method in your own code so it shows that

nova bison
#

and others methods I would write myself

#

I dont want to code in 0.7 opacity

slender nymph
naive pawn
naive pawn
#

(don't know how you could configure that, but i mean. it might be a thing. idk.)

nova bison
#

I could just make it public i guess

#

how do you do it?

rich adder
#

Use Generate C# class and opt for actual events think

indigo notch
#

Hi, I'm following the Unity Essentials Pathway and I've just got to the point where it teaches me how to code. It said that if the script doesn't open in an IDE I should reinstall Visual Studio, do i have the IDE?

naive pawn
#

yes, that's visual studio

indigo notch
#

Ohhh right

#

By the way

#

I noticed that the guy from the tutorial has this at the left side, which is the Unity Project folders. They dont show up for me in the Visual Studio, how can I enable this?

frail hawk
#

that is another IDE

indigo notch
#

Oh so it's not Visual Studio

slender nymph
#

They are using vs code, your are using visual studio (it's better)

indigo notch
#

Not gonna lie his looks better 😭

#

I guess that's visual studio but for Apple

frail hawk
#

it is not always about good looking

naive pawn
indigo notch
#

I see

frail hawk
indigo notch
frail hawk
#

you can expand the hierarchy but you already have your open scripts at top anyways. do not care about that too much

green copper
#

is there a way to use spritesheets outside of using them for looping animations?

specifically I made a spritesheet with a number counter, and one blurred "spinning" sprite to be an inbetween frame

I'd like to be able to call changeNumber(4) and the renderer displays the spinning sprite for a few milliseconds, then shows frame 4

I could just seperate the sprites out and make them selectively visible but that feels too hacky, and my googling efforts mostly find me tutorials about transitions from and between loops

naive pawn
#

are you using the actual animations systems for those at all? or just doing manual sprite swapping?

green copper
#

neither yet, trying to figure out which to use

#

I have the sprites in the form of a sprite sheet I exported from Aseprite

#

and it's sliced correctly

naive pawn
#

if you want to make an actual spinning animation and/or have each number have idle animations, you could use an animator now to give that flexibility for the future

#

but if not you could just have an array of those numbered sprites and a specific slot for that intermediate sprite and swap between them manually

naive pawn
green copper
green copper
naive pawn
#

you wouldn't have the blur sprite in the array, you would use it separately

#

the blur isn't the 10th number

green copper
#

oh, yeah that'd be easier lol

#

thanks!

past yarrow
green copper
#

So, in the past, when I needed to make an action take a specific amount of time, I always just did something like

FixedUpdate()
{

  timeSinceThingStarted += 1
  
  if (timeSinceThingStarted > amountOfTime && doingTheThing == true)
  { 
    doTheThing()
    doingTheThing = false
    timeSinceThingStarted = 0 
  }

}

I never thought to ask, is there a better way? Some

doTheThingInAWhile(function(), time);
naive pawn
slender nymph
naive pawn
naive pawn
past yarrow
green copper
#

in this specific instance, I just want to flash the blurred sprite for a few milliseconds, then show the updated number

looking for a solutionfor small, mostly unimportant visual stuff like that where getting granular about it feels like overkill but I don't know a better way

naive pawn
#

you tend to get this sort of pattern for important stuff:```cs
/* some update loop / {
float elapsed = 0;
while (true) {
elapsed += Time.deltaTime;
while (elapsed >= timeInterval) {
/
do thing */
elapsed -= timeInterval;
}
yield return null;
}
}

sour fulcrum
#

Imo coroutines are the nicest in most cases purely because it’s an excuse to move that logic into a dedicated function

green copper
#

I'd like something like


updateNumber(int number)
{
  sprite = blur;
  wait(30);
  sprite = numbersArr[number];
}

#

I'll look into coroutines

sour fulcrum
#

Yeah coroutines are literally that lol

green copper
#
private SpriteRenderer spriteRenderer;
private Sprite sprite;


spriteRenderer = GetComponent<SpriteRenderer>();
sprite = spriteRenderer.sprite;

Why does this not make sprite a reference to the component I can use to change the sprite?

If I made it sprite = GetComponent<SpriteRenderer>().sprite; it would if I understand correctly, why does it not in this case?

sour fulcrum
#

what is sprite on the second line

#

(Also the first line is just what you want?)

naive pawn
#

sprite isn't the component, it's just the current sprite of the component

sour fulcrum
#

(Aka it’s the photo and spriterenderer is the photo frame)

green copper
#

I was expecting sprite to be a pointer to the property of the componenet, but now that I'm saying it out loud I don't remember where I got the concept that it would stick like that

#

it might be leftover from visual basic from forever ago crossing a wire in my head

naive pawn
#

c# typically doesn't use pointers or references in that way

sour fulcrum
#

Yeah setting via getting like that gets you the value inside the box, not the box itself

naive pawn
#

idk visual basic, but sounds like what you're thinking of would be something like this in c/c++ terms

spriteRenderer = GetComponent<SpriteRenderer>();
Sprite *sprite = &spriteRenderer.sprite;
// or
Sprite &sprite = spriteRenderer.sprite;
#

which c# just doesn't really do

green copper
naive pawn
#

it's a reference, but yes same idea

#

the thing is, getting the sprite gives a reference to the actual sprite, not the spriteRenderer's property that holds said sprite

green copper
#

I think I see

Can I only make references to components, and not properties unless the property is itself a component?

naive pawn
#

no, references don't care about components
this is a c# thing, not a unity thing

#

imagine something like this:

Vector3 pos = transform.position;
```changing `pos` wouldn't affect the transform's actual position, right?
#

now that's a value type - changing the pos changes the actual underlying value
that value isn't linked to transform.position at all

but it goes a little differently with a reference type, because now there's 2 ways to change it - do you mean mutating it, or replacing it altogether?
in your scenario, sprite is a reference to some Sprite in memory
that's not directly linked to the spriteRenderer.sprite, they just happen to point to the same Sprite - that's what getting the reference is

so now if you change the actual Sprite that sprite points to, ie mutation, like sprite.pivot = new Vector2(0, 0);, that change propagates to spriteRenderer.sprite because it points to the same Sprite

but if you change sprite, as in the variable, like sprite = myOtherSprite;, that's reassignment - there was an indirect link to spriteRenderer.sprite via the underling reference, but not the actual sprite variable
so that doesn't affect spriteRenderer.sprite

grand snow
granite wave
#

Hey all, I have a question on object references. I was watching Tarodev's video on Object Referencing here: https://www.youtube.com/watch?v=dtv7mjj_iog&t=761s

I am unable to replicate what he is doing at the time stamp. Basically instead of using:

[SerializedField] private GameObject myGameObjectPrefab;
private GameObject _myGameObject;
private _myScript myScriptFromGameObject;

and then setting the private member via _myGameObject = Instantiant(myGameObjectPrefab);

AND then relying on _myScriptFromGameObject = _myGameObject.GetComponent<myScript>();

He is able to set the prefab serialized field from GameObject type to the prefab as a type, and also set the private member variable for the instantiated GameObject to the prefab type as well?

I am not able to get rider to accept this?

PSA: The "Unit" class is a simple class I created to represent a unit in my game. It's NOT an inbuilt class. Sorry for the confusion.

As a new dev, keeping references to game objects you need can be a little confusing. Learn how to store game objects for later use as well as allowing external scripts access to your goodies.

Instead of trying ...

▶ Play video
sour fulcrum
#

you want your prefab reference to be of that type

#

rather than GameObject

granite wave
#

Yes, so in my case the prefab is called Player, I cannot switch the serialized field or private variable to the prefab type

sour fulcrum
#

why

granite wave
#

he demonstrates in this, that if you do that you dont need to do GetComponent

sour fulcrum
#

why can you not switch the serialize field or private variable to the prefab type

granite wave
#

Rider says its wrong

sour fulcrum
#

what does it say

slender nymph
#

note that it isn't the prefab type, but rather a type of component that is on the prefab

granite wave
sour fulcrum
#

You do not have a class (and therefor Type) called Player

granite wave
slender nymph
#

presumably you want your prefab variable's type to be PlayerManager

granite wave
#

The prefab he supplies to his serialized field is fully instantiated

slender nymph
#

doesn't matter

granite wave
#

so you can make a gameobject's type one of its components?

slender nymph
#

you can drag a gameobject into a slot in the inspector for a variable that is of one of its components type

sour fulcrum
#

It's still a GameObject type instance that has multiple MonoBehaviour type instances on it as components, this just lets you be more specific/direct about what your doing

granite wave
#

hmm, yeah i dont know if i like this route, would you suggest i stick with the regular GameObject type for the serialized field and get my components as needed?

slender nymph
#

using the actual type you care about instead of GameObject is 100% better in all cases

granite wave
#

okay, thank you, appreciate the quick help

#

So in this case, what id like this script to do (among other things but ill figure those out), is look at the serialized field for a prefab, spawn that prefab, and then get another script component from that spawned prefab. Is using PlayerManager type instead of GameObject still the way?

slender nymph
#

if the prefab has a PlayerManager component on it, and that is the type of object you want to get from the instantiated object. then yes, your prefab variable should be a PlayerManager type, then you can directly assign the other variable the returned object from Instantiate with no need to call GetComponent

sour fulcrum
#

Because Unity enforces that

Every GameObject has a Transform
Every Transform has a GameObject
Anything deriving from MonoBehaviour has a GameObject (and therefore Transform). You can easily jump between these references. In some cases Unity builds in some of these functions to simplify their use too

granite wave
#

okay, understood, if i had a second script on PlayerPrefab (Lets say PlayerSkills), that was not PlayerManager in this instance I would need to GetComponent<PlayerSkills>() to get that additional one in this situation?

naive pawn
#

sure, or you might have a direct reference from PlayerManager depending on how it's set up

granite wave
#

okay, yes im tracking

#

extremely helpful, thank you both

sour fulcrum
#

components live on gameobjects

#

it's kinda comparable to components being employees inside a store (gameobject)

#

If you walk into a grocery store, you don't know who all the employees in the building are

#

but if you walk up to an employee, you certainly know what store they work at

granite wave
#

Yeah makes total sense, i think if anything I was thinking a bit too much on what I was seeing.

#

Question on Timelines:

In unreal, id often animate shader parameters and objects via sequencer (timeline basically).

In unity, ive historically done this via async tasks to drive shader parameters.

Async tasks, even when driven by curves and what not, tend to be difficult to dial artistically, where timeline allows for really nice sequencing and lookdev.

Is there some bad performance implication from using timelines vs Async Task tweening(my target platform is mobile VR)?

frosty hound
#

Timeline is just a collection of animations/animators, etc. It's no different than if you used those instead.

#

So no, there isn't any major performance difference than doing it in code (unless you're animating UI elements, which is a bit of a consideration if you're not breaking your canvases up properly).

mossy jasper
#

I love chat GPT, it gave me working player movement script🥹

sour fulcrum
#

just wait until you find out about google 😄

slender nymph
#

Or until they realize they move faster diagonally than they do if they only move along a single axis

queen adder
#

And input is in Fixed Update, not too big of a deal for continuous input but still not the best

acoustic belfry
#

i been studying some stuff, and correct me if im wrong but

stateMachine is basically that there is a main value currentState wich determines wich "block/cluster" of functions must play in the update for make it work more organizer and dont overlap?

#

but now this makes me the question, what diference is between using the stateMachine and using a Int value for each state

teal viper
acoustic belfry
#
    Idle,
    Patrol,
    Attack
}

State currentState;

void Update() {
    switch (currentState) {
        case State.Idle:
            IdleLogic();
            break;
        case State.Patrol:
            PatrolLogic();
            break;
        case State.Attack:
            AttackLogic();
            break;
    }
}```
teal viper
#

Just having an enum doesn't make it a state machine strictly speaking.

acoustic belfry
#

oh

#

then what does it?

acoustic belfry
#

idk im just seeing that my enemy and player script are too unpolished and i wanted to fix it

teal viper
# acoustic belfry then how i can make it a statemachine?

Again, it depends on what definition you want to follow. Wiki states this:
"A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time."

acoustic belfry
#

FSM i guess

teal viper
#

In this case as long as you have some code structure that can have multiple states but be only in one of them at the same time is a state machine.

acoustic belfry
#

yeah

#

thats the thing

teal viper
#

In more stricter scenarios, it might require you to have separate objects representing the state and the state machine itself

acoustic belfry
teal viper
acoustic belfry
#

and i only need to make my script more....organized

acoustic belfry
teal viper
teal viper
acoustic belfry
#

o h

teal viper
acoustic belfry
teal viper
#

Which might actually be what you want. It depends.

acoustic belfry
#

but i mean, both methods work for me, but wich one is actually better?

teal viper
#

Because you can expect yourself to remember what state corresponds to what index and even more so of new people that see your project for the first time.

#

It's also close to the concept of "magic numbers" which is a bad practice

acoustic belfry
#

makes sense

#

well, thanks

proven fiber
#

I'm building a 2d platformer in Unity 6

I've imported my tileset, sliced it into tiles, created a rule tile, added the possible combinations with the proper rules. Each tile in my tileset has 4 variants (so I have 4 floors for example).

When I'm placing tiles, the output is not randomly selecting from my list (of 4 floors for example).

Why is it not random and I how do I make it random?

slender nymph
mental oriole
#

I was making a angry bird game i wanted to render my 3 angry bird state according to scenrio like while its on rest it should be this image when i its flying it go to other image and when it hit it goes in 3rd image can anyone help

#

how can i do this

#

can somone guide me

#

i got a big sprite with all the images

#

is there a way to call all 3 images according to scnerio we can make like when its in air change to this sprite and on collision change to this ?

#

i can show u code how i have worked so far

unique quartz
#

this error shows up, i've set up a raycast thing and i think it's failing and crashing, all my objects have a variable assigned

NullReferenceException: Object reference not set to an instance of an object
SelectionManager.Update () (at Assets/scripts/SelectionManager.cs:28)

My line 28: interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();

cosmic dagger
ivory bobcat
cosmic dagger
#

Looks like three possible objects . . .

unique quartz
ivory bobcat
cosmic dagger
unique quartz
#

i just meant it in a general way, sorry

cosmic dagger
#

Variables are either a reference or a value type . . .

#

Only reference types can be null . . .

#

You are using reference variables on that line. You need to look at the line and find each variable that is a reference type. Then use a Debug.Log for each reference variable to check if it is null . . .

unique quartz
#

it came up with this i think i'm a little slow.. 😭

cosmic dagger
#

Did you just copy it into a random place in the script?

unique quartz
#

yes i'm unsure where to put it

#

should I have put it before line 28?

cosmic dagger
#

I'm just confused because you didn't even place it inside of the class . . .

unique quartz
#

i am new to coding I don't know where things go

ivory bobcat
unique quartz
#

ok thanks so i'll put it before line 28

cosmic dagger
unique quartz
#

Interactable: Branch_03 (1) (InteractableObject)
UnityEngine.Debug:Log (object,UnityEngine.Object)
SelectionManager:Update () (at Assets/scripts/SelectionManager.cs:31)

Transform: Branch_03 (1) (UnityEngine.Transform)
UnityEngine.Debug:Log (object,UnityEngine.Object)
SelectionManager:Update () (at Assets/scripts/SelectionManager.cs:30)

the two above is a grey speech bubble

This one is an error: NullReferenceException: Object reference not set to an instance of an object
SelectionManager.Update () (at Assets/scripts/SelectionManager.cs:32)

Is that what is missing?

ivory bobcat
unique quartz
ivory bobcat
# unique quartz

In the left image, look for the first blank log. Each log would print what item should have been printed followed by that item.

#

Click that log. The object with said component script in the scene will be highlighted yellow. Check the inspector for that object and ensure the component has a proper reference for the text variable.

unique quartz
#

yep i believe it does, at least it looks the same as the tutorial i'm following

ivory bobcat
unique quartz
#

i clicked on what was highlighted yellow

ivory bobcat
#

Show the script for SelectionManager using one of the two format !code

eternal falconBOT
ivory bobcat
#

interaction_text was null but you'll have to figure out why.

unique quartz
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SelectionManager : MonoBehaviour
{

    public GameObject interaction_Info_UI;
    Text interaction_text;

    private void Start()
    {
        interaction_text = interaction_Info_UI.GetComponent<Text>();
    }

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            var selectionTransform = hit.transform;

            if (selectionTransform.GetComponent<InteractableObject>())
            {
                Debug.Log("Missing/blank entries are null");
                Debug.Log($"Text: {interaction_text}", this);
                Debug.Log($"Transform: {selectionTransform}", this);
                Debug.Log($"Interactable: {selectionTransform.GetComponent<InteractableObject>()}", this);
                interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
                interaction_Info_UI.SetActive(true);
            }
            else
            {
                interaction_Info_UI.SetActive(false);
            }

        }
    }

}

ivory bobcat
#

So interaction_text is assigned in Start. It's gotten from the interaction_Info_UI component.
Check the interaction_Info_UI object that you referenced and make sure it's got a Text component.

unique quartz
#

yes it has a textmeshpro component

ivory bobcat
#

Well, TMPro isn't a Text component.

unique quartz
#

the tutorial said to do textmeshpro

#

how do i change it to a normal text one

ivory bobcat
#

Try Changing your interaction_text variable to type TMP_Text and your GetComponent<Text>() call in Start to GetComponent<TMP_Text>()

unique quartz
#

ok!

ivory bobcat
#

You may need to add the TMPro namespace

#

Right clicking that error should allow you to add the namespace as a potential fix

unique quartz
#

which option would I select

ivory bobcat
#

The option to import the TMPro namespace - quick actions and refactoring

unique quartz
#

and then which one? it has more options

#

sorry for having to have all this spoonfed

ivory bobcat
#

I can't see what you see.

unique quartz
#

sorry i am trying to screenshot it but it wont let me

ivory bobcat
#

Click the first option to import the TMPro namespace ie using TMPro

unique quartz
ivory bobcat
unique quartz
#

thanks yes I only did one and forgot about the other when I saw the error

ivory bobcat
#
private TMP_Text interaction_text;``````cs
interaction_text = interaction_Info_UI.GetComponent<TMP_Text>();```
unique quartz
#

yep done!

#

should the code work fine now?

#

i'll test it

#

still errors

ivory bobcat
unique quartz
ivory bobcat
#

Post an update of your code

unique quartz
#
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class SelectionManager : MonoBehaviour
{

    public GameObject interaction_Info_UI;
    TMP_Text interaction_text;

    private void Start()
    {
        interaction_text = interaction_Info_UI.GetComponent<TMP_Text>();
    }

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            var selectionTransform = hit.transform;

            if (selectionTransform.GetComponent<InteractableObject>())
            {
                Debug.Log("Missing/blank entries are null");
                Debug.Log($"Text: {interaction_text}", this);
                Debug.Log($"Transform: {selectionTransform}", this);
                Debug.Log($"Interactable: {selectionTransform.GetComponent<InteractableObject>()}", this);
                interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
                interaction_Info_UI.SetActive(true);
            }
            else
            {
                interaction_Info_UI.SetActive(false);
            }

        }
    }

}



#

no errors

ivory bobcat
unique quartz
#

😭

ivory bobcat
#

The error is suggesting that the referenced variable interaction_Info_UI does not have a TMPro_Text component.

#

Modify the logs to this: cs Debug.Log("Missing/blank entries are null"); Debug.Log($"UI: {interaction_Info_UI}", interaction_Info_UI); Debug.Log($"Text: {interaction_text}", this);and click on the UI log.

unique quartz
ivory bobcat
# unique quartz

After clicking, an object in the scene should become highlighted.

#

Check that object and see if it's got what you expect it to have.

unique quartz
#

yep my Interaction_Info_UI is highlighted

#

it still does have a tmp_pro component

ivory bobcat
#

Change your text field to this:cs [SerializeField] private TMP_Text interaction_text;and remove the Start method. Save the script.
In the inspector drag and drop the object with the TMPro Text component into the Interaction Text field of your Selection Manager.

unique quartz
#

what is my text field?

ivory bobcat
#

After serializing the field, you'll see the field in the inspector for the Selection Manager component.

unique quartz
#

yes but where do i write that code

ivory bobcat
#

You should be able to drag the object in the scene with the TMPro Text component into that field.

unique quartz
#

i already had dragged it in

ivory bobcat
#

Have you serialized your interaction_text field?

unique quartz
#

no i was askign where do i put that line

ivory bobcat
#

Instead of relying on Start, simply reference the field from the inspector

#

Where you declare the field in code

unique quartz
ivory bobcat
#

That would be where you'd assigned it.

#

You should have declared it above as a member of the class.

unique quartz
#

oh here?

ivory bobcat
#

You might want to take some (free) courses on c# and watch some Unity !learn tutorials

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
#

An example of referencing from the inspector: https://youtu.be/ac7PIcQs178?t=473

This is a basic tutorial on how to use Unity's TextMeshPro UI elements: InputField, Text, and how to code a button click to change these.

If you are already familiar with how to create the UI elements and want to jump to the code section go here: https://youtu.be/ac7PIcQs178?t=235

A very similar video but with Legacy UI can be found here: htt...

▶ Play video
unique quartz
ivory bobcat
#

In your case, you'd drag your object with your text component into that text field.

#

If it prohibits you from doing so, that object would be missing the necessary component or isn't within the same scope (an asset trying to reference some non persistent scene object etc)

unique quartz
#

i think i misunderstood oyu

ivory bobcat
#

I've got to go, good luck. You're missing the necessary basics to accomplish the current task. You may want to find someone to directly assist you or ask your professor for clarity/help.

unique quartz
unique quartz
burnt vapor
# unique quartz

Sorry but this is very basic C# logic. I can't imagine your school is giving you a task without giving enough time to at least learn how the syntax works

#

In your case you have a field with an attribute sitting in a place where namespaces are defined, which makes no sense. Data goes into a class.

#

After that you are missing namespaces and therefore many methods and types are unknown. Moving the field to a proper spot might already fix those.

unique quartz
#

pretty much everyone in the class is going horribly

burnt vapor
#

My suggestion is that you try making a basic console application and/or dive into some of the basics of C# to learn how the syntax works and how some of its features can be used to scaffold an application

#

I really don't mind helping with that, but I really suggest you do this without any involvement from Unity. You can't learn both at the same time properly without wasting a lot of time

unique quartz
#

will do! I appreciate the help as you and dalphat have been very patient, thank you

#

my assignment is due tomorrow however and i'm just trying to get this over and done with so i can start back from scratch next unit and work through the basics properly

burnt vapor
#

What is it you need to make exactly? I can't imagine anybody would get anything meaningful done if they haven't been teached the basics

#

I mean I don't mind helping you with this specifically because you seem like you want to genuinely learn it but I would definitely spend time learning C# as soon as you can

#

You should start with what I mentioned initially, and move the field into the class

unique quartz
#

i just restarted and made it a text instead of tmp

#

😭

naive pawn
#

that's not tomorrow tho

#

you got 2-3days depending on your timezone

burnt vapor
#

No, you should be using TMP (TextMeshPro). The one you switched to is old and should not be used.

#

Not to mention it is not the issue you are having. You need to move the field into the class.

#

@unique quartz

unique quartz
burnt vapor
#

I mean if it's not a game with any requirements then I'd just make pong or something

unique quartz
#

😭

burnt vapor
#

Well I can't really help with that, especially since I am at work

#

I don't mind fixing any issues you have though

#

Did you fix the issue by moving the field?

unique quartz
#

i'm just doing the tutorial now but with tmp again

#

give me five and i'll do it

sour lintel
#

Hi! There's so many channels and stuff, so Idk where to ask for this, but going to give this one a shot.

So, i'm trying to make a lethal company mod, and they have an sdk thing to replace the player models, but when I import it, it fails to compile with these errors


Library\PackageCache\com.bunya.modelreplacementsdk@91ccd7f277\Editor\RotationOffsetEditor.cs(7,7): error CS0246: The type or namespace name 'Codice' could not be found (are you missing a using directive or an assembly reference?)```
I asked them about it, they didn't know how to fix it so I was hoping someone here have seen these happen before and how they fixed it.
sour fulcrum
#

no modding on the server

#

lc modding server only

sour lintel
#

Well, this is a unity problem

sour fulcrum
#

no

#

you cannot get the help you need here

unique quartz
#

the raycast is a bit odd though 😭

#

it works but it doesnt lol

burnt vapor
#

Hard to say without code

unique quartz
# burnt vapor Hard to say without code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SelectionManager : MonoBehaviour
{

    public GameObject interaction_Info_UI;
    Text interaction_text;

    private void Start()
    {
        interaction_text = interaction_Info_UI.GetComponent<Text>();
    }

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            var selectionTransform = hit.transform;

            if (selectionTransform.GetComponent<InteractableObject>())
            {
                interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
                interaction_Info_UI.SetActive(true);
            }
            else
            {
                interaction_Info_UI.SetActive(false);
            }

        }
    }
}```
burnt vapor
#

That looks about as good as it can get tbh

#

This would mean the raycast hit the object properly, so it might be the object that is at faulth here @unique quartz

#

I'd check the collision of the object, which is likely much bigger than you think

north kiln
unique quartz
burnt vapor
unique quartz
#

how do i do that?

burnt vapor
#

Definitely also try what vertx suggested, even if it's just as a bit of an excercise.

unique quartz
#

okay!

potent garnet
#

What is the best way to design a boon system like Hades

#

Just any general implementation methods I should do

limpid cloak
#

hey all, last week i started going through the unity tutorial and the C# codeacademy course, since i have a game idea i wanted to prototype. considering i am new to both programming in general and unity, is there a particular document or course that teaches how the two integrate and what all the commands available do?

frosty hound
#

Asking what "all the commands" do is a question nobody can answer, nor is it the right approach to learning to make games (or coding).

The Unity Learn tutorials already teach you how to do both for simple things. Most people turn to YouTube for more tutorials, but you can quickly find yourself in tutorial hell.

Start with smaller projects using what you learned off the things you've already went through, instead of aiming to prototype your game idea.

brave robin
# potent garnet What is the best way to design a boon system like Hades

More of an advanced coding question, but the boons - and most of the other data - can be done as scriptable objects. You'd create an abstract scriptable object class for all boons, with abstract methods for its functionality, and then create the derived ones per boon.
You'd also need a way for the boon to influence in-game mechanics, like "do +25% more damage when hitting an enemy suffering from coffee stained clothes", so a game event system that allows an active boon to listen for the event in progress, read its parameters, check its conditions, and modify its outcome will be handy

potent garnet
naive pawn
echo ruin
naive pawn
#

i had that issue for quite a long while and i didn't notice any effects, but it's not too hard to guard against to prevent potential issues
imo it's unnecessary noise in the console as well

polar acorn
#

If it only happens when you stop the game, it's probably a race condition - something is destroyed before this object that this one depends on

#

It might be a problem, since it would also throw this error when changing scenes, if this object is a DDOL.

#

It's kind of an edge case though, unlikely to matter

echo ruin
#

Yeah, that's what I was thinking. I'm using object pooling. Enemy units add themselves to a queue before they get disabled.

polar acorn
#

Probably wouldn't worry about it unless either this object or the one that's throwing the NRE are DontDestroyOnLoad objects

echo ruin
#

I'm using a function that finds the correct queue to add them to. I'm guessing either the queue or function gets destroyed before the unit is

rocky canyon
#

yessir, add some logs to know for sure

naive pawn
#

functions don't get destroyed

echo ruin
#

Or the component

naive pawn
#

anyways if the context of the issue is something that won't be relevant for disabling via destruction or scene changes, you could set up a bool that's set via OnApplicationQuit, that'll be called before OnDisable

rocky canyon
#

andy simply make sure ur utilizing those functions..
OnDestroy() OnDisable() etc

echo ruin
#

The error is within OnDisable

rocky canyon
#

basically "Clean up" before closing

#

ohahhh u can also see if u can see whats happening w/ the stack thingy at the bottom of the console

#

shows -> the order -> of how scripts are communicating/getting to that point

echo ruin
#

Oh right

#

I'll try to check that out, if it wants to replicate

rocky canyon
#

i forget which order it goes..

#

i think the top is the newest, and bottom is older

naive pawn
echo ruin
#

That's literally it lol

rocky canyon
#

ohh

#

mb

naive pawn
#

you can, yes

rocky canyon
#

my enemy pooling did something similar,
my workaround was just checking if the pool wasn't null before adding or removing themselves

naive pawn
#

there was a forum that discussed that but i don't remember any of the keywords

rocky canyon
#

or a list actually

echo ruin
#

I fixed it with if (parentPool != null). I should honestly do that more often

rocky canyon
#
void OnDisable()
{
    if (isQuitting || enemyList == null) return;

    if (enemyList.Contains(this))
    {
        enemyList.Remove(this);
    }
}```
naive pawn
#
class GameManager : MonoBehaviour {
    public static GameManager instance;
    public bool quitting { get; private set; } = false;
    void OnApplicationQuit() {
        quitting = true;
    }
}

class PlayerController : MonoBehaviour {
    void OnDisable() {
        if (GameManager.instance.quitting) return;
        /* ... */
    }
}
```this is how i did it
#

huh, i should probably make my singletons use props

#

your code has been randomly selected for review, please do not resist

echo ruin
#

On another note, and I know it might not be related. I started getting this one at the same time

#

Is that normal?

rocky canyon
echo ruin
#

I figured

rocky canyon
#

cloud stuff..

#

no clue there lol ¯_(ツ)_/¯

naive pawn
rocky canyon
#

one of them odd unicode chars

naive pawn
#

weirdly enough, copying that to my browser, the last star shows up but not the others

rocky canyon
#

must not work across all platforms

naive pawn
#

ah it's because you got them from different blocks for some reason

rocky canyon
#

chatgpt problems

#
 public class GameManager : MonoBehaviour
    {
        public static GameManager Instance { get; private set; }

        public bool IsQuitting { get; private set; } = false;

        void Awake()
        {
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject); // prevent duplicates
                return;
            }
            Instance = this;
            DontDestroyOnLoad(gameObject); // optional: if GameManager lives across scenes
        }

        void OnApplicationQuit()
        {
            IsQuitting = true;
        }
    }``` this was their 5-star "remix"
#

which is the exact same thing.. but with an Awake() function which im sure u'd have anyway 😅 lol

#

i wonder if theres a reason that u'd use a flag in the singleton as isQuitting and referencing that.. thats any different than just using Application.quitting

naive pawn
# rocky canyon *chatgpt problems*

instead of BLACK STAR (U+2605) and WHITE STAR (U+2606) both from Miscellaneous Symbols, you got HEAVY FIVE POINTED BLACK STAR (U+1F7CA) from Geometric Shapes Extended (no white version, only a light version)

naive pawn
#

Application.quitting is an event, not a bool

#

ik it looks like a bool lol

rocky canyon
naive pawn
#

happened to me the first time too lmao

rocky canyon
#
void OnEnable() {
    Application.quitting += OnAppQuit;
}``` so something like this then
naive pawn
#

probably in Awake