#💻┃code-beginner

1 messages · Page 692 of 1

rocky canyon
#

digiholics analogies go hard 😄

frail hawk
#

i like your examples digi, the one with the cat dishes was also nice

sharp solar
#

its easier to access clothes on the sofa until the sofa has like 100 clothes on it

rocky canyon
#

yea i missed out on the cat bowl one

kindred iron
#

yeah u are right but normally u shouldnt get a script from an another script so u need use observer pattern am i right?

#

i saw it so

#

and

#
public class HealthUI : MonoBehaviour
{
    [SerializeField] private GameObject healthBar;
    [SerializeField] private Health playerHealth;

woulndt it be better to just get the hp and maxhp form this playerHealth?

#

its not observerpattern

#

cuz i dont need an event at this point

rocky canyon
#

events are helpful for things like this scenario...

-> why would you update the UI every single frame unless the health has changed from the last value it had...

sharp solar
#

is an event just when you tell something to call this method when something happens

frail hawk
#

kind of

wooden hill
# sharp solar like a callback

first you subscribe to the event from places that are interested in the event.
then you call the event from one place (or multiple places) which means it will call the corresponding method on all subscribers.
Kind of like when you upload a video on youtube and it notifies every subscriber about it.

kindred iron
#

@polar acorn i made a projectile which i shoot and used observer pattern but im asking myself if it was better before can u read it?
with observer pattern:

public void OnTriggerEnter2D(Collider2D collision)
{
    if (!collision.CompareTag("Wall"))
    {
        EventManager.SendDamage(new DamageEvent(damage, collision.gameObject, owner));

        if (collision.CompareTag("Enemy") || collision.CompareTag("Player"))
        {
            SoundManager.PlaySound3D(SoundTypes.OnHitSoundEffect, transform.position, 0.8f, Random.Range(0.9f, 1.1f));
        }

        Destroy(gameObject);
    }
}

without observer pattern:

 public void OnTriggerEnter2D(Collider2D collision)
 {
     if (!collision.CompareTag("Wall"))
     {
         //EventManager.SendDamage(new DamageEvent(damage, collision.gameObject, owner));
         collision.gameObject.GetComponent<Health>().TakeDamage(damage);

         if (collision.CompareTag("Enemy") || collision.CompareTag("Player"))
         {
             SoundManager.PlaySound3D(SoundTypes.OnHitSoundEffect, transform.position, 0.8f, Random.Range(0.9f, 1.1f));
         }

         Destroy(gameObject);
     }
 }
drowsy flare
#

Okay so I instantiate a prefab as a GameObject using something like:
GameObject BackgroundObject = Instantiate(BackgroundType, transform.position, Quaternion.identity) as GameObject;
Where BackgroundObject is my prefab. That prefab has a script with a SerializeField variable, which I would like to populate with a value when I'm instantiating it.
I guess this might be really easy if you know how, but I'm so lost. Any ideas?

naive pawn
#

type BackgroundType and BackgroundObject as that script instead of GameObject, and have the script provide a public property/initialization method you can feed values to

rocky canyon
#
[SerializeField] private BackgroundScript backgroundPrefab;

BackgroundScript spawnedPrefab = Instantiate(backgroundPrefab, position, Quaternion.identity);
spawnedPrefab.MyValue = someValue;```

something like this is how i generally do it
rocky canyon
#

or use a method

#

spawnedPrefab.Initialize(someValue);

drowsy flare
#

Hmm yes using a method might be the way after all

rocky canyon
#

the take-away being that u can use the Script as the Type.. so instead of a gameObject and then needing to use a getComponent

#

u can just instantiate it using w/e the class is (and already having that reference ready to roll)

drowsy flare
#

Haha yeah that's probably what I should do. I should have done it to start with, but the thing I'm doing is so minor so it felt like overkill. But yes, you're right.

rocky canyon
#

👍

topaz hatch
#

All set up! Thanks y'all for letting me know about the whole Library/Class thing.

ember tangle
brazen aurora
#

my game has prefab dungeons that are instantiated and then the old one is destroyed to show that your moving onto the next room. my character can pickup weapons and drop them by changing the parent of the weapon. However, the way i have this set up, when the player switches weapons, the parent of the old one is now null, which causes the weapon to not be destroyed along with the dungeon. is there anyway i can change the parent of the wweapon to whatever dungeon room is currently in the scene? ive been trying for a while and cant find anyway
code for holding weapon:

    {
        if (interact)
        {
            if (!isHolding)
            {
                if (collision.CompareTag("Weapon"))
                {
                    collision.transform.SetParent(grabPoint);
                    collision.transform.position = grabPoint.position;
                    collision.transform.rotation = pivot.rotation;
                    weaponController = collision.gameObject.GetComponent<Weapon>();
                    activeWeapon = collision;
                    isHolding = true;
                }
            }

            else if (isHolding)
            {
                if (collision.CompareTag("Weapon"))
                {
                    activeWeapon.transform.SetParent(null);
                    collision.transform.SetParent(grabPoint);
                    collision.transform.position = grabPoint.position;
                    collision.transform.rotation = pivot.rotation;
                    weaponController = collision.gameObject.GetComponent<Weapon>();
                    activeWeapon = collision;
                    isHolding = true;
                }
            }
        }
    }```
#

code for creating next room

    {
        if (currentRoomNumber >= 0 && currentRoomNumber < 50)
        {
            currentRoomNumber++;
            Dungeon _newDungeon;
            newDungeon = Instantiate(dungeonPrefab[0], transform.position, transform.rotation);
            _newDungeon = newDungeon.GetComponent<Dungeon>();
            _newDungeon.RandomSpawn();
            spawnedChest = false;
            Destroy(gameObject);
        }
    }```
vast matrix
#

I'm attempting to code a script that allows me to move the player camera, but it only moves vertically in a very weird way (idk how to explain it) this is my code ```using UnityEngine;

public class PlayerCameraFollow : MonoBehaviour
{
public float SensX;
public float SensY;

public Transform PlayerPosition;

public Transform Orientation;

float XRotation;
float YRotation;

private void Start(){
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
    transform.position = PlayerPosition.position;

}

private void Update(){
    //get mouse input
    float MouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * SensX;
    float MouseY = Input.GetAxisRaw("Mouse X") * Time.deltaTime * SensY;   

    YRotation += MouseX;
    XRotation += MouseY;

    XRotation = Mathf.Clamp(XRotation, -90f, 90f);

    //Rotation Cam & Orientation
    transform.rotation = Quaternion.Euler(XRotation, YRotation, 0);
    Orientation.rotation = Quaternion.Euler(0, YRotation, 0);
}

}

frail hawk
#

you got it double with Mouse X

vast matrix
#

oh ok ty

#

I didnt notice that lol, but it works now

frail hawk
#

glad you fixed it

brazen aurora
#

can someone help me with my problem?

fickle plume
eternal falconBOT
frail hawk
#

they already did but tldr

fickle plume
#

@brazen aurora You should link your question if you are bumping it.
As to your question, if you are passing object between objects that being destroyed, you need to pass it first or hold its reference first by an object that will not be destroyed, like a managing script.

hollow mirage
#

Hi, I am working on a 3rd person controller that moves by clicking. when reaching a height it slides down but is supposed to stay on the terrain, no matter how steep the terrain is

fickle plume
#

If you are using physics, you need to have enough friction not to slide, or turn it kinematic while stationary.

hollow mirage
#

public class SimpleClickToWalk : MonoBehaviour
{
    public Camera mainCamera;         
    public LayerMask groundLayer;    
    public float moveSpeed = 5f;     

    private Vector3 targetPosition;
    private bool isMoving = false;

    void Start()
    {
        if (mainCamera == null)
            mainCamera = Camera.main;

        targetPosition = transform.position;
    }

    void Update()
    {
        HandleClick();
        MoveCharacter();
        StickToGround();   
    }

    void HandleClick()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit hit, 100f, groundLayer))
            {
                targetPosition = hit.point;
                isMoving = true;
            }
        }
    }

    void MoveCharacter()
    {
        if (!isMoving)
            return;

        Vector3 direction = targetPosition - transform.position;
        direction.y = 0;

        if (direction.magnitude < 0.1f)
        {
            isMoving = false;
            return;
        }

        Vector3 move = direction.normalized * moveSpeed * Time.deltaTime;

        
        if (move.magnitude > direction.magnitude)
            move = direction;

        transform.position += move;

      
        if (move != Vector3.zero)
            transform.forward = move.normalized;
    }

    void StickToGround()
    {
        Ray ray = new Ray(transform.position + Vector3.up * 1f, Vector3.down);
        if (Physics.Raycast(ray, out RaycastHit hit, 10f, groundLayer))
        {
            Vector3 pos = transform.position;
            pos.y = hit.point.y;
            transform.position = pos;
        }
    }
}```
elder hearth
#

Hi! I'm a new dev in unity and this is my first game that im making without tutorials and my mouse isnt being Picked up in the game while running, this is for my script to look around. Also its picking up my controller(Xbox if that matters). Oh and my mouse(in the new Input system(and im unity 6)) is action type is Value and control type is Vector 2, the binding is Delta [mouse]

eternal falconBOT
elder hearth
elder hearth
keen dew
#

Did you set a value for the sensitivity field

elder hearth
#

Yes

#

Ive set everything i need ion the player prefab

keen dew
#
Debug.Log($"lookAction: {lookAction.ReadValue<Vector2>()}, sensitivity: {Sensitivity}");

Put this in the MouseLookingAround method and see what it prints

elder hearth
#

ok

#

Without using a xbox controller

lookAction: (0.00, 0.00), sensitivity: 2
UnityEngine.Debug:Log (object)
PlayerMovement:MouseLookingAround () (at Assets/Scripts/Player movement.cs:97)
PlayerMovement:Update () (at Assets/Scripts/Player movement.cs:58)

With using a xbox controller

lookAction: (0.25, -0.97), sensitivity: 2
UnityEngine.Debug:Log (object)
PlayerMovement:MouseLookingAround () (at Assets/Scripts/Player movement.cs:97)
PlayerMovement:Update () (at Assets/Scripts/Player movement.cs:58)
keen dew
elder hearth
#

Okay

#

Why ui tho?

keen dew
elder hearth
#

Its okay lol

drowsy flare
solemn tundra
#
if (Input.GetKeyDown(KeyCode.Space)) 
{
    animator.SetTrigger("Jump");
}
#
if (Input.GetKeyDown(KeyCode.Space) && !IsGrounded) 
        {
            animator.SetTrigger("Jump");
        }
#

does anyone know how i would allow the player to jump when touching the ground and play the jump animation, but if the player is not grounded dont play the animation (if the player is pressing jump mid air). if i use the code on the topthe player can play the jump animation will mid air, but if i use the code on the bottom the player has to press jump mid air again after jumping to actually play the jump animation. plz help

wintry quarry
#

! means "not"

#

It should be if (Input.GetKeyDown(KeyCode.Space) && IsGrounded), no?

polar acorn
solemn tundra
#

if i use !IsGrounded then the player jump animation doesnt play bc their grounded but if the play presses space again mid air the animation plays, i what the animation to play once while on the ground and not allow the player to press space again to play the animation again mid air.

#

if i use just IsGrounded then the player can spam jump and the animation plays mid air

fickle stump
#

yeah i mean you're checking if you're not on the ground instead of checking if you're on the ground

fickle stump
#

ye

polar acorn
rich adder
#

show us how you check/assign IsGrounded

solemn tundra
solemn tundra
polar acorn
rich adder
elder hearth
solemn tundra
#

idk if this helps

rich adder
#

just make sure IsGrounded parameter is linked to the IsGrounded in code / from raycast

#

its hard to tell from here, maybe you should make a video with the animator window pulled up and try jumping so you can see what animator is doing

wintry quarry
#

sounds like it reaches too far down

sharp solar
#

is it possible to generate and play audio realtime in unity?

wintry quarry
#

sure

sharp solar
wintry quarry
#

that's an option, sure

sharp solar
#

is c# plenty fast enough to do this thousands of times per frame?

solemn tundra
#

im watching a yt video about jumping and it seems the best way is to section the jump animation into 3 parts (jump, fall, land) ill add this and see how it looks

sharp solar
#

is sending data from gpu to cpu pretty fast as long as i do it in large chunks

#

by fast i mean

#

not latency fast, but data rate

sour fulcrum
#

This probably isn’t beginner level talk if you need proper specifics

#

“Pretty fast” isn’t a particularly helpful metric

silk night
sharp solar
#

can you call a method through inspector

#

ive made a test one public but cant figure out how to invoke it

wintry quarry
sharp solar
wintry quarry
wintry quarry
sharp solar
#

ill check out naughty attributes

rich adder
#

its less nice looking than a button but requires no extra code beside the attribute built in
( your right click on the component and it shows up)

sharp solar
#

perfect

keen fiber
#

How could I make my crouching smoother? I'm pretty sure when I crouch it resizes the controller's height from the center so it drops and then when I stand back up it hits the ground so it snaps. I've tried to immediately move the player down when they crouched by doing transform.localPosition -= new Vector3(0f, number, 0f); but that didn't work. Any help?

rich adder
keen fiber
#

I don't see how that would help since the character controller would still fall when it gets sized down

#

this is what i want it to do

rich adder
keen fiber
#

Like I said, I tried doing that with transform.localPosition -= new Vector3(0f, number, 0f); but that didn't work. If I edit the center of the Character Controller then the gun doesn't move with the camera.

rich adder
#

this dude has good video on it
https://youtu.be/-XNm7dPVVOQ?t=572

Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!

Join me and learn your way through the Unity Game Engin...

▶ Play video
rich adder
#

the position should not be touched at all.. all you're doing in ideal situation is shrinking and shifting the collider itself

#

the weapon thing can be addressed easily after that

#

the timestamp I linked explains the process

#

nary an issue with this method and its pretty common

wicked fiber
#

How would I define a parent in code? Ex: transform.position.parent

polar acorn
#

Transforms do

wicked fiber
#

How would I find the transform of a parent?

polar acorn
#

The parent is a transform.

wicked fiber
#

Oooooooh

wicked fiber
#

thank you both

hazy crypt
#

Hey guys, Im trying to serialize some data, ive got it working saving and loading a single float, but now im trying to serialise a class of seralizable data. all of the data is serializable in the data class, and my saving method isnt failing, but when I try to load im getting an error saying that nothing was saved in the file path

#

I can show my code

sharp solar
#

in compute shaders its fine to set unsigned integers using the setint method right?

hazy crypt
#
{
    public static void SaveGhost (RecordTo recordTo)
    {
        BinaryFormatter formatter = new BinaryFormatter();

        string path = Application.persistentDataPath + "/playerGhost." + recordTo.levelName;
        FileStream stream = new FileStream(path, FileMode.Create);

        GhostData data = new GhostData(recordTo);

        formatter.Serialize(stream, data);
        stream.Close();
    }

    public static GhostData LoadGhost(string levelName)
    {
        string path = Application.persistentDataPath + "/playerGhost." + levelName;
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            GhostData data = formatter.Deserialize(stream) as GhostData;
            stream.Close();

            return data;
        }
        else
        {
            Debug.LogError("Filepath does not exist in " + path);
            return null;
        }
    }
    
}
wintry quarry
rich adder
hazy crypt
rich adder
#

is there a reason not to just use Json serialization ?

sharp solar
sharp solar
#

oh, well im using int in behaviour and uint in shader, is there anything inherently bad about doing that

hazy crypt
sharp solar
#

is this likely to bug out sometimes

hazy crypt
#

Its a competitive racing game

wintry quarry
hazy crypt
#

But thats fine, ill look into other methods

rough granite
sharp solar
polar acorn
rich adder
hazy crypt
sharp solar
#

shader stuff seems to always use int not uint so i guess i will just switch it to int

hazy crypt
rich adder
#

you could do TOJson then use SHA type algo to scramble it

polar acorn
rough granite
sharp solar
hazy crypt
wintry quarry
wintry quarry
#

e.g. protobuf, messagepack

hazy crypt
#

I have no server

rich adder
#

I usually do SHA512 and its good enough, if someone really wants to they can decompile it and find out which algo you use and possibly a the Key if you stored it in the same code.. but at least deters regular joes from it

rich adder
hazy crypt
#

one small step at a time 🦾

rough granite
rich adder
#

the free tier is pretty generous

#

you probably wont ever run out unless you get insane amount of traffic, and if that were the case you should be earning enough for it lol

hazy crypt
#

im just enjoying making it i dont care about the money

#

but i see your point

rough granite
rich adder
rough granite
#

though off topic how do i get unity to register earnings? cause i've made some money from selling a game off itch.io but unity still says $0

hazy crypt
#

The unity one would probably be fine, as long as theres enough documentation for me to start understanding how to use it

rich adder
hazy crypt
#

Also if it lets me upload and download my ghosts

rough granite
rich adder
wintry quarry
rich adder
rough granite
rich adder
# hazy crypt what is UGS

oh sorry they call it just Cloud now, basically their Unity Gaming Services, but yeah its just Cloud now

rough granite
hazy crypt
#

Oh I see, thanks

#

Im on a bit of an island with this stuff, im not familiar with these terms haha

wintry quarry
rich adder
rough granite
wintry quarry
#

nope

rough granite
hazy crypt
# rich adder no worries with time you will

Yeah its a slow process but my day job really slows down in summer so i get more time to focus on hobbies. The more time I spend in this server the less I feel like an alien 👽

rich adder
#

I'm 5 years in just about and still feel like I never know enough

hazy crypt
#

Ah thats a vibe, I teach sports and whenevr people hit that 5 to 10 years amrk they start realising that they dont know anything about their sport at all haha

rich adder
#

you start going from Dunning-Kruger effect to Imposter syndrome lol

elder hearth
#

Sorry forgot to turn off the ping, my bad

frigid sequoia
#

There is no way of removing parameters in a subclass that exist on it's parent class right?

wintry quarry
#

do you mean fields?

frigid sequoia
#

I basically want to do a variant of an inventory item that does nothing at all, a dummy

wintry quarry
#

All subclasses have all the members of the parent class

frigid sequoia
#

Yeah, as I expected, well I have no clue on how should I refactor this then

wintry quarry
frigid sequoia
#

This is an inventory that is filled with items of the type "gear", the last one is meant to be a "dummy gear" that isn't meant to do anything at all, it's just to fill the empty cells. My idea was to keep the dummy as gear type to simplify the lists that hold and display the inventory. Gear does a bunch of things that I do not want the dummy to do at all, so I am wondering what would be the best way to make a dummy that does nothing but it's still a gear type

wintry quarry
#

using an array you can simply leave null slots in it

#

null slots would be empty slots

#

then your presentation layer (the ui that displays this) can handle things as needed

frigid sequoia
#

It's not like you have a fixed amount of slots that you can fill, it's meant to expand indefinelty. The dummies would expand to cover 1: the last unfilled row; and 2: the full viewport they are in if the items you are currently holding are not enough to do so. It's just so you can visibilly see there is supposed to be something there and it's not just a full empty square lol

wintry quarry
#

sounds like something your UI code needs to worry about and your actual data model doesn't

#

I think you probably haven't established a clear boundary between your data model and your presentation layer

#

which is going to bite you

sour fulcrum
#

Could potentially use an interface to dumb this down even more right? Like a ISlottable or something. Then Have Item and your “empty” class implement that

#

Depending on what the Inventory needs to know

frigid sequoia
#

Yeah, I am having kinda of a mess of structure rn. Like I am working on it

#

I am not even sure how to separate the gear on the UI that has visual elements and all and the one that is just a component that is meant to be attached to whoever is using it

#

But right now, I am with the arrangement of this inventory

#

The thing is gear is already currently inheriting from another class that is "tooltipItem", can I still give it another parent class?

#

Should be an interface right?

#

It cannot inherit from two classes

frigid sequoia
wintry quarry
#

I would kinda have to juggle with the fields of the gear items on the array to sort them
Array vs list doesn't complicate the sorting process at all

frigid sequoia
#

I mean making the List/Array of the type Item instead of Gear

wintry quarry
wintry quarry
#

I was just guessing

frigid sequoia
frigid sequoia
wintry quarry
#

or you have an ItemSlot which can reference either a Gear or a Character

#

and your inventory holds ItemSlots

#

It would then be quite easy to have an empty ItemSlot

frigid sequoia
#

And.... ItemSlot would be... what? An abstract parent class?

wintry quarry
#

no

#

just a class

#

with fields

#
ItemSlot {
  // only one of these two would be populated
  Character character;
  Gear gear;
}```
#

Methinks you jump to inheritance too eagerly

frigid sequoia
#

I am inheriting quite a bit, yeah

#

But shouldn't I? Considering both of those are basically always gonna be linked with an ItemSlot, why not making it part of the thing directly?

#

What's the criteria for that?

wintry quarry
#

why would they always be part of an itemslot

#

do your characters and Gear not exist other than when you're looking at the inventory menu?

#

An "ItemSlot" in this case is like a shelf

#

just because you put a candle on the shelf, it doesn't mean a candle is a shelf.

frigid sequoia
#

In this case, is more like "candle that can only exist on a self"

#

Those items are referring the UI versions of them, they cannot exist outside UI, in this case the shelf

#

Like the actual usable gear cannot have like a graphic component that is meant to show in the UI, it just does stuff

rough granite
sour fulcrum
#

all my homies hate enums

brave shadow
#

let's say, I have a prefab like this, and then I change something on it:

#

like, the location of an object

#

Does that cause the location of every instance of that object on all prefabs to also change?

frigid sequoia
#

Remember to overwrite tho

brave shadow
#

If I don't overwrite, does it only change the position of this specific instance of the prefab?

sour fulcrum
frigid sequoia
#

You can also just click the prefab itself and edit it on the void

#

Rather than on scene

sour fulcrum
#

Ideally you wanna prefer to handle those exempt differences via setting them in code than handling them via instance differences though, just because it’s easier to manage and validate

brave shadow
sour fulcrum
#

Yee

brave shadow
sour fulcrum
#

Yeah all good

brave shadow
#

another basic question, what is that icon that looks like the prefab icon but has a {} in the lower right corner?

#

like, its name

frigid sequoia
#

You mean... scripteable objects?

#

I, have, still, not successfully used any over a prefab actually lol

sour fulcrum
#

ScriptableObjects are ways to make “templates” of data that you’d usually reference in a script/monobehaviour. They are usually used to separate data and logic.

Eg lets think about Minecraft

You might have a Block MonoBehaviour class that exists for every block in the game. Rather than having say “Cobblestone.png” in a prefab for every Block type, you could have Blocks keep a reference to a ScriptableObject class named say “BlockData”. Then BlockData can contain the texture, name etc. per block type

frigid sequoia
#

Basically it's a script that is saved as like a prefab without needing to attach it to anything, pretty much

#

How is this clearing the list but not destroying any of the items without sending any error message?

rich adder
frigid sequoia
#

It's for quick testing

#

It's meant to the normal destroy

#

CurrentDummies is just a list of items that do nothing

#

Oh, no, of course, I am destroying the component, not the gameobject, fuck I am dummie myself

woeful scaffold
#

I'm having an issue with my interacting system, would be grateful if someone could point me to the direction of fixing it 🙏

Interact function, the ray seems to be hitting and calling out the door, but it doesn't see it as a IInteractable somehow.

{
    if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out RaycastHit hit, interactRange))
    {
        Debug.Log("Ray hit: " + hit.collider.gameObject.name);

        if (hit.collider.gameObject.TryGetComponent<IInteractable>(out var interactable))
        {
            Debug.Log("Interactable found.");

            UIManager.Instance.interactText.text = interactable.interactionPrompt;
            UIManager.Instance.interactText.gameObject.SetActive(true);

            if (Input.GetKeyDown(KeyCode.E))
            {
                Debug.Log("Pressed E on: " + hit.collider.name);
                interactable.OnInteract();
            }

            return;
        }
    }```

for reference, this is my IInteractable.cs:
```public interface IInteractable
{
    string interactionPrompt { get; }
    void OnInteract();
}```

and this is my Door.cs:

```public class Door : MonoBehaviour, IInteractable
{
    [Tooltip("Animator controlling door animations")]
    public Animator animator;

    // Default state of the door
    private bool isOpen = false;

    string prompt = "Press E to open door";
    string IInteractable.interactionPrompt => prompt; 

    private void Start()
    {
        if (animator == null)
        {
            Debug.LogWarning($"Door '{gameObject.name}': Animator is not assigned.");
        }
    }

    public void OnInteract()
    {
            isOpen = !isOpen;
            animator.SetBool("isOpen", isOpen);
            Debug.Log($"Door '{gameObject.name}' {(isOpen ? "opened" : "closed")}!");
    }
}```
#

Everything seems to be linked and correct yet when the ray hits it doesnt see the door as a IInteractable

sour fulcrum
#

is the collider its hitting the actual door

#

any chance its some child?

woeful scaffold
#

the door script is linked to the parent door, which is Door - DoorHinge - Door (The model)

sour fulcrum
#

whats it hitting

woeful scaffold
#

wait I'll try to mask the doorhinge and door model for a second

sour fulcrum
#

also if you define the type on the out variable you don't need to define it in the generic which just looks better, eg.

thing.TryGetComponent(out MyType myThing)

#

not something that matters but just nice to know

woeful scaffold
#

oooh nice

#

I put the DoorHinge and the Door on ignore raycast layer

#

now all thats left for the ray is the parent door

#

seems like the ray isnt hitting now

#

it does hit the 2 cubes next to it

#

this is the parent Door

#

I think im stupid

sour fulcrum
#

There’s nothing to hit 😄

woeful scaffold
#

the parent is an empty gameobject, therefore no collider, therefore ray not hitting

#

so i should put the script on the door model itself huh..

#

i just realized it hahaah im testing it right now lets see

sour fulcrum
#

Or have the collision as just a box collider on the root

#

If the door is just a simple rectangle

woeful scaffold
#

oh

#

yeah ill do that then

sour fulcrum
#

Depends on how the animation runs actually

#

Might not be viable my b

woeful scaffold
#

it just rotates 90 degrees

#

the hinge rotates itself and the model with it

#

is there a way to stretch the collider on the model?

#

or do i need to manually do it

woeful scaffold
#

can anyone help me understand why when i start up the game, my door opens automatically? Cry

#

isOpen is unchecked = false

rich adder
woeful scaffold
#

figured it out a minute ago 🙏

woeful scaffold
#

@rich adder wanna help me with a different issue

#

I have this isOpen bool, and i want some doors to be automatically open at the start, so i created a new transition from Entry -> DoorOpen (on isOpen = true)

#

but when i start up the game with a specific door that has isOpen = true, it doesnt open at the beginning

rich adder
woeful scaffold
#

in the inspector, on a specific door

#

the isOpen default is false

#
{
    isOpen = !isOpen;
    animator.SetBool("isOpen", isOpen);
    prompt = ($"Press E to {(isOpen ? "close door" : "open door")}");
    Debug.Log($"Door '{gameObject.name}' {(isOpen ? "opened" : "closed")}!");
}```
#

so lets say it has isOpen = true at the beginning, i think its problematic because interact make it false, and then puts the animator on false too

#

because its code problematic, i just made an animator transition

rich adder
woeful scaffold
#

oh,

#

outside of the interact?

#

oh wati yeah

#

bruh thank you

red imp
#

hello there. do dynamic buffer support paralel like native list or nativequeue, like this"public NativeQueue<T>.ParallelWriter"?

grand badger
#

yikes.

red imp
static breach
#

i have so many scripts. can i somehow in editor look for like "PlayerCamera" and it finds every script that contains "PlayerCamera" ?

sour fulcrum
static breach
#

VSCode

sour fulcrum
#

not sure how it works in code but in studio i can right click a type and go to find all references

static breach
#

i should switch from vscode to visual studio

#

even when i love vscode

teal viper
#

You can find references in vs code as well

static breach
#

i love the layout of vscode

#

hitting ctrl + F only shows in currenct document

teal viper
#

Vs code provides most of the same features as VS nowadays.

static breach
#

found it

teal viper
static breach
#

its ctrl + shift + f instead of ctrl + f

sour fulcrum
teal viper
#

That's a regular search

static breach
#

ctrl + shift + f is good for what i wnated

#

its giving what i wanted

proud mulch
#

That search is terrible lol

static breach
#

idk. its good for what i need

#

xD

proud mulch
#

Oh for sure, I'm just ragging on VS Code 🙂

static breach
#

i used to do webdev and i like vscode for that

proud mulch
#

I'm a web dev and in large React apps, VS Code is terrible for go to definition - constant loading progress bars. Webstorm's much better (for me)

static breach
#

i just started learning webdev, was good for my use xD but im not up to date at all

#

like 10 years ago i used that...

#

microsoft expression web or so

#

xD

median hatch
grand badger
#

but you can do ctrl+shift+f yeah if that's indeed what you want 😄

static breach
#

i rly need to cleanup all my scripts

grand badger
#

I usually just go to the var with ctrl+T, then find all references

static breach
#

also idk why but whenever i put a script on a gamemanager i always create a new gameobject instead of just having 1. i think thats a big fail aswell KEKW

proud mulch
grand badger
#

I keep my project's hierarchy as minimal as possible, but back it up with behind-the-scenes logic (like scene initialization, editor scripts, etc)

static breach
#

my hierachy is horrible lol

grand badger
#

I agree lol

#

I hope your UI is at least not all over the place xD

static breach
proud mulch
grand badger
#

hmm yeah I meant in scene/hiearchy but nice 😛

static breach
grand badger
faint osprey
#

hi ive got a slider for my ui which on value changed is hooked up to a function with a float parameter altho the value of the slider isnt going into the parameter

grand badger
#

can u send a screenshot of the component?

faint osprey
grand badger
#

yup, so, you're already passing a fixed value there, that's not correctly setup

faint osprey
#

ah

grand badger
#

what's the definition of AudioMixerHandler.UpdateMa....?

faint osprey
#
{
    SetVolume("MasterVol", value);
} ```
grand badger
#

try pressing the [-] button and reassigning it, idk 😛

faint osprey
#

wdym

grand badger
#

the minus button here

faint osprey
#

still the same

#

oh

#

wait

#

at the top

#

dynamicfloat

grand badger
#

yup!

faint osprey
#

cool nice

burnt vapor
candid helm
#

So, I'm doing this beginner unity tutorial for a 2d platformer. I have run into several issues at the timestamp in the video:

  1. in her code, rb.velocity & rb.velocity.y don't exist anymore in my current version of unity so I replaced those with rb.linearVelocityY. Is that correct? Why or why not?
  2. I'm getting a blue information hint in the error list, that my start is empty. Is that supposed to be that way at that point in the tutorial?
  3. I'm getting a error that says 'moveSpeed' doesn't exist in the current context, but in the video her code seems to work fine. What's up with that?

Video Link with timestamp & screenshot of my code:

https://youtu.be/xb3d7HarKcI?si=vlYXbvZYYbFgAdFT&t=182

FREE code for this video on my Patreon
In this episode we'll be getting our player moving using Unity's 'new' Input System!
We'll be working with the Input System throughout this platformer series, so check out our future episodes for more implementations.

❗️❗️❗️📢 BUY THE COMPLETE GAME TEMPLATE NOW!!! 👾❗️❗️❗️
...

▶ Play video
slender nymph
#
  1. yes, Rigidbody2D.velocity was renamed to Rigidbody2D.linearVelocity, as was the X and Y counterparts to that property (which were also added fairly recently)
  2. if Start is empty at that point of the tutorial then yes, your Start should be empty as well and the IDE is simply telling you that it is empty
  3. You are getting an error because you spelled it wrong
grand badger
#

what is rb.linearVelocityY? 😛 You probably mean rb.linearVelocity.y

grand badger
#

huh, cool

#

but yeah about the moveSpeed (vs movespeed), as a programmer you need to learn to type less and use auto-complete more 😄

drowsy flare
#

When I build my Unity (web) application, I would like to execute a post-build bash script. Where should I be looking to find info on this?

pulsar pelican
slender nymph
#

If you're on unity 6 or later then there's the Awaitable class that has the EndOfFrameAsync method you can await. otherwise you'd need to use unitask or a coroutine instead of a Task

sage mirage
static breach
sage mirage
sour fulcrum
#

Just two cents, I'd personally have the stuff like post-processing, vfx, managers, UI, etc. above environment, lighting etc. since there a lot smaller and environment and such tend to expand into pretty big groups of objects

#

keeping the messy toybox at the bottom so its easier to find the important stuff 😄

sage mirage
#

Check how much space I have

sour fulcrum
#

I've had scenes that would have a fully expanded environment tab fill that space 9-10x over 😄

sage mirage
#

I love organization btw

#

I cant work on a messy environment

#

XD

#

Its for productivity purposes basically, it improves the workflow and production

pulsar pelican
sage mirage
#

I recommend Visual Studio for free it's the best option.

#

People might want to pay in order to get more features to expand, but really if you are a solo developer and you are a beginner dont have a team yet what's the reason to pay

restive kettle
#

guys its okie if i updated c#?

#

im using unity 6

naive pawn
restive kettle
naive pawn
#

structs are available

#

default struct constructors aren't

grand snow
#

why that wasnt a thing earlier on annoys me 😠

earnest wind
#

How can i know what the object im over in ui if i know Input.mouse position?

naive pawn
#

raycast from the screen?

earnest wind
stuck field
#

If they have colliders

earnest wind
#

wait

#

let me show you the code

naive pawn
#

that's what the block raycast thing is for

#

though if you're using Input you could also use the OnMousex events i think

earnest wind
#
RectTransform rt = TextureImages[LayerOn].rectTransform;
        if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, screenPosition, null, out Vector2 localPoint))
            return;

        Vector2 pivotAdjusted = new(localPoint.x + rt.rect.width * 0.5f, localPoint.y + rt.rect.height * 0.5f);
        float scaleX = rt.rect.width / TextureLayers[LayerOn].width;
        float scaleY = rt.rect.height / TextureLayers[LayerOn].height;

        int texX = Mathf.FloorToInt(pivotAdjusted.x / scaleX);
        int texY = Mathf.FloorToInt(pivotAdjusted.y / scaleY);

        if(texX < 0 || texY < 0 || texX > TextureLayers[LayerOn].width || texY > TextureLayers[LayerOn].height)
        {
            Debug.Log("Out of bounds");
            return;
        }

        Debug.Log($"{texX} : {texY}");
naive pawn
#

i saw that, which is why i brought that up

naive pawn
earnest wind
#

ive tried GraphicsRaycaster but its just weird idk why

spiral oak
#

Is it so much of a big deal to use obsolete methods or properties?

rare oracle
#

Hi, if anyone is using NGO Lobbies, did it happens to break for you too? Just got this error rn but it worked fine since a few weeks:

naive pawn
spiral oak
naive pawn
#

some work in the editor, but not in builds, afaik

rare oracle
#

Seems like unity just pushed something they souldn't have

rare oracle
eternal needle
spice shadow
#

the Unity Multiplayer Services package

sharp solar
#

in compute shaders is there some cheaper texture u can do that has just 1 channel instead of 4 channels

#

oh ig u just set it to uint or something there right

chrome fern
#

How do I get a forced 60 FPS without turning VSync off?

wintry quarry
#

there's no avoiding/changing that with vSync on

#

(you can definitely still get LESS than your monitor refresh rate, but not more)

rare oracle
chrome fern
#

Yeah I have that line of code and VSync off but then it causes screen tearing

rare oracle
#

Iirc it means that you are rendering frames faster than your monitor can

#

Do you still have tearing with Vsync on?

chrome fern
#

I don't believe so, but VSync on caused all the WaitForSecond code to not work on someone else's PC.

wintry quarry
chrome fern
#

That's every enemy in the game. UnityChanThink

#

And the game is borderline done.

rare oracle
#

yeah probably a time.time instead of deltaTime somewhere

wintry quarry
#

Sounds like you have a major bug to fix before it's done

rare oracle
#

or things in update that should be in fixedUpdate

wintry quarry
#

It's not really worth speculating on what the exact issue is without getting an explanation of what's going wrong and seeing the code involved

chrome fern
#

I thought modern platformer games had forced 60 FPS so that things would work.

wintry quarry
#

definitely not

rare oracle
#

Sure but its the most common errors

naive pawn
#

you can't "force" a specific framerate in practice, the real world is unfortunately messy

wintry quarry
#

but they don't force a framerate

sharp solar
#

is there such thing as something like a render texture but super cheap with no bloat like mip maps and depth buffers and rgb channels, just a grid of integers or floats

#

single channel

#

would it be best to just use an array?

#

somehow

naive pawn
sharp solar
#

not to worry chat gpt helped me out

restive kettle
#

guys what vsc extensions should i downlod?

slender nymph
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

supple oar
#

Hello guys!
Trying to make a script to solve a math operation with 4 variable integers and 4 variable kinds of operation (+, -, ÷, ×), trying to find a way to make it without having to make a hundred IFs and Else IFs

sharp solar
#

is the fastest way to get gpu to sample average value in a texture just to get it to generate mip maps and read the 1x1 texture

rich ice
sharp solar
#

forums are the best way to wait 5 hours to get an answer to a yes or no question lol

rich ice
#

it has a general thread too

sharp solar
#

ahh ok i didnt see

rich ice
supple oar
#

But not sure on how to do this

rare oracle
#

You could use delegate for the operations

supple oar
naive pawn
#

if you allow arbitrary parens you can just ignore pemdas for the calculation

fervent wind
#

I want to learn C# only limited to unity ( i have programming expierence and how coding works inst new to me)
Any PDF i can refer to which explains it step by step?
I had downloaded one but its quite old sadly
I am not sure how many changes have been name

#

Alright

#

thanks!

slender nymph
#

I'm curious what you found that was so old that it wasn't worth using. was it a 20 year old book or something?

rare oracle
fervent wind
rare oracle
#

iirc it'll even follow PEDMAS

fervent wind
#

I am new to this and am not sure how old these things are

#

i just dont wanna take the risk 💔

#

Bettter take advice rather than messing up

slender nymph
fervent wind
#

Alright!

#

thanks

red igloo
#

any ideas on how to fix this?

naive pawn
#

well, make it stop spinning?

hexed terrace
#

increase angular drag

naive pawn
#

or add angular drag/friction

hallow sun
#

Well, the code you shared doesnt have anything to do with it spinning, that spin clearly happens before you even start moving

naive pawn
#

we don't do DMs here, it defeats the purpose of having a community server

#

just !ask about your question

eternal falconBOT
wintry quarry
#

your question is incredibly vague. You should share how your game is currently set up, your current code, and a good explanation of what kind of movement you're trying to achieve

naive pawn
#

and post the relevant !code you're having issues with

eternal falconBOT
plain brook
#

well im trying to make my first game but the code wont work and im not sure what to do got this from a guy on YT

naive pawn
#

first off, configure your !ide

eternal falconBOT
naive pawn
#

secondly - be more specific. you wouldn't be here if it was working, we need to know how it isn't working
are you getting errors, is it not doing anything, is it doing something you don't want it to do, etc

plain brook
#

its not doing anything

wintry quarry
#

Check your console window for errors

#

most likely if this is a new project, your project has defaulted to the new input system

plain brook
#

ive done that

wintry quarry
#

and this code is trying to use the old

wintry quarry
#

What was the result?

#

What do you see there?

#

We are not mind readers

plain brook
#

well nothing happened

wintry quarry
#

Did you ever attach this script to your player object?

frail hawk
#

maybe the script is not attached to your gameObject

plain brook
#

probs

rich adder
#

what does the error say?

#

probably something about the Input class

#

🛑 red means error

#

if you have errors , well things dont work as they should..usually..

red igloo
#

I have this issue where when I jump I reach the normal height and then when I do it again I go higher for some reason

rich adder
#

you likely need to reset the y velocity to 0 before jump

red igloo
rich adder
red igloo
dusty tendon
#

is the minimum vertex distance property on linerenderers deprecated? i can’t seem to find it in the inspector

rich adder
red igloo
#

its like a weird spring jump

rich adder
#

btw unrelated somewhat...most of the move code should be in fixed update..
always move rigidbodies in fixedupdate (unless its Impulse then its ok in update)

wooden hill
#

btw something nagging me but why do you use input getaxis when you also use new input system notlikethis

red igloo
rich adder
lethal meadow
#

you should change any deltaTime to fixedDeltaTime as well pretty sure

#

correct me if I'm wrong

rich adder
#

deltaTime turns into fixedDeltaTime when placed in FixedUpdate, although they should not be used with AddForce / .Velocity

#

rigidbodies are already moving on a fixeddelta (unless you use MovePosition but thats for kinematics)

red igloo
#

so how can I fix this issue? also the lineardamping doesnt change as well

rich adder
#

cant fix issue if you dont narrow down the origin of the issue

red igloo
rich adder
tulip radish
#

Hello

rich ice
#

howdy.
Not a 'Social Chatroom', so, "hi" and "hello" generally go unanswered.
If you have a Unity question, feel free to !ask

eternal falconBOT
red igloo
#

well it looks fine now

#

doesn't do that springy jump

pallid olive
#

im trying to code this plane to fly and the tutorial said that once i code this part the plane should rotate and pitch but when i pressed play it wouldnt do that

polar acorn
eternal falconBOT
pallid olive
red igloo
#

I added
else { rb.linearDamping = 0f; }
and it fixed the issue I was having

mystic lark
#

i get this error when im not hitting any cllider but the if is still going trough, i tried doing hit.collider != null but still and also even when the colliders tag is diffrent i still get the message any ideas

red igloo
#

!code

eternal falconBOT
mystic lark
#

its kinda long and prob bad but dont juge okay UnityChanFinished

polar acorn
mystic lark
slender nymph
mystic lark
#

and how do i send big lines of code?

slender nymph
frail hawk
#

layermasks in raycasts are very usefull

mystic lark
slender nymph
#

which is line 143

frail hawk
#

line 96

#

i guess

mystic lark
#

89

polar acorn
slender nymph
polar acorn
#

what hit are you trying to get data from

#

you didn't even do a raycast

mystic lark
#

it was at first but then the attacks couldnt go trough if im (exsample looking at the sky)

frail hawk
#

you could actually move the code into line 56 if statements

mystic lark
frail hawk
#

start small, this is not easy

mystic lark
#

evry time i try to get help i relaise how stupid i am

mystic lark
frail hawk
#

you are not stupid, you just need more practise

mystic lark
#

i have been trying to learn for over past 1 and a half

frail hawk
#

so it is easy you can not just use hit because it doesnt exist in that context. but you have it a few lines higher so you could put the code you want into that if statement

naive pawn
frail hawk
#
if (Physics.Raycast(cameraTransform.transform.position, cameraTransform.forward, out hit, 10f, resourceLayer))
``` hit only exists inside this if statement
naive pawn
#

are you following a tutorial?

mystic lark
mystic lark
naive pawn
#

you probably should

slender nymph
mystic lark
naive pawn
#

get some actual structured learning

frail hawk
#

ph right he declared the Raycast outside sorry missed that

naive pawn
#

there are resources pinned in this channel and in !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

slender nymph
naive pawn
#

"tutorial hell" is not caused by using tutorials, it's caused by using tutorials without trying to learn and understand what they give

mystic lark
#

i did learn for a year C# without tuching unity

naive pawn
#

and have you used it recently?

mystic lark
#

then i made some small projects first without tuorials

#

now im donig something little bigger

mystic lark
naive pawn
#

you mean for unity or c#?

mystic lark
#

C# for unity

naive pawn
#

gotcha..

frail hawk
#

when i said inside this if statement of course i ment inside the scope / body

naive pawn
#

footnote: that is contextual to how the function works and is used

#

if you negate the result, then the raycasthit is only valid in the else, or outside the if if there's an early exit, eg with a guard clause

slender nymph
#
{ // outer scope, out parameter is accessible here
  if(Raycast(out var hit))
  { // inner scope, out parameter is guaranteed to be valid here }
}
zenith cypress
#

Yep because the out var sugar syntax basically just places a variable right before the if statement that it writes into smart

short hazel
#

Allows you to do neat stuff like

if (!Raycast(thing, out var hit))
  return;

// 'hit' accessible here
spiral oak
#

reduces overhead for me

#

i even always write the return in the same line as the if clause because that way I interpret them as a whole stament (only continue if x)

elder hearth
#

Im gonna assume that this is the correct channel for this,
I was wondering whats the best way to make a pickup system i dont want code or anything just like how i could maek it

rich adder
#

most typically its done with some sort of physics query , casts , overlap etc.

elder hearth
#

Okay thanks ill see what fits best

solemn bobcat
# elder hearth Im gonna assume that this is the correct channel for this, I was wondering whats...

Things like OnTriggerEnter let you detect if your object has entered another object's area, which can be used to detect if another objects in pickable range. Since physic is overall slow, you can alternatively create some manager that will iterate through pickable objects and check if their close enough to the player (calculations may include radius of both objects). For best efficiency you could base it on some sort of quad tree, but I wouldn't bother unless there are hundreds of pickable objects and multiple pickers.

Alternatively, you may implement pick up on mouse click. In such case you want to use OnMouseDown method, or combine OnMouseOver with some input detection. Alternatively, you can cast a ray from the camera, check the intersection with a plane, and check how far it is from pickable object.

elder hearth
#

Well the game will(one day) have multiplayer(up to 4 or 5) so id need a system that wouldnt interfere with other players and can be used in a client host enviorment, and there will be a decent amount of object in a scene so by the looks of it a quad tree would be the best option. Wdyt

slow idol
#

how do i check if a gameobject is in the scene, even if it's disabled

rich adder
slow idol
#

wouldn't that still return true if it existed in assets?

rich adder
#

GameObject find Methods exists and they search the heirarchy, but generally not recommended to be used often cause they're slow

slow idol
polar acorn
#

If you drag in an asset, it will check that asset. If you drag in a scene object, it will check the scene object

slow idol
#

right. how do i differentiate between an asset and a scene object

polar acorn
#

How are you referencing it?

slow idol
slow idol
polar acorn
# slow idol

Which thing are you intending to check for the existence of

slow idol
#

toSpawn

polar acorn
rich adder
#

I believe there is also gameObject.scene.isValid() you can do

slow idol
rich adder
#

just put it in a List when you spawn it then check the list?

polar acorn
slow idol
polar acorn
#

Things that need to be spawned, and things that need to be activated

slow idol
#

...i refuse because i am stupid

lean sandal
#

Hello im following a tutorial right now and I am trying to do something very simple.. I have been trying for HOURS to do this fucking shit and its starting to stress me out a lot can someone please help me.... Im attempting to use OnCollisionEnter2D inside a script named Player, the player script is attached to a rabbit that has a rigidbody and a box collider... the rabbit is supposed to run into carrots and the carrots are set to destroy and increase score. I even put in print("object collided") and nothing happens

#

The carrots only have a box collider on them

#

All of it is 2D and i havnt found anything wrong with the script code at all...

#

the carrot is tagged Carrot and everything is spelled correctly i checked 100 times

polar acorn
#

Show the inspectors of both objects

lean sandal
eager elm
lean sandal
#

the script code?

eager elm
#

ye

lean sandal
eager elm
#

here is your problem

lean sandal
#

a misspelling??

eager elm
#

it's a Capital 'O', OnColl...

lean sandal
#

OMG XD

eternal needle
eternal falconBOT
eager elm
#

You should put the print() method at the very top of your method next time

lean sandal
#

I corrected the O and its still not working

eager elm
#

configure your ide and then put the print outside the if statement so you can pinpoint where your problem is.

#

it's also Enter2D not Enter2d

lean sandal
#

@polar acorn , @eternal needle , @eager elm thank you so much for helping me

#

So it was a mispelling the whole time

#

Yeah I dont know how to configure and fix the studio im using Microsoft Visual Studio

eternal needle
elder hearth
sharp solar
#

how can this output a completely black texture

#

if i do result[id.xy] = 1.0; it passes the full white test

eternal needle
lean sandal
timid quartz
#

for some reason I'm not able to set these game objects to be active or inactive in code.

here's what I've tried:

  • making sure that the correct, prefab specific game objects are what's linked in the inspector (they are the correct objects)
  • printing a statement that tells me when an object should be disabled (they disable correctly based on my test parameters)
  • manually hitting the checkbox at runtime (it disables and enables just fine)

is there something really obvious I am missing here? this is mystifying to me

#

from reading online the only "gotcha" I can find is that a disabled object stops its update loop but this is just about getting the objects to correctly disappear and reappear

#

wondering if this has anything to do with the fact that the children are model variant prefabs

timid quartz
#

argh, it was something silly - was running the code on the prefab to instantiate and not the instantiated prefab 😛

fickle stump
#

I'm not sure if thsi is the correct channel, but I'm trying to have multiple grids in my scene. Could someone help me out? 😄 i can only see one grid

#

Or correction: is it even possbile to have multiple grids in my scene?

#

or does that not work?

ivory bobcat
fickle stump
#

Yeah it kinda is code related :>

#

but I'll move onto that chat then! Thank you

vocal urchin
#

Why use structs vs classes? I have some classes I use to save data that I think I could easily change into structs but idk if it's worth changing them all if it causes unforeseen issues

sour fulcrum
#

classes are "alive" where-as structs are not. Comes with a bunch of implications and potential pros and cons that include structs never being null, optimization considerations and many other things

#

Don't feel like you have to convert stuff just for the sake of thinking it's "better". Usually it's fine to have something as a class

#

Usually if I just have a tiny group of data with no functions or etc. I'll go with a struct

#

RaycastHit is a good example of that (doesn't really do anything it just has a contextually relevant assortment of information)

vocal urchin
#

I see

#

Might be able to use them going forward at least

rich adder
ivory bobcat
rich adder
#

ref vs value type is especially important when doing stuff over the wire , say netcode etc.

true knoll
#

Hey! I don't know if this is the right channel, but I'm really struggling with this. (In isometric pixel art) I have a png of the layer in which my water is going to be on, and I want to apply a noise texture on top of it. Only thing is, I can't figure out for the life of me how to go about this. The water shape is not a square, and the only way I could get the noise texture to show up was on a UI image, which I couldn't figure out how to change the shape of..? So how should I do this? Thanks!

brave robin
vocal urchin
# rich adder https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-bet...

thanks all. if I'm reading this right, a struct might be a good fit for a lot of it since most of the data is simply used once for instantiation once the game loads and shouldn't need allocated to the heap or altered in anyway, just used for instantiation and discarded. However, the line "It logically represents a single value, similar to primitive types (int, double, etc.)." makes me think I should not use a struct since my class stores more than one value. Would the below class work well as a struct for example?

{
    public int prefabID;
    public Vector3 position;
    public int currentHP;

    public EnemySaveData(int prefabID, Vector3 position, int currentHP)
    {
        this.prefabID = prefabID;
        this.position = position;
        this.currentHP = currentHP;
        
    }
}```
sour fulcrum
#

the struct represents a single, primitive-like value, that doesn't mean the struct can't contain references to reference-esque values (though in this case your not doing that anyway)

#

savedata is a very common usecase for structs yes

rich adder
#

Vector3 as struct makes sense
Mathf. not so much , seems more fit for a class but who knows why they chose that

vocal urchin
#

thanks everyone!

iron wing
#

really general question, why would i initialize a variable with [SerializeField] private instead of just declaring it as public?
wouldn't the only difference be that i can't edit it from another script? if that's the case, why wouldn't i want the freedom to do so if i needed to like by default?

rich adder
#

or if working with teams, other ppl not assigning things that shouldnt be assigned in that way

if you have a public variable and you modify it , do you really know that value was changed? Instead it would be better if its just private and modified with a method, this way there you can put things like events or any sort of thing that can say "hey I changed a value here for this"

eternal needle
# vocal urchin thanks all. if I'm reading this right, a struct might be a good fit for a lot o...

for enemy save data in particular, id probably keep it as a class just because it might grow if you ever want to save more than just this. It is already more than the recommended 16 bytes.
Another thing to think about in context to a save system, this class can be null. a struct cannot (excluding nullable). If you have a save system trying to load a struct but there is no data, you have to declare another way to say that no data was found. In this case you'd have a struct that contains the default ints and vector3. this isn't a problem really but something to think about since you'd likely want to separate how structs and classes are returned

iron wing
sour fulcrum
#

If something is public the assumption is that if a stranger touches it, the code is designed in mind to account for that

#

if your GameManager has a public reference to your Player and some random script sets that to null, does that break your game?

rich adder
iron wing
#

okay okay that makes sense thanks

wraith pumice
#

Hello I'm very new to unity and this server (so I oplogise if it's not the right chanle) but can someone help me? I have no idea why this is happening

#

I started unity 3 days ago

wraith pumice
#

I'm sorry

#

I don't know where else to ask

rich adder
#

what are we even looking at ?

wraith pumice
#

The gizmo handles move with the mouse

#

Is it like a setting that I accidentally set on

rich adder
#

possibily.. looks like its stuck in some sort of surface snapping or something

#

you tried just restarting unity or something?

wraith pumice
#

I can do it again tho

dull grail
#

I'm a bit lost bc can't understand why this code throwing null reference exception when i'm trying to collect 2nd item no matter of his settings. I've tried to delete picked item data from slot and successfully collected 2nd item but then i will get same error on 3rd item. I just don't understand what's been lost and why

https://hastebin.com/share/oligerekiq.csharp

drowsy flare
#

Is there a setting to always have the camera visible in the unity editor? When I select the camera I get a green outline of the rendered screen, but when I select another object it disappears.

I think it's been visible always earlier, so I probably accidentally some setting 😐

foggy spade
#

whenever i try to learn something new in unity i usually get the grasp of it, but when it comes to math i cant understand it for the life of me, is there anything i can do to improve like this maybe a side project or something im still a beginner kinda

eternal needle
eternal needle
dull grail
dull grail
#

Well, i'm a moron. It didn't iterated bc i've added only 1 slot to array...

flint remnant
#

How to render SpriteRenderer GameObjects in SceneView via Editor Window?

Hi! I'm working on an Editor Window that previews prefabs in the SceneView. I already have this working for GameObjects with SkinnedMeshRenderer by extracting the mesh and using Graphics.DrawMesh in SceneView.duringSceneGui.

// This works for SkinnedMeshRenderer
void OnSceneGUI(SceneView sceneView)
{
    var mesh = skinnedMeshRenderer.sharedMesh;
    Graphics.DrawMesh(mesh, matrix, skinnedMeshRenderer.sharedMaterial, 0, sceneView.camera);
}

However, I'm stuck on how to achieve the same result for GameObjects with SpriteRenderer. I need to render sprites from prefabs directly into the SceneView through my Editor Window.
Context: Unity 6000.0.52f1

naive pawn
foggy spade
errant quiver
#
        string tilemapSortingLayer = tilemapRenderer.sortingLayerName;
        int tilemapSortingOrder = tilemapRenderer.sortingOrder;

       
        tower.GetComponent<SpriteRenderer>().sortingLayerName = tilemapSortingLayer;
        tower.GetComponent<SpriteRenderer>().sortingOrder = tilemapSortingOrder;

why is this code instead of setting things correcty why is the tilemap sorting order -1200

original tilemap's renderer sorting order is 0

TOWER FINAL SORTING INFO - Layer: 'Background', Order: 0
UnityEngine.Debug:Log (object)

i even got debug log of the value of tower component but somehow it was set back to -1200

grand snow
#

Its either you setting this or something else

#

also doing GetComponent() twice is wasteful

sacred lake
#

How do you serialize a list of references to objects without causing an "invisible" prefab override?
For example in a use-case like this:

public class Foo : MonoBehaviour
{
    //If Foo is attached to an object and this list contains references in the scene that are not part of the prefab, it will cause an override. How to fix cleanly?
    [SerializeField, HideInInspector] private List<GameObject> gameObjects = new();

    private void OnValidate()
    {
        //Expensive search function to update and assign gameobjects based on the search function
    }
}
rugged coyote
#

hello iam new in unity and i have a simple problem that i cant move left and write although my script is true
using UnityEngine;

public class moveLR : MonoBehaviour
{
public float move;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{

}

// Update is called once per frame 
void Update()
{
    move= Input.GetAxis("Horizontal");
    transform.position += new Vector3(move,0f,0f);
}

}

sacred lake
#

If this is not changing the position of your transform in the inspector, have you checked which input system are you using @rugged coyote? If you're using the new input system than Input.GetAxis("Horizontal") will not work

#

Also did you make sure move is not 0?

grand snow
errant quiver
rugged coyote
grand snow
sacred lake
rugged coyote
sacred lake
#

If it is 0, it will not move

rugged coyote
grand snow
rugged coyote
#

what do you think tris?

sacred lake
#

I was wondering what would be a clean way of fixing this since for our team the blue line indicating overrides is something we try to actively avoid when possible in our scene.

grand snow
#

Perhaps a different design that does not require the prefab instance to have a serialized references to scene objects?
e.g use other component that spawns + initializes them with the references needed.

sacred lake
slender nymph
sacred lake
slender nymph
# rugged coyote

have you added logs to make sure that the code is actually running without errors?

grand snow
rugged coyote
slender nymph
#

well unless you actually ask about specific things then i won't know what you don't know

rugged coyote
#

but i thing my code is true

grand snow
fast relic
rugged coyote
#

no

sacred lake
slender nymph
rugged coyote
#

i dont get any error

slender nymph
#

show the console then during play mode

dim minnow
manic sparrow
#

i have an icy surface that i want to use to apply a slippery effect on players/enemies
the player can wear something to become immune to it and can also apply something to the ground to turn it into ice

does it make more sense to have the effect be written in the player's movement checking for the ground or for the ground to apply it to the player/enemy

rugged coyote
#

i have one day struggling with moving right and left i feel like iam veryy stupid

slender nymph
#

show your console during play mode.

rugged coyote
slender nymph
#

show your console during play mode

rugged coyote
slender nymph
#

look at that, errors!

rugged coyote
#

my first time seeing that

naive pawn
#

you're trying to use the input class but unity 6 is set to use inputsystem by default so you need to change that

#

as the error says

slender nymph
# rugged coyote my first time seeing that

then it's your first time looking at your console. unity 6.1 defaults to using the input system exclusively, if you want to use the input manager (with the Input class) then you need to change the active input handling like the error says

naive pawn
naive pawn
slender nymph
#

as far as i know, yeah. unless they changed it in some patch version

naive pawn
#

i haven't been using unity 6 so i mustve dropped the .1 in my mind somewhere along the way

#

breaking changes in a minor version....

frail hawk
naive pawn
#

well i guess it technically doesn't break existing projects lol

fast relic
foggy spade
naive pawn
sacred lake
grand snow
sacred lake
#

I was thinking of using a scriptableobject but realized that I wanted to do this during edit time so I figured having references to objects in a scene would not make sense for an SO

sacred lake
slender nymph
sacred lake
#

That's what I am saying

slender nymph
#

"not make sense" is not the same as "not possible" so that was not clear

sacred lake
#

My bad

grand snow
#

if your objects have some kind of unique id then that could allow for out of scene referencing but otherwise yea needs to be in scene to be done correctly this way

sour fulcrum
#

You can do dodgy shit with scriptableobjects pointing to assumed references like singletons

sacred lake
#

Ye I rather not haha

sacred lake
faint sentinel
#

I was trying to implement a dash mechanic and it works until we try anything related to the Y axes, more specifically if we try to jump and dash at the same time (and hold jump) it seems like the addForce (from the jump) is still applying during the dash, but it can be something related to Input system, where i check the direction using de vertical system input, I really dont know and i know my code is a mess i really need to clear it

slender nymph
#

!code

eternal falconBOT
sacred lake
naive pawn
sour fulcrum
#

can i not reference this class?

wintry quarry
sour fulcrum
#

TMP_Dropdown/DropdownItem

#

yeah its a nested class

#

fucking hell

dim minnow
#

It's an internal class.

wintry quarry
#

Nested isn't an issue

#

It's protected

#

That's the issue

sour fulcrum
#

can they just not tho like 😭

wintry quarry
#

What are you trying to accomplish

sour fulcrum
#

i just wanted to change the colour of the text of a certain option

#

:/

wintry quarry
#

You can do it in a TMP_Dropdown subclass, as one option

#

Another option is attaching a custom script to the template object and having it change the text color based on some criteria

sour fulcrum
#

ohh does it just straight up instansiate that?

dim minnow
#

The OptionData for the TMP_Dropdown supports a color.

sour fulcrum
#

thought it was manually copying over options for some reason

sour fulcrum
wintry quarry
#

Or just use Transform.GetChild etc and manually find it

sour fulcrum
#

will look into just adding a component if its instantiating the lot

faint sentinel
wicked ivy
#

i have to update my unity api level 32 to 36 i have installed 33 34 35 36 versions in android studios and copy pasted them in unity sdk platforms but when i try to build the game it show to update the android gradle verson

sacred lake
brazen aurora
#

im trying to instantiate a bullet which then uses the bullet script to move towards the player, but it says it cant get the reference, not sure what im doing wrong

    {
        timeSinceLastShot += Time.deltaTime;
        Vector2 direction = (player.transform.position - transform.position).normalized;
        transform.up = direction;
        if (timeSinceLastShot >= shotCooldown)
        {
            timeSinceLastShot = 0f;
            Collider2D[] collider = Physics2D.OverlapCircleAll(transform.position, 15f);
            foreach (Collider2D collider2D in collider)
            {
                if (collider2D.CompareTag("Player") && lastPlayerPosition == null)
                {
                    lastPlayerPosition = collider2D.transform.position;
                }
            }

            GameObject bullet = Instantiate(bulletToShoot, transform.position, transform.rotation);
            bulletBehaviour = bullet.GetComponent<BulletBehaviour>();
            bulletBehaviour.MoveToPlayer((Vector2)lastPlayerPosition, damage, speed); 
        }
    }```
keen dew
#

Show the exact error message and which line it points to

brazen aurora
#

bulletBehaviour = bullet.GetComponent<BulletBehaviour>(); points to this line here, the other lines are coming from this function im pretty sure

naive pawn
#

so bullet is null

#

wait what

brazen aurora
#

yh

naive pawn
#

no that's not right

#

it's saying the error is inside MoveToPlayer

#

at BulletBehaviour line 27

#

you're looking at the wrong lines

hexed terrace
brazen aurora
#
    {
        Vector2 shotDirection = (_playerPosition - (Vector2)transform.position).normalized;
        rb.velocity = shotDirection * _speed;
        damageToDeal = _damage;
    }``` 
line 27 is 
```rb.velocity = shotDirection * _speed;``` 
but ive gotten the reference of the rigidbody
naive pawn
#

it's null

#

errors don't lie

#

how are you setting rb?

brazen aurora
#

in start im doing rb = getcomponent<rigidbody2d>();

naive pawn
#

don't retype code, copy it over directly

brazen aurora
#
    {
        rb = GetComponent<Rigidbody2D>();
    }```
naive pawn
#

anyways, does the object in question have a rigidbody2d then

brazen aurora
#

yes

earnest wind
#

how do i make a scroll rect not interactable but its scrollbars interactable??

naive pawn
#

is bulletToShoot deactivated or the BulletBehaviour disabled?

earnest wind
naive pawn
#

(also btw you can type bulletToShoot as BulletBehaviour directly instead of GameObject, so you don't have to do the GetComponent afterwards)

brazen aurora
naive pawn
#

show your bulletToShoot/bullet's inspector

brazen aurora
#

like the bullet spawns but it doesnt move

naive pawn
#

and this is the prefab you've set as the bulletToShoot?

brazen aurora
#

yes

#

ive 100% put it in the enemy's inspector

naive pawn
#

sanity check - make sure you've saved and recompiled

brazen aurora
#

everything is saved

naive pawn
#

try putting a log in BulletBehaviour.Start to check what you get from the GetComponent

brazen aurora
#

for the rigidbody?

naive pawn
#

yeah

brazen aurora
naive pawn
#

...and you aren't getting the error..?

brazen aurora
#

no i still am

naive pawn
#

before this message?

brazen aurora
#

every time a bullet spawns

naive pawn
#

...i thought Start ran before Instantiate completed, wtf

brazen aurora
#

i think the null reference maybe coming from this script because of the shotdirection

#

since that uses the _playerposition

#

which comes from the shoot function

naive pawn
#

that's not how stuff works

#

structs can't be null

brazen aurora
#

could i send the whole code of both scripts

naive pawn
#

yeah, use !code

eternal falconBOT
brazen aurora
rich ice
sage mirage
#

That's your issue!

#

Investigate your code and inspector

#

Are you assigning components with drag and drop method or manually through code?

brazen aurora
#

Through code

sage mirage
#

Show me your code where the error is occuring

#

In here

#

if possible

#

The whole script

brazen aurora
sage mirage
#

oh ok

brazen aurora
#

In line 27 in bullet behaviour

sharp mirage
#

If i wanted to print a message to correspond with certain event in the update log how would I do it without the message being printed hundreds of times every second cuz u can't rly multiply a print by delta time

sage mirage
#

Check the blue texts

sage mirage
#

alright 140 and 112 you have highlighted

#

let me see

wintry quarry
#

So the Rigidbody2D reference is null

plucky copper
#

Those more knowledgeable than I:

Is an Event Bus Singleton bad design?

Take a situation. My room may or may not have traps. Each trap does a unique thing to the player up to and including triggering death, to companion damage, or even monsters to appear.

This room may or may not have some or all traps. Is it cleaner to use an event bus to decouple dependencies? Each interested entity subscribes via the bus, and the traps invoke their mayhem via the bus, or should each interested entity seek out in the scene / level what they are interested in at load?

wintry quarry
#

Use Awake instead of Start for that kind of initialization

brazen aurora
#

Alright I'll try in a sec

wintry quarry
naive pawn
polar acorn
#

Instantiate will call Awake before it returns. Start will happen before the next Update loop.

sour fulcrum
#

(Also assuming the gameobject is enabled)

sharp solar
#

the kernel can access the values up here properly right?

#

its really seeming like the only valid values are the ones in function parameters

sharp solar
#

you cant set it in shader code

#

has to be set here

#

im guessing they default to 0.0 then

earnest wind
sharp solar
#

learning

earnest wind
sharp solar
earnest wind
#

huh

polar acorn