#💻┃code-beginner

1 messages · Page 335 of 1

wintry quarry
#

Isn't that to be expected when you stretch the object?

dreamy junco
#

no but i want pixel by pixel

wintry quarry
wintry quarry
stone saddle
#

i dont think it does anything with the players position or movement

stone saddle
#

it just moves the background, right?

#

public class ParallaxEffect : MonoBehaviour
{
    public Transform cameraTransform;
    public float parallaxFactor = 0.5f; // Adjust this value to control parallax effect strength

    private Vector3 startPosition;
    private float initialZ;

    private void Start()
    {
        startPosition = transform.position;
        initialZ = transform.position.z;
    }

    private void LateUpdate()
    {
        float parallaxOffsetX = (cameraTransform.position.x - startPosition.x) * parallaxFactor;
        float parallaxOffsetY = (cameraTransform.position.y - startPosition.y) * parallaxFactor;

        Vector2 parallaxOffset = new Vector2(parallaxOffsetX, parallaxOffsetY);

        Vector3 newPosition = startPosition + new Vector3(parallaxOffset.x, parallaxOffset.y, 0);
        transform.position = new Vector3(newPosition.x, newPosition.y, initialZ);
    }
}
willow scroll
#

And consider sending big code blocks using sites

stone saddle
#

my bad

stone saddle
willow scroll
#

"The player is still jittering between pixels", you said. Where's the player script?

stone saddle
#

here

willow scroll
#

Since I have to download it to fully see it

stone saddle
#

ah right

molten dock
#

did they remove the thing that shows ppl on mobile

stone saddle
willow scroll
willow scroll
stone saddle
willow scroll
stone saddle
#

for collision? or the camera

#

i dont have a specific player script

willow scroll
stone saddle
#

urrrrr

#

Moves the player?

#

Im not entirely sure what youre asking

#

oh my bad

#

i had the wrong script copied

#

thats the one for the paralax effect

willow scroll
stone saddle
#

no its for controlling the player, sorry

#

i pasted the wrong script

#

this should be the correct one

willow scroll
#

In your case, you're changing the Rigidbody.velocity

bleak yew
#

Anyone know how i can fix the issue where my ui components are clipping through my 3d gameobjects?

stone saddle
willow scroll
polar acorn
#

If you don't want it to be occluded by world-space objects, you should be using an overlay canvas

bleak yew
willow scroll
polar acorn
willow scroll
frosty hound
#

No there is no console channel, and yes that would be against the NDA.

bleak yew
willow scroll
#

I'm sorry, have you received the answer?
This is how the default Inspector is drawn, with the script's name at the start, and I don't really know whether you can somehow make the script's name go before the editor fields.
The code

fervent abyss
#

thanks

rocky lava
#

Can i put stuff from UI where im struggling with buttons here? or would that be in another channel

slender nymph
#

is the issue code related? if yes, then yes. if no, then #📲┃ui-ux

rocky lava
#

nvm i got it already, thank you!

opaque hinge
#

This isnt as much a scripting question as it is a logic question so Im not sure if this is the right place to ask, but say you have a grid made of hexagons with a character in the center hexagon. On every turn the player destroys a hexagon and the character will move one hexagon closer to the nearest outside piece. If no hexes are deleted at the beginning of the game, the character always reached an outside piece assuming the make the most logical move. So is there a way to determine how many pieces need to be destroyed so that the player always could win if they play perfectly. For example I know if you have a 7x7 grid and remove 14 pieces at the start, the player can win by destroying a max of 10 tiles. How can this be scaled to different size grids?

stone saddle
#

sorry, bad timing

opaque hinge
#

haha all good thanks

stone saddle
#

@ PraetorBlue sorry for the ping. I've tried fixing the wall collision with your advice but I cant quite get it to work. Would you mind looking at my stuff again when you have time?

wintry quarry
#

and if those are different things

opaque hinge
wintry quarry
#

what's a "7x7" grid mean in hexagons?

#

and are they trying to reach the 7th ring or the 8th ring?

#

For example I would consider the outside ring here the "4th ring" and the center piece is the "0th ring"

#

Anyway it is not clear to me that if the player removes one hex per turn, they could ever stop the character from reaching a particular ring at all.

opaque hinge
#

7 hexagons wide by 7 hexagons long

#

yeah exactly

wintry quarry
#

Ah - that seems weirdly designed because the corners are further away than the sides

#

the sides are only 3 moves away. The corners are 4+

opaque hinge
#

I suppose

wintry quarry
#

anyway at each piece there are at least two possible moves bringing them closer to the outside, so destroying one hex at a time will never stop them

opaque hinge
#

but I have working logic for this right now that if I destroy 14 tiles at the start of the game, the player can win everytime

#

yes exactly, so I would need to destroy tiles before the game starts

wintry quarry
#

I mean couldn't you just destroy the 6 tiles surounding the start position and win?

opaque hinge
#

no its randomly destroyed

#

like a certain number of tiles are randomly destroyed before the game start

wintry quarry
#

Then what happens during the actual game?

acoustic arch
#

is their any use or way of sorting values in a dictionary?

wintry quarry
opaque hinge
#

the player destroys one tile per turn trying to prevent the enemy from escaping

wintry quarry
#

sorting implies there is an order.

acoustic arch
wintry quarry
acoustic arch
#

gonna use a List<> instead

opaque hinge
#

If any 14 tiles are randomly destroyed before the game starts, the player always has a chance to win if they play correct

#

doesnt matter which ones

#

ive tested that

wintry quarry
#

If these are destroyed

#

it seems the player cannot win

opaque hinge
#

that is not 14 tiles, but they could win that im pretty sure

acoustic arch
opaque hinge
#

yeah I thought it would be an interesting start, ive already implemented the pathfinding logic for the enemy which was fun

wintry quarry
#

Player can't win like this

#

I can't count apparently lol

abstract finch
#

I'm trying to make a third person over the shoulder camera but I'm struggling to get it to take into account the offsets. The line represents the direction its facing. here it should be looking straight ahead.

            transform.rotation = Quaternion.LookRotation(lookDir - transform.position);
            Debug.DrawRay(transform.position, transform.forward * 1000, Color.red);```
Am I doing something wrong here? The character itself is facing (0,**90**,0). The Target Transform is facing (-38,**85**,0)
wintry quarry
#

lookDir - transform.position < in fact this doesn't make any sense

abstract finch
#

i see

wintry quarry
#

subtracting a position from a direction is ??

abstract finch
#

I figure I need the mid point between these two

wintry quarry
#

what is this code meant to do

abstract finch
#

Its something like an over the shoulder camera. So the camera looks straight ahead of where it is but also accoutns for the pitch and offsets.

#

Im struggling with getting it to look at the proper spots atm

wintry quarry
#

btw this:
var lookDir = _targetTransform.forward + (_targetTransform.right * _sideOffset) + (_targetTransform.up * _yOffset);
Can just be:

var lookDir = _targetTransform.TransformDirection(new Vector3(_sideOffset, _yOffset));```
stone saddle
# wintry quarry I can't count apparently lol

Hi, would you mind quickly looking at my code again if you have time? Ive tried to do what you said regarding wall collision detection and teleporting the player to the wall when the player is on the wall but now the player cant move up and down, and gets stuck when holding the direction of the wall. https://pastebin.com/zQwewP1s

abstract finch
#

ahh

wintry quarry
#

er wait actually

opaque hinge
# wintry quarry

you may have gotten me with that one, so there might be a few unwinnable scenarios

wintry quarry
#

that's not right haha

#

it's weird to use addition etc.

abstract finch
#

is it inverse?

#

InverseTransformDirection

opaque hinge
#

im honestly playing it in a different tab trying to win

wintry quarry
#

which should sort of work

abstract finch
wintry quarry
#

the second line should be:

transform.rotation = Quaternion.LookRotation(lookDir);```
#

But the real question is what do you want the "offset" to represent?

#

An angle? A position offset from something?

abstract finch
#

Its producing this

abstract finch
wintry quarry
#

Unwinnable position with 19 tiles removed:

#

You'll have to be a bit smarter about this than just removing random tiles.

opaque hinge
#

that isnt unwinnable

wintry quarry
#

isn't it?

opaque hinge
#

just removed the yellow middle right

wintry quarry
#

ah true

#

good call

opaque hinge
#

but I see your point

#

I feel like unwinnable positions are rare enough that my method is fine for a 7x7

#

I just wouldnt know how it would change when I scale it

wintry quarry
#

if you write an algorithm that detects an unwinnable position you can use that

#

and regenerate if you get one

acoustic arch
#

to be fair half my legit solitaire games are unwinnable

#

but i wouldn't say it's a good thing

stone saddle
opaque hinge
#

ah that would be smart, I would need to look into how to do that

slender nymph
stone saddle
#

working other than always being 1 or 2 pixels away from the wall

slender nymph
#

oh in that case, physics material 2d with no friction

slender nymph
#

yeah i'm not going to try and read that code. if you want to share your !code do it correctly 👇

eternal falconBOT
stone saddle
#

sorry, i just meant to demonstrate that it was working without being teleported to the wall

acoustic arch
#

is it possible for my class to have a constructor that can take 3 arguments but only NEEDS 1 argument to be filled when the object is created?

slender nymph
wintry quarry
acoustic arch
#

thanks

stone saddle
#

sorry, never used pastebin before

slender nymph
#

okay, and now have you bothered trying my suggestion. or are you just going to dump the code, expect me to read all of it and tell you some other solution to your issue?

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


public class Ob : MonoBehaviour
{
    Vector3 originalPos;

    void Start()
    {
        originalPos = transform.position;
    }

    void Update()
    {
          if (transform.position.x < 52611)
            {
                transform.Translate(Vector3.right * 10 * Time.deltaTime); 
            }
            else
            {
                transform.position = originalPos; 
            }
    }
}
#

I have this object that is moving and when it passes a certain x point I want it to go back to the starting state and then start moving again.

stone saddle
#

everything was working fine as shown in the video

slender nymph
#

physics material 2d with no friction

lost cypress
#

This code is not really working and I'd really appreciate it if someone could help me with it.

stone saddle
polar acorn
#

Is it not moving at all or is it not resetting

slender nymph
summer stump
lost cypress
lost cypress
stone saddle
slender nymph
slender nymph
molten dock
#

is singleton like i make a script named singleton, do the singleton loop thing and then whatever variables i make in that script are now acessable thru all scripts

polar acorn
lost cypress
polar acorn
slender nymph
wintry quarry
#

52611????

#

that should be basically the entire known universe in Unity terms

slender nymph
lost cypress
summer stump
#

Maya and blender have different ones haha

summer stump
#

I always laugh about unreal sitting there out in the cold

lost cypress
#

I will see what I can do about scalig it down. Anyways so the size is the problem tho right?

#

There is no fixing the problem if not scaling down

slender nymph
#

i mean, that's likely part of the problem

summer stump
polar acorn
acoustic arch
#

how fast is this train to go from the origin to over 50k

wintry quarry
summer stump
# lost cypress

Why are you showing this? And there are five listeners in the scene!?

polar acorn
lost cypress
summer stump
lost cypress
#

I did this and nothing is showing.

dusty silo
#

Vertecies have CircleColliders and Edges have EdgeColliders

lost cypress
slender nymph
wintry quarry
#

(but you should sitll fix them)

lost cypress
polar acorn
wintry quarry
lost cypress
summer stump
wintry quarry
#

pretty sure they're trying to show that their log didn't print

lost cypress
#

Just thought I would show you everything

wintry quarry
#

which we already knew

summer stump
#

Then wherever you put the log didn't run? Not sure how that is useful without seeing the code where you added it

lost cypress
#

sure but "show don't tell" kinda thing

#
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{
    Vector3 originalPos;


    void Start()
    {
        originalPos = transform.position;
    }

    void Update()
    {
       
            if (transform.position.x < 52611)
            {
                transform.Translate(Vector3.right * 10 * Time.deltaTime); 
            }
            else
            {
                Debug.Log("Resetting position " + transform.position.x);
                transform.position = originalPos; // Reset position
           
        }
    }
}
wintry quarry
#

right we already knew this wasn't happening

#

because the object is NOT at x >= 52611

summer stump
#

Should have gone in the top if

polar acorn
wintry quarry
#

BTW this code makes me panic, deeply.

polar acorn
#

See how far it actually gets before it "falls off"

wintry quarry
#

Seeing this tells me something somewhere has gone horribly wrong

#

and the project is in trouble

#

The blind are leading the blind in this project

hidden heath
wintry quarry
#

Yes I believe that's expected. They want to keep moving until they reach that point

lost cypress
#

It falls off at 100000 lol

slender nymph
polar acorn
lost cypress
#

this is the original state:

stone saddle
wintry quarry
wintry quarry
#

why

molten dock
#

has anyone else experienced their scene being way darker when they load it ingame

wintry quarry
lost cypress
slender nymph
#

that would take over an hour

wintry quarry
#

why not like

#

near the origin

hidden heath
summer stump
wintry quarry
#

but yeah to move 70km in a few seconds it will have to be travelling at orbital velocities.

polar acorn
#

That's why you log

wintry quarry
#

-17000 is way less than 52611

#

even if this thing has no parent

polar acorn
wintry quarry
lost cypress
wintry quarry
#

Anyway whenever you release "Kerbal Train Program" let me know so I can play it.

summer stump
#

Also, They said it was from blender at that size, but it's scaled up to 600? What is this?
#💻┃code-beginner message

Edit: Sorry for the ping ultrasnow

wintry quarry
#

anyway Unity doesn't really support anything happening at more than about 1-2km away from the origin. This sounds like a perfect candidate for a floating origin system.

lost cypress
wintry quarry
#
Debug.Log($"My x position is {transform.position.x}");```
lost cypress
formal escarp
#

Hey. I have a player and i have two animations made. One for Idle and one for Walking. How can i make it so when you start the game its the idle thats playing and not the walk? its connected correctly on the Animator. And i wanted to ask how can i make it so you move and play the correct animation?

polar acorn
wintry quarry
polar acorn
#

At which point it will stay there for as long as this object exists.

formal escarp
polar acorn
lost cypress
formal escarp
#

I dont have any code. It just starts.

polar acorn
#

and then never leaves walk

formal escarp
summer stump
lost cypress
polar acorn
acoustic arch
#

alright for my enemy ai i have thought of a way to calculate all of the possible moves the enemy could make and weight them

lost cypress
formal escarp
polar acorn
lost cypress
#

guys it is now working

acoustic arch
#

some kind of coroutine waitunti maybe

lost cypress
#

because rn I set the limit for x =150 and it works like planned

polar acorn
lost cypress
#

transform.position = originalPos

#

I wanna start a little earlier than originalPos
what do i do?

dense root
#

What's going on, how come it says there's already a script named that when there isn't?

wintry quarry
dense root
#

This is a blank project

#

Weird even when I try to create a blank folder it's not working

#

Maybe I need to remake the project

crystal chasm
#

Have you tried turning it off, then turning it back on?

dense root
#

Sorry?

rocky canyon
#

delete the library folder and restart unity

#

looks like corruption

celest holly
#

Should i try and make my own inventory system or follow a tutorial

crystal chasm
#

Always try.

celest holly
#

i know following a tutorial would give me a more optimal script but i feel like i learn less doing so

eternal needle
summer stump
lost cypress
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{
    private float timer = 0; 
    private float moveInterval = 30f; 
    private MeshRenderer meshRenderer;
    Vector3 originalPos;

    void Start()
    {
        meshRenderer = GetComponent<MeshRenderer>();
        // originalPos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
        originalPos = transform.position;
    }

    void Update()
    {
        if (transform.position.x < 150)
        {
            transform.Translate(Vector3.right * 10 * Time.deltaTime); 
        }
        else
        {
            timer += Time.deltaTime; 

            if (timer >= moveInterval)
            {
           
                transform.position = originalPos;
                meshRenderer.enabled = true;
                timer = 0f; 
            }
        }
    }
}
#

guys this is my code

rocky canyon
celest holly
#

okay thanks for the advice

#

just whenever i follow a tutorial i realise im just mindlessly copying

lost cypress
#

I wanted to set a 30 sec interval, as in when my object passes a certain point, I want to reset its position and make it wait 30 second before making it move. The problem here is that it is not really waiting 30 seconds.

celest holly
#

i want tolearn these big systems so i dont have touse other peoples code

celest holly
#

or an invoke

crystal chasm
rocky canyon
#

🤢

celest holly
#

no

#

i refuse to use ai

rocky canyon
crystal chasm
#

It's not ideal, but still better than a tutorial.

rocky canyon
#

username checks out

crystal chasm
#

I'm sorry, I forgot where I was. Use Unity Muse, not ChatGPT.

rocky canyon
#

lol. thats marginally better

#

but still.. hands on / docs / tutorials is the secret sauce

lost cypress
rocky canyon
#

you can post w/o trying to emphasize your message
we'll still respond

polar acorn
slender nymph
crystal chasm
lost cypress
#

It says that there is no meshRendered attached etc.. but I saw online that this what I should do in order to control setting on and off the mesh.

polar acorn
rocky canyon
#

ya, probably missing entirely, or its missplaced

lost cypress
polar acorn
lost cypress
#

So do I have to create a meshrenderer component to be able to set on and off the mesh?

polar acorn
#

If you can see a mesh, there's a meshrenderer somewhere

crystal chasm
#

Are you just trying to hide the mesh?

lost cypress
#

Wait I get it.

#

There is no mesh because

#

I have mulitple objects in the same folder with a shared script and collider

#

should I create a meshrenderer?

polar acorn
crystal chasm
#

Just create a reference to the mesh renderer on the mesh.

polar acorn
# lost cypress how?

Usually with a public variable and then dragging in the object with the renderer

crystal chasm
#

Public MeshRenderer mRenderer;

ivory bobcat
# celest holly i know following a tutorial would give me a more optimal script but i feel like ...

If you're wanting to learn, consider asking yourself if you're at a level where you can digest and learn what's being shown or just simply copying/pasting and being overwhelmed?
Truthfully, it's going to take time either way. The main difference would be if you learn better by doing it yourself or if you learn better by repetitively implementing the work of others. Doing both would probably the better choice where the order would be what you'd be comfortable with:

  • learn and implement it yourself then observe how others have implemented it
  • learn how others have implemented it then implement it yourself
    Whichever is easier for you. The main goal would be to be learning and not simply accumulating unnecessary practices.
lost cypress
#

Can I not create a meshRenderer component for the entire folder containing my object that I wanna move? Let the code be the way it is?

polar acorn
lost cypress
#

At least now the error is gone and my program works but no meshs are being set on or off tho.

crystal chasm
#

It looks like you are only turning the meshRenderer on. It's already on, so unless you are switching it off someplace else, there is no need to turn it on.

summer stump
polar acorn
lost cypress
polar acorn
queen adder
#
    private void generateGrid()
    {
        parentObject = new GameObject();
        parentObject.name = "Tiles";

        tiles = new Dictionary<Vector2, Tile>();

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                var spawnedTile = Instantiate(tile, new Vector3(x, y), Quaternion.identity);
                TileSettings(spawnedTile, x, y);

                if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
                {
                    // Outline
                }

                tiles[new Vector2(x, y)] = spawnedTile;
            }
        }

        cameraObject.transform.position = new Vector3((float)width / 2 - 0.5f, (float)height / 2 - 0.5f, -10);
    }

What can I do to give an outer outline to all the outer tiles? I figured changing the sprite wont work because then it would need to be rotated etc based on the side the tile is on. Is that the only way?

lost cypress
#

I want the whole thing to dissapear so I gotta create a variable for everything?

polar acorn
crystal chasm
#

Create an array, and then use find objects of type <gameobject> then use a var to check if it has a meshRenderer.

rocky canyon
#

if u want to manipulate /modify something then yes it has to be a variable..
the code needs to know what ur talking about..
you can say.. disable the audiosource.. but the codes gonna ask which one

crystal chasm
#

Or make a public gameobject array and manually fill it if you are afraid of code

rocky canyon
#

u can change things directly.. but its still sort of a variable..
for example..
transform.position =
youre accessing the position property of the transform .. which is just a Vector3 variable

lost cypress
#

it has no mesh

modest dust
rocky canyon
#
    [SerializeField] GameObject objectToDisable;

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            objectToDisable.SetActive(false);
        }
    }```
lost cypress
modest dust
rocky canyon
#

you can reference other objects

lost cypress
summer stump
rocky canyon
#

doesn't have to be on the object running the script necessarily

modest dust
summer stump
lost cypress
summer stump
lost cypress
summer stump
#

You disable the OBJECT

lost cypress
#

so got confused a little

summer stump
#

Which disables the children

#

Which disables the mesh renderers (and every component)

modest dust
#

If you want to disable the meshes and keep everything else you could just recursively go through each child starting from the parent, check for a MeshRenderer and disable it.

#

Or just make a serialized array of MeshRenderers.

summer stump
#

this is the correct way to do what Jester was suggesting

lost cypress
modest dust
#

That's disabling the object itself in it's entirety

#

Will also disable any components and children

lost cypress
#

the enitre project or just its children

#

in which case that is the point

modest dust
#

Entire object alongside it's children

lost cypress
#

oops

lost cypress
modest dust
#

Depending on the end result you want, there are different ways

lost cypress
#

The only result I want is to make the object (and its children) invisble and then visible and toggle with it given if and else statements

polar acorn
#

You could make a new object that all of the meshes are children of, and then disable that. This way you just disable the meshes and not the main parent object

modest dust
#

Do you care about any other components attached to that GameObject?
No? -> parentGameObject.SetActive(false);
Yes? -> Recursive or array

polar acorn
#

That'll disable all of its children

lost cypress
lost cypress
#

I am kinda new to unity scripts

#

nvm

queen adder
#

How do I handle the corners? I want the corners to have the outline on both sides.

    public void SetOutline(bool left, bool right, bool top, bool bottom)
    {
        outlineOverlay.SetActive(true);

        if (left)
        {
            outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 180);
        }
        else if (right)
        {
            outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 0);
        }
        else if (top)
        {
            outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 90);
        }
        else if (bottom)
        {
            outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, -90);
        }
    }
main anchor
#

this is what it looks like when i sink, it just isnt very clear in the last video as there wasnt alot of objects around

wintry quarry
hushed hinge
rocky canyon
#

why would it work a 2nd time?

#

u set _isActive to false..

polar acorn
rocky canyon
#

it'll not be true again.. unless u manually switch it to true somewhere else

#

ahh.. nvm i do see where u set it back to true..

rocky canyon
polar acorn
# hushed hinge why?

Two reasons:

  1. It makes sure that you're calling the function at all
  2. It makes sure that you're calling the function on the object you think it's on
polar acorn
polar acorn
#

Show the inspector for it

hushed hinge
rocky canyon
hushed hinge
polar acorn
#

Wait, this is the object the script is on

#

I asked you to log the thing this collided with

hushed hinge
hallow sun
#

i think it may be an issue with <Player2D>, can you show us this script?

polar acorn
polar acorn
# hushed hinge

Why are you just logging the word "remove powerup". You should log collision to make sure you're hitting the object you are actually expecting to

#

That's why I said to log collision

rocky canyon
#
    public bool _isActive = true;
    private float _timer = 2.0f;
    private float _timerReset = 2.0f;
    private void Update()
    {
        if(!_isActive && _timer > 0)
        {
            _timer -= Time.deltaTime;
            if(_timer <= 0.0f)
            {
                _timer = _timerReset;
                _isActive = true;
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if(_isActive)
            _isActive = false;
    }
``` i tested w/ and reduced the timer to 2 seconds.. so it'd work faster.. but it **works**
@hushed hinge
polar acorn
#

Or is the object named collision

hallow sun
#

are you properly setting !_suitOff to false when you powerup?

hushed hinge
hushed hinge
strong geyser
#

Hello, my text is not entering the text field of my script

hallow sun
polar acorn
hushed hinge
summer stump
#

They said to log THE collision

summer stump
#

Oh, yeah, log the VARIABLE collision

#

That is why it is in that font

#

Debug.Log(collision);

#

See the lack of quotation marks?

hallow sun
# strong geyser yep

There's a bunch of options for some reason, but this one is what works for me:

using TMPro;
public TMP_Text textObject;
summer stump
#

But better would be Debug.Log($"Collided with: {collision}");

hushed hinge
summer stump
hushed hinge
hallow sun
prime bough
#

Hello! I'm having a little bit of trouble using UnityWebRequest.Post to send raw body data to a api server on Unity 6. I'm i supposed to be using a different function? It seems like it doesn't like it when I give it any other data in the second string slot.

teal viper
summer stump
rocky canyon
#

either one of these will work for UI text..

prime bough
wary igloo
#

does anyone know how why when my tiimerboo is true the timers doesnt start adding up ?? and when it reaches 10 it should reset but that is not happening here``` if (timerboo == true)
{
if (timers < 10)
{
timers += 1;
Debug.Log(timers);
}
}
else
{
timers = 0;
timerboo = false;
}

valid marlin
#

When does it set timerboo to false, since the else statement only runs if timerboo is false

rocky canyon
#

use debug statements to debug whats happening

prime bough
#

turns out i can use a upload handler and just send the raw data through that

rocky canyon
#
if (timerboo == true)
{
    if (timers < 10)
    {
        timers += 1;
        Debug.Log("Timers: " + timers);
    }
    else
    {
        Debug.Log("Timers reached 10");
    }
}
else
{
    timers = 0;
    timerboo = false;
    Debug.Log("Timerboo is false. Resetting timers.");
}```
wary igloo
#

it still for some reason does't run when the timerboo is true

valid marlin
#

Move the else statement after the if timers

wary igloo
#

oh nvm I see what I did wronig

#

it works now

#

thank you

valid marlin
#

Np

grizzled fulcrum
#

Alright I've been having issues with this walking animation for so long, but I'm having a multitude of problems with it
I want to solve at least one, so I would appreciate some insight on this issue at hand

Been trying to make the player jump, but we have a variable in which if you hold the spacebar, the player jumps higher, but it occasionally plays on that, and occasionally doesn't
What do I need to change here for the entire animation to play out both on a tall and short jump?
(I'm unsure what else I need to screenshot to have more info on the matter)

eternal falconBOT
grizzled fulcrum
#

That should be it--

random cave
#

How do I make my missile that uses rb velocity look where its going

#

Its kinda facing one direction ALWAYS

#

Firing code

#

Missile code

random cave
# random cave Firing code

It instantiates the missile and the shooting effect then deletes the shooting effect after 4s, switches to the next firepoint and repeat [This gives a left right effect]

random cave
# random cave Missile code

It just gets the component, adds velocity, enables the rocket's thruster and keeps adding thrust in FixedUpdate

ivory pollen
#

try setting transform.forward = _rb.velocity.normalized

real rock
#

Could also use something like lookAt (I forget the exact name) if you want it over time

random cave
real rock
#

What like it keeps moving but sideways or?

random cave
#

Yeah

#

Its like locking on to the target but doesnt care

real rock
#

Are you using AddForce?

random cave
#

Nah

random cave
#

Now back to struggling with guided missiles 😭

real rock
#

Sorry I’m on a phone so reading code kinda hard lol

random cave
#

Yeah all good

real rock
#

What’s rocketSpeed?

random cave
#

I've tried using LookAtConstraint & transform.LookAt but both I cant get the target because the missile a prefab

random cave
#

its speed

#

how fast it goes

real rock
#

Mm but what is it

#

Vector.forward or a (1,1,1)

random cave
#

a float

real rock
#

Oki

random cave
#

Also sorry

#

How do I make something smoothly rotate towards an object or have a delay like its a realistic thing not instantly snapping?

real rock
#

I wanna say Quaternion.Lerp is the best, which may also fix your looking at things issue

ivory pollen
#

there's also Vector3.RotateTowards()

random cave
#

Ok last thing

#

If im tryna get an object [a target] from a prefab how do I do that

#

Its kinda not in the game

real rock
real rock
random cave
#

Find it

real rock
#

Uhhh idk what you’re trying

random cave
#

Say I want my missile to RotateTowards an object that isnt inside the prefab

ivory pollen
random cave
#

I cant serializefield it

#

I cant assign it using the GetComponent

modest dust
ivory pollen
#

@random cave the thing that is responsible for instantiating the prefab should also set some kind of .target field on it

random cave
modest dust
random cave
#

I want my missile to look at a ball that is in the scene, since its not with the prefab I cant assign it or anything

random cave
ivory pollen
#

oh, if it's always the same target, that's easy. You could stick a tag on the target, and then use GameObject.FindWithTag() to find it in the missile's Start() method, for example.

acoustic arch
#

!code

eternal falconBOT
real rock
#

FindWithTag or FindObjectOfType are probably best

modest dust
#

Pass it into the missile after instantiating or just make a static instance of it so that the missile get's it by itself

modest dust
random cave
real rock
#

Depends what specifically you’re looking for

random cave
#

Unity also pauses if I leave it empty

real rock
#

Is OfType in optimised? Yes. Is it very convenient for getting the component you need when optimisation isn’t an issue? Yes

modest dust
ivory pollen
random cave
#

can I do
enter script name here.ball and I can use that?

real rock
#

I mean

#

Yes

random cave
#

if ball is a gameobject

real rock
#

But no

random cave
#

no harm in trying

ivory pollen
#

that sounds close to the static field approach that @caesar is proposing.

modest dust
#

You could, that's a static instance, most likely

random cave
#

yeah thats what im getting

#

ok ok thanks I will go try now

real rock
#

Do static fields work in the inspector properly?

ivory pollen
#

no

modest dust
random cave
#

yes it is from the instantiating script

ivory pollen
#

downsides: they are also a bit of an issue if you want playmode hotreload to work, or if you want to disable domain reloading when entering/exiting playmode

random cave
#

the mother of the missile lmfao

real rock
#

So you’d be probably looking at a singleton for the static approach which I’d argue is less what this channel is aimed at. What caesar is actually saying is smart though

random cave
#

yes

#

caesar is very smart human

#

i think

real rock
#

I prefer to dynamically get stuff at Start but I have a bad habit for that that I wouldn’t recommend if you’re aiming for super optimisation

random cave
ivory pollen
#

it's how much you want it to rotate. probably you want something * Time.deltaTime

real rock
#

Radians are kinda like degrees but in another unit, it’s the max rotation (I think?)

random cave
ivory pollen
#

oh, then use fixedDeltaTime

real rock
random cave
#

I am still missing one number

#

its 2 vectors3 and 2 floats

real rock
#

Unless I’m misremembering how that works in fixed

real rock
#

I don’t remember how that one works

random cave
#

maybe max turn rate?

#

imma set it to 60 and test it

eternal needle
random cave
#

how do I make transform into a vector3

#

wait no im stupid

#

My brain thought transform was position for a second and confused why its not a vector3

real rock
#

Lol

#

Been there done that

random cave
#

Well now the moment of truth

vital hinge
#

anyone knows why input field doesnt work on mobile? The keyboard doesnt pop up to allow me to type

real rock
#

Can you not cross post pls

#

Someone will get there

random cave
#

I dont want it to work because then I have to work on making guided bombs that GUIDE MOVING TARGETS [like bruh]

real rock
#

Well thats easy

#

Once you have them guide towards a stationary one you just change it to a moving one

#

Should be the same logic

random cave
#

Now that im thinking bout it

#

I just get the moving target, lookat its position and done

real rock
#

Exactly :3

random cave
#

Bro what that seems too simple

real rock
#

A lot of the time something that seems insanely complicated is just a small change

wheat tangle
#

Does anyone know why my visual studio code just opens a blank screen with just the normal stuff at the top
(I have literally never used unity before this)

vital hinge
real rock
#

I was ready to tear hair out over a bug someone found because I spent like 2 days fixing it, I’d swapped a - to a +

random cave
#

😭

real rock
#

I’d help if I knew but I’ve not needed that yet so :/

random cave
#

I havent bug fixed yet

#

Maybe because my standards are too low lmfao

real rock
#

Mine was not a fun bug tbf

#

But it was a high impact one

random cave
#

If I give my game to someone to test they'd probably cry

real rock
wheat tangle
real rock
#

Can you post a pic of what VS looks like?

wheat tangle
#

It's going to take maybe a minute or two because I have to get discord on my PC turned on

real rock
#

Oki

modest dust
real rock
#

^ I’m so glad I started testing this terms game early

modest dust
#

The amount of bugs they notice is sometimes insane

random cave
#

Imma do that

#

But I barely have any friends lol

real rock
#

My first and second term didn’t get much testing but this term I’m already on V0.5.2 and it’s week 3 I think?

random cave
#

Dang thats a lotta bugs

real rock
random cave
#

Lotta updates?

wheat tangle
#

here it is

real rock
#

Sometimes an update is a bug fix spree and sometimes it’s just a hot fix or two

frosty hound
#

Can you all take this to DMs, this isn't a hangout channel.

real rock
# wheat tangle here it is

Hhh been a while since I’ve had that, try ending the task in task manager and double clicking the file again

real rock
random cave
real rock
wheat tangle
#

Do you know if there's anywhere I can look or try to find the way to fix this

eternal falconBOT
modest dust
# random cave But I barely have any friends lol

One is already enough, it's about quality, not quantity. Both are important but having a single person who'll check your game from start to finish is already better than doing it yourself, as the more you develop and test the more you tend to skip over some stuff and might not notice a fair amount of bugs.

real rock
# eternal falcon

Would this fix the issue? Looks like their IDE isn’t even opening the files properly rn

real rock
unique gust
#

hey guys i need some help

#

i'm making a snake game in 2022lts version and i made a line to spawn the apple but it causing an error and idk how to fix

#

private Transform SpawnApple()
{
return Instantiate(applePrefab, new Vector3(Random.Range(-9, 9), Random.Range(-5, 5), 0, Quaternion.identity));
}

frosty hound
#

And what does the error tell you?

unique gust
#

here's the example i'm following and the editor says that does not support 4 arguments

slender nymph
#

look a little closer at the example then your code

frosty hound
#

There is a small difference between yours and the example

unique gust
#

i was wrinting wrong oh gods

shell ice
#

Hi there,

my question is whether there is some way I have missed of making a gameObject a child of another object without affecting it’s local scale?

Example:

Object A has a scale of 1,1,1 and it is not a child of any object.

Object B has a scale of 1,1,0.5.

At runtime, Object A becomes a child of object B. Currently, object z suddenly changes scale along the Z axis to account for the 0.5 of it’s parent. Can I avoid this change in any way?

cyan imp
#

Has anyone had an issue where some animations don't fully listen to gravity while others do...? Basically 2 of my animations aren't fully contacting the tilemap but 1 of them has no problem working properly and I'm so confused lol

unique gust
#

Now another problem has arisen, the game spawns the apple but when passing over it it does not destroy it even though it has the function

slender nymph
#

!code 👇

eternal falconBOT
unique gust
#

how i use it?

slender nymph
#

did you read the bot message?

unique gust
slender nymph
#

transform.position == appleInGame.position this is not a good way to determine if two objects are overlapping. this will only ever be true if the objects are in the same position, but just because they overlap doesn't mean that they are in the exact same position

unique gust
#

how can i do it?

rich adder
#

probably an overlap or something, or trigger?

slender nymph
# unique gust how can i do it?

you should start by going through the beginner courses on the unity !learn site. the pathways teach you all about the important stuff you'll need to understand, like collision detection

eternal falconBOT
#

:teacher: Unity Learn ↗

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

unique gust
#

but in the video I'm watching he collides and "eats" the apple

red siren
#

I'm having trouble setting the position of an UI element that gets instantiated at runtime. Basically I spawn an object, then spawn the text on top of it. I can't get them to align. Are there any function helpers for this?

#

I'm thinking ScreenPointToLocalPointInRectangle but it doesn't seem to be working

slender nymph
rich adder
red siren
#

I'm parenting it to the canvas

#

the canvas is set to scale with screen size

#

overlay

#

That's the canvas and that's the Text that I'm instantiating

rich adder
#

just use anchored position then

#

if they're both ui

red siren
#

Basically I need to position the Text to an object that's also instantiated at runtime

#

So spawn object, spawn text. It's like one of those popups for health

rich adder
#

an "object" is very vague

unique gust
# slender nymph can you link the video where they are comparing the positions for equality to ch...

Faça o jogo SNAKE em menos de 20 minutos!
Preste atenção em tudo o que será compartilhando nessa aula. Você certamente utilizará todos os conceitos passados em seus próprios jogos.

✅Meu curso para iniciantes(https://criandomeujogo.com/cursoinicianteunity)
✅Ebook "5 dicas para começar na Unity"(https://criandomeujogo.com/ebook5dicasiniciarunity)...

▶ Play video
rich adder
#

everything is an object

red siren
#

GameObject

rich adder
#

UI objects are also GameObjects

red siren
#

Gotcha

rich adder
#

you mean like a world object?

red siren
#

A GameObject in world space yeah

rich adder
#

oh have you tried just WorldToScreenpoint ?

slender nymph
red siren
#

Let me try

rich adder
slender nymph
# unique gust can u tell me why?

well there's the whole "comparing positions to check for an overlap" thing that is a truly god awful way of checking for collisions. what if the objects are 0.001 units away on a single axis? they are fully overlapped, but the positions are not the same so they don't count as overlapping with that terrible code

hushed hinge
#

i have a problem, is that the twon different pencils in the background are like shown on both of the cameras even though each camera are supposed to be focues on the background which is supposed to follow the player

#

it works for all of the backgrounds

unique gust
rocky canyon
#

well, ur gonna need to know about colliders for game dev anyway

#

its just 1 of many important parts

slender nymph
unique gust
#

So I think I better stop the project for now

rich adder
#

come back to it when you learn the proper tools/functions available to you

red siren
#

Yeah it's not working.

What I'm doing : Getting the world space object's transform. Using WorldToScreenPoint, then ScreenPointToLocalPointInRectangle, then parenting it.

rich adder
#

why ScreenPointToLocalPointInRectangle.
just use screenpoint and set RectTransform anchorpos to it?

red siren
#

Yeah that seems to work better. I think I'm getting up the anchors of the text incorrectly

#

Would the canvas in the prefab cause issues or it's just temporary?

rich adder
#

you might need to account for scale of canvas

red siren
#

makes sense, let me see

rich adder
#

also just for shits n gigs try just setting transform.position maybe?

gray elk
#

I'm trying to have my cannon change position based on where the mouse is, but it always chooses to the same angle when the mouse is clicked no matter its placement on the screen. Does anyone know what is causing this?

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

public class CannonManager : MonoBehaviour
{
    public GameObject cannonBallPrefab;
    public Transform firePoint;


    private Camera _cam;
    private bool _pressingMouse = false;

    private Vector3 _initialVelocity;

    void Start()
    {
        _cam = Camera.main;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
            _pressingMouse = true;
        if (Input.GetMouseButtonUp(0))
        {
            _pressingMouse = false;
            _Fire();
        }

        if (_pressingMouse)
        {
            // coordinate transform screen > world
            Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;

            // look at
            transform.LookAt(mousePos); 
        }
    }

    private void _Fire()
    {
        // instantiate a cannon ball
        GameObject cannonBall = Instantiate(cannonBallPrefab, firePoint.position, Quaternion.identity);
        // apply some force
        Rigidbody rb = cannonBall.GetComponent<Rigidbody>();
        rb.AddForce(_initialVelocity, ForceMode.Impulse);
    }
}

gray elk
red siren
#

Got it to work, it was a problem with the scaler

slender nymph
red siren
#

It's not perfect, but close enough I guess for now

rich adder
red siren
#

It works with constant pixel size, but it breaks with match screen size.

#

screen to screen size*

#

It kinda misaligns it a bit

#

If I change the ref resolution to 800 x 800 it works perfectly as well

#

But as soon as I go for a ref resolution of 16:9, it breaks again

#

at least it kinda works

rich adder
red siren
#
           Vector2 anchoredPosition = (screenPoint - centerPoint) / canvas.scaleFactor;```
#

This is what I got. I guess I should divide each component of the vector2? I'm a bit mind numb right now.

rich adder
#

oh I was thinking something like

var canvasScale = canvas.scaleFactor * Vector2.one;
var scaledScreenPosition = new Vector2(screenPosition.x / canvasScale.x, screenPosition.y / canvasScale.y);```
but its prob not right
red siren
#

ah yeah

unkempt carbon
#

hi guys does anyone know how to add more than 1 submenu for create asset menu?

gray elk
queen adder
#

Hi

#

Guys I want to create an score board and an starting screen for my ar game any tips?

slender nymph
unkempt carbon
queen adder
#

And I had a problem with my hit box how to fix it

deft grail
#

what does it do and what do you want it to do

#

show a screenshot of what it does

queen adder
#

It's a Ballon shooting game

deft grail
summer stump
#

See #📖┃code-of-conduct
It is against the rules to dm people without permission

It is also not a good idea for YOU. Less eyes on the issue = less help

gray elk
# slender nymph huh? your issue was with ScreenToWorldPoint. i provided a resource that explaine...

I'm sorry, I have been sick as a dog all weekend and I'm being a lot slower than usual, my bad

I made this change to my code:

if (_pressingMouse)
        {
            // Calculate the distance from the camera to the near clip plane
            float distance = _cam.nearClipPlane;

            // Transform screen coordinates to world coordinates using the distance
            Vector3 mousePos = _cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance));

            // Set z-coordinate to 0 to ensure the cannon aims at the same plane as the cannon itself
            mousePos.z = 0;

            // Look at the mouse position
            transform.LookAt(mousePos);
        }
    }
slender nymph
#

this is AI generated code, isn't it

gray elk
gray elk
#

Our professor suggested we use AI to figure out issues with code we were having for some reason haha

#

I know thats what i was thinking too but when he demonstrated it in class it worked for what he was doing so i guess thats why he suggested it notlikethis
he said if we could pinpoint the problem it would be helpful

queen adder
#

Paying thousands of dollars just for the proff to say use gtp

red siren
#

I wouldn't suggest using chatgpt, it's gonna block your progress

gray elk
#

he's a great prof, he has been teaching us stuff all year, but if its anything outside of our understanding he said to use Unity forums and chatgpt to skim the code and find where the flaws may be
of course he said it is unreliable, because obviously, but there wasnt any other methods given if we were thinking outside the box from what was learned in class

#

we haven't learned any mouse location sensoring for the semester and i thought it would be much easier to apply but i was incorrect

red siren
#

One way to progress is to learn what words you should be using and learn to google or look for tutorials for it, another one that's very valuable is learning to read the documentation

#

It's weird to read the docs at first, but once you get into it it's really really useful

queen adder
#

Docs?

#

Is it C#scripts?

gray elk
#

I've been watching a tutorial for a physics based cannon ive followed step by step at, which is helpful but everything works EXCEPT the cannon angling and im insure why

deft grail
red siren
#

Unity documentation, learning the API. It doesn't fix all problems but it helps. If you know what class you want to use, you can read up on it and learn what it's able to do for you

rocky gale
#

whats the advantage of using abstract classes as opposed to interfaces?

charred spoke
#

Thats like asking whats the advantage of eating apples over oranges

rocky gale
#

i mean it seems similar

north kiln
#

Abstract classes are mostly intended for providing default implementations. Interfaces only recently allowed for default implementations, so the gap has lessened, though there are still differences. Abstract classes can have fields, and I don't think interfaces can iirc?

summer stump
rocky gale
#

ah

north kiln
#

But really it's a semantic thing, an abstract class means you expect a subclass to be that thing, but an interface expects an inheritor to implement that thing

rocky gale
#

oh i see

#

so with abstract theres a default but you can still change implementation in subclasses?

charred spoke
#

You use abstract classes when you have a concrete base functionality you want to inherit. Imagine a abstract mammal animal class. All mammals breath so you would implement that in the base class. Interface are when you have no concrete functionality but still provide a method signature.

rocky gale
#

oh that makes sense

charred spoke
rocky gale
#

oh ok

#

i understand better now, thanks

north kiln
#

The thing is that categories suck and implementations can vary a ton, so it is apples v oranges, do what feels right to the scenario.
For example, reptiles also breathe, so why would mammal implement breathe. Would you move that to a subclass, or would that be an interface? 🤷 depends on what matters as far as the implementation is concerned

rocky gale
#

mmmm yea that makes sense

pseudo laurel
#

I need help with this error I've tried everything its impossible. Heres the script:

using UnityEngine;
using UnityEngine.EventSystems;

namespace HTC.UnityPlugin.Pointer3D
{  
    [RequireComponent(typeof(BaseMultiMethodRaycaster))]
    public abstract class BaseRaycastMethod : MonoBehaviour, IRaycastMethod
    { 
        public BaseMultiMethodRaycaster raycaster { get; private set; }
   
        protected virtual void Awake()
        {
            raycaster = GetComponent<BaseMultiMethodRaycaster>();
            raycaster.AddRaycastMethod(this);
        }

        protected virtual void OnEnable()
        {
        }

        protected virtual void OnDisable()
        {
        }

        protected virtual void OnDestroy()
        {
            raycaster.RemoveRaycastMethod(this);
        }
        public abstract void Raycast (BaseRaycaster module, Vector2 position, Camera eventCamera, List<RaycastResult> raycastResults);```
red siren
#

Is that the full script?

#

cuz if it is you're not closing the class, you're missing some }

#

Every { needs its corresponding }

ivory bobcat
#

What line is 31?

#

Is this your code?

red siren
#

It's the last line of what he copy pasted, might be something he just found cuz the error from what I see is pretty basic

torn rain
#

This is a super basic question but is there a way to mass assign things in the unity editor? I have like hundreds of sprites that I need to assign to scriptable objects and I was wondering if there was a way to automate the process

#

Rather than dragging and dropping

timber tide
#

mix in some onvalidation and then serialize it to a list

#

or ISerializable interface

#

oh, or do the menuitem attribute way as shown in the example

blissful spindle
#

I have a 2D project and I want to rotate my player towards my pouse position but this seems to not work as intented can anyone help me? https://hatebin.com/tqqtrsrupe

slender nymph
#

there are a number of issues with that. firstly, that Input.mousePosition is in screen space not world space, which is where i assume your player is at so you need to convert that using the ScreenToWorld method on the Camera

#

then you're trying to rotate a position to another position and use that as a direction, that makes almost no sense at all. direction is computed with (endPosition - startPosition).normalized

#

and finally, Quaternion.LookRotation makes the Z axis point along the direction you pass to it. in 2D the Z axis is used for depth, it points in toward the screen. so when you make your object point its Z axis in the direction of the mouse it will rotate in a way you are not expecting. for 2d the "look" direction is typically either transform.up or transform.right depending on how your sprite is designed. you can just set the direction from the player to the mouse as the transform.up/right (whichever is its "forward" direction)

#

also why bother storing the mouse position in a field if you only use it in that one method?

topaz mortar
#

I have a Character class, where I ended up putting all my character logic and visuals in, it's 600 lines of code.
But now I'm working with Cloud Save and json data to save my character
Like half the attributes are for visual stuff that don't need saving and a lot of the functions are too
I'd say what I need for saving/loading my character would probably be only 100-200 lines of code.

Any ideas how I would "fix" this?
Do I completely rework the class and separate it? How would I split it up?
Would it work just fine like it is now with a lot of the attributes not in json to Serialize/Deserialize it? Or would I have to write custom functions for this? I've been using JsonConvert.SerializeObject and DeserializeObject on a simple class and it works great.
Or is there some other way I don't even know of?

#

I have a Character object in my scene as well, but can't really think of a clean way to split it up. It just has the Character class script on it now.

sand gate
#

!docs

eternal falconBOT
sand gate
#

ok so i tried learning unity 2 years ago but had to stop due to highschool. Now that i have graduated hs , i have started learning it again. I donot want to follow any yt tutorials as i cal easily fall into the "only watching tutorial" thing. My main problem is the scripting. I suck at scripting. I would love an advise.

#

scripting is the worst part for me

rare basin
#

advise about what exactly

#

ask specific question

#

there is no general advise how to learn programming

modest dust
eternal falconBOT
#

:teacher: Unity Learn ↗

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

sand gate
#

I want to learn unity basics

#

But from where

#

I have done c# basics

modest dust
#

The bot link right below my message

sand gate
#

thankyou

burnt vapor
eternal falconBOT
fierce shuttle
# topaz mortar I have a Character class, where I ended up putting all my character logic and vi...

Personally, I would split your serializable logic, and even your visual references if you want, if your able to offload the visual logic to another system your character can plug into, I think that may be helpful incase youd want other systems to reuse parts of your character (maybe for AI for example), but without much code change, you could have a reference to a serialized POCO to represent your data, and save/load that, you would have to write functions to save your specific data, though if you decide to build a generic save/load system, then youd only need to write those functions once, and any class can use it to save and load its specific data

timber tide
#

I've been playing around with a ILoadable and ISaveable idea where I'd just have these custom methods in each class with their own initializer logic instead of sticking all that logic in the manager.

topaz mortar
#

ChatGPT called it a DTO class

real rock
#

DTO?

#

Data to object I wanna guess?

topaz mortar
#

Data Transfer Object

real rock
#

Makes sense

topaz mortar
#

Is it weird/bad to have these classes: Character (just the raw data), CharacterLogic, CharacterVisuals

But a lot of the logic is tied to the visuals
Say health changes, that's logic, but it also need to be redrawn on the canvas
Pretty easy to call a function in the other class, but it might become hard read the code really fast?

real rock
#

Sounds sensible to me tbh

fierce shuttle
topaz mortar
#

I have some logic for changing player max health, on level up for example.
This needs to happen on my server (non-persistent, REST API) because we don't trust the client
The issue here is that when I sent a request to my server, the client has to wait for a reply to be able to update it's max health, which looks pretty bad
The logic could be really simple like maxhealth += 10 but if I decide to change it to 15 at some point, I would need to do it on both client & server, which I was strongly recommended against here.
So how do I fix this delay?

real rock
fierce shuttle
topaz mortar
#

I just have the UI elements as attributes on my CharacterVisuals script now

#

[SerializeField] private Slider healthBar;

eternal needle
timber tide
#

usually if it's UI related then I'm subscribing to it

#

if hp changes -> UI needs to be notified then updated

eternal needle
#

It also helps if you're reusing scripts, the character script shouldnt know anything at all about the HUD (visuals). This lets you reuse the character script if you're making npcs or whatever, since you would handle their visuals differently

timber tide
#

just playing around with networking it's gotten me to the point where I do need to split a lot of the visuals and the scripting data, but sometimes on smaller objects I feel like I could just handle it together in a single script

#

like, when you think about monobehaviours that are slots of an inventory, the correct way is for them to just have scripts that relay what's been clicked to the inventory, but if I'm lazy enough I'd just use those monos and make them into the actual data object too

#

another thing too is that you don't really need to share or reuse inventories (UIs) across different clients. To each their own so just integrating what's on the scene together with your data object can make sense.

topaz mortar
#

Is there some way to make this work? I need exactly the same logic to increase strength, dexterity and intelligence
IncreaseStat(ref Character.Vitality, 1);

#
        {
            // Do not add stats if there are not enough points available
            if (CheckNotEnoughStatPoints(amount))
                return;

            stat += amount;
            Character.StatPoints -= amount;
            CharacterVisuals.SetStatsUI();

            SaveStats = true;
            SaveStatsTimer = 0;
        }```
gaunt ice
#

you cant pass properties as ref or out

ivory bobcat
topaz mortar
#

yes

#

it's a property of Character

ivory bobcat
#

Likely you're only passing a copied value

topaz mortar
#

I understand the error, I just don't know how to write this properly, without having to write a separate function for each stat

teal viper
ivory bobcat
#
var vitality = Character.Vitality;
IncreaseStat(ref vitality, 1);
Character.Vitality = vitality;```
teal viper
#

*use a reference type for stats

topaz mortar
ivory bobcat
topaz mortar
#

In these situations I hate that C# doesn't allow you to pass variable names like PHP does

gaunt ice
#

dont make it property

teal viper
#

Character.Vitality.ModifyStat(1);

ivory bobcat
gaunt ice
#

public get/set doesnt encapsulate anything

#

just make it class field

teal viper
ivory bobcat
#

The return value from the property isn't the back field variable itself but a copy.

topaz mortar
teal viper
topaz mortar
#

What you mean by that or how it would work?

teal viper
#

C# is an object oriented language, so that's the most natural way to do what you're trying to do with refs.

topaz mortar
#

I'm just trying to find a way to turn this (example has 2, but I have 4) into one function

        public void IncreaseStrength(int amount)
        {
            // Do not add stats if there are not enough points available
            if (CheckNotEnoughStatPoints(amount))
                return;

            Character.Strength += amount;
            Character.StatPoints -= amount;
            CharacterVisuals.SetStatsUI();

            SaveStats = true;
            SaveStatsTimer = 0;
        }

        // Increase Dexterity
        public void IncreaseDexterity(int amount)
        {
            // Do not add stats if there are not enough points available
            if (CheckNotEnoughStatPoints(amount))
                return;

            Character.Dexterity += amount;
            Character.StatPoints -= amount;
            CharacterVisuals.SetStatsUI();

            SaveStats = true;
            SaveStatsTimer = 0;
        }```
#

Adding a stat class sounds interesting

teal viper
#

Or you cloud use a dictionary of <StatEnum, int> to store your stats. Then it would be as simple as Character.Stats[StatEnum.Vitality] += value;

burnt vapor
#

Make a Dexterity struct and implements the + and - operators, and set the value that way

#

@topaz mortar

topaz mortar
#

yeah this is all a bit too complicated for me lol

burnt vapor
#

Structs work the same as a class if you assume it is just like your integer

#

But it takes some reading

topaz mortar
#

I tried making a Stat class, but it doesn't fix my issue because there's still duplicate code in each function then, but it was interesting to learn this 🙂

burnt vapor
#

Why care about duplicate code?

#

You can't merge everything

topaz mortar
#

yeah I think I'll just stick with duplicate code 😛 not a big deal

burnt vapor
#

If you want an easy to read way, a struct is one of those ways

topaz mortar
#

just looking for a better solution

gaunt ice
#

just use field instead of property if no special logic needed to be encapsulated

real rock
topaz mortar
#

having github copilot auto-generate the duplicate code makes life easy 🙂

real rock
#

I think you have some bugs

topaz mortar
#

yeah I moved Character to CharacterLogic & CharacterVisuals, nothing major, just gotta update all the references

#

and optimizing some stuff while I'm at it

timber tide
#

//class that maps an enum, for all its entries, to a list of StatValues which when computed returns a final float value pertaining to that enum entry
public class Stats<E, T>
where E : Enum
where T : StatValue<E> //stat value is just wrapped values (percent, additive, ect) before being computed is added to our float dict value
{
  //keep track of our instances of increased values
  Dictionary<E, List<T>> statValueDict = new();

  //values which are the result of all computed StatValues
  Dictionary<E, float> valueDict = new(); 
    
  public virtual bool AddStatValue(T statValue) { }
}
#

this is how I encapsulate my stats which is just a bit more logic than doing enum dict mapping

topaz mortar
#

looks like something I might be able to understand in a year or two lol

#

I should really get a book on OOP and study it some more

timber tide
#

it's just saying that an enum type, for all entires, have some stat they are specific to

burnt vapor
#

If this is something you don't understand, why exactly are you generating your code using AI?

#

Sure it would help if you learned the process yourself?

topaz mortar
#

I understand all the code I use 🙂

queen adder
#

Hi there, i have added this models of a mannequin, and i wanted to add a feature to them but idk how i do it, i wanted to them to make a random audio, but only when i am a little far away, if i am to close then them don't make any sound, but if i am far from them, it would make a random audio.
Does anyone know how to add that feature?

real rock
#

Tbf VS started trying to guess what I’m typing and I never bothered to tell it to stop

topaz mortar
#

if I'd use AI to generate something like that I would definitely figure out how it works

real rock
#

I might have to soon though because it’s getting less accurate

topaz mortar
#

I've been programming for 20 years, but just never got to any of the more fancy/advanced stuff

topaz mortar
topaz mortar
real rock
#

I don’t like to fully AI gen unless I’m completely stuck on learning a concept but so far VS has been not too bad at taking what I’m typing and extrapolating my goals based on names

topaz mortar
# burnt vapor Sure it would help if you learned the process yourself?

what would you recommend to learn stuff like this?
to me this is far beyond the basics, I've been a professional web developer for 4 years and never came into contact with stuff like this
most of my colleagues barely understood what OOP means, well not sure if I'm very good at it either since starting working with Unity

#

or it might just be the difference between PHP & C#

real rock
#

Definitely

topaz mortar
real rock
#

Php to me as someone that knows python, js and c# and has education in CS is a really bad “language” that basically tricks html into doing clever things (that’s my perception at least). Even JS which works on browsers tends to have a much more object oriented structure, but C# takes that much further than browser based stuff

topaz mortar
#

PHP is just a lot easier than C#, at least how I remember it, it allows you to do so much more, most of which is probably just bad practice and why C# doesn't allow it

real rock
#

Eh it depends

timber tide
#

I just use php because everything still uses php

real rock
#

I have no .net background so I can’t speak for that side of it but I would be in disbelief if php and html could make a game half as well as c# and Unity

topaz mortar
#

I haven't used it for like 3 years now and started working with C# like 6 months ago

real rock
#

People say python syntax is weird but my mind is broken whenever I look at php

topaz mortar
real rock
#

I mean hell Unity can build to webgl

#

But that doesn’t make it optimal, especially from a developer side

rare basin
#

what did you programm past these 20 years lol

topaz mortar
#

yup, just never got to any complicated/advanced stuff

#

basic PHP mostly

rare basin
#

it's not advanced

#

it's kinda basic

#

of c#

#

or any language

real rock
#

Tbf generics don’t exist in other languages like python and js because they aren’t type safe so I only learned about them recently

topaz mortar
#

I'm really bad with terminology as well, so I might understand "generics" but just not recognize the word

rare basin
#

generics exists in python

#

and in js

real rock
#

Not if you don’t set a type for anything sunglas

topaz mortar
#

nope, never really used Generics, seen it a few times but never had a need for them

#

or I just never learned what they are so didn't recognize the need for them

real rock
#

They’re handy and powerful

rare basin
#

i can't kinda understand how can you use something for 20 years

#

and don't want to improve

#

your skills

real rock
#

I’d recommend learning them or finding something online that uses them understand use case

topaz mortar
#

that's a weird assumption

#

I looked it up, I understand what they are

timber tide
#

i mean, if you can understand why list works in c# then that will probably help out

topaz mortar
#

I like learning while doing, I hate theory
so if you can find a way to work around it without actually needing it, you kinda never learn stuff like that

rare basin
#

weird approach but alright

topaz mortar
#

Anyway, if anyone can recommend a book to teach me these "basics" I'd be very interested

real rock
#

If you want an example for something I first used them for, I made a script that emulated pythons random.choice. I could have made an interface for every type I needed or I could use a generic to allow it to handle a list of any type

gaunt ice
#

generic in java/python/typescript is just static type checker iirc, the value is still got boxed

topaz mortar
# rare basin weird approach but alright

I have dyslexia, which makes it very hard for me to understand terminology like "generics" without actually using them
So I would only learn what they are and how to use them by actually using them myself
I learned programming in school and it never came up and then afterwards I never needed it, or maybe I did, but I just worked around it not knowing it

#

In a week I won't remember what "generics" are if someone would ask me

#

I can't even remember the difference between parameter and attribute lol

rare basin
#

well, actually it depends

#

depends if it's value or reference type

#

iirc value types are being boxed into their correspdoning wrapper types

real rock
rare basin
#

but there's no boxing for reference types

real rock
#

Parameters are limited to the context of its method, attributes are limited to the context of the whole class

#

Otherwise they function sumilaraly

topaz mortar
rare basin
#

you don't know what's a value or reference type?

topaz mortar
#

I probably do, I just don't recognize the terminology

topaz mortar
#

dyslexia is fun 🙂

rare basin
twilit dirge
#

I have scriptable tiles I'm using for seasons. To save myself the time, I'm using a script to programatically update all the sprite references for each season. This works, at runtime and in the editor.

But when I restart the unity editor all of the references to the sprites just go blank, except for the first season which retains all the sprite refereneces. why is this happening? I'm saving the asset after I update sprite list, I'm saving the project

#

sprite references to other tiles that I added manually are also retained, but the first season's were all added programatically as well, so it makes no sense for this to be happening.

#

oh wait. i think i realize it's because when I added the first season to all these tiles it was added when the actual asset was created too

#

well, how do I make sure all these references are saved when updated programatically?

#

nvm im dumb i needed to mark it as dirty

languid spire
twilit dirge
#

i like how i come to that realization as soon as you reply-

topaz mortar
twilit dirge
#

thanks yall

languid spire
manic sphinx
#

I need help, I'm a beginner and I want to save the open chests so I can't open them again and they stay open, the problem is that I change scenes in the game so it gets complicated because they go by index and if I change scenes and the I try to load it goes crazy, I don't know if I explain myself, can anyone think of how to do it? Could I just destroy the gameObject with tag chest that I just opened and it disappears? The problem with deleting it would be that if I start the game again it would be there again, right??? please help

manic sphinx
#

I have no problem sharing between scenes, the problem is that the chests are a list with an index, because I am not going to pass chest to chest, that is where I have the problem, a list between scenes with an index number, when in a scene the 012, in the next one it should be 234, but it is still 012, so the order does not work