#💻┃code-beginner

1 messages · Page 773 of 1

north kiln
#

Then post code properly so people can talk about it without having to re-write it or read through a greasy screenshot

grand snow
#

I detect british school/uni computer

onyx silo
#

indeed

spiral summit
#

currently my device has visual studio code and visual code, i want when i open resource it will go to visual studio code, what should i do?

hot wadi
#

!ide

radiant voidBOT
hot wadi
spiral summit
#

yes, i have followed the instructions to configure it before

hot wadi
#

Did u set the script editor in the project setting?

restive brook
spiral summit
#

oh god i cant see visual studio code option

restive brook
#

Browse and find it

grand snow
#

Shouldnt be needed if vs code is installed correctly 🤔

spiral summit
#

thanks i found it,now just reboot right?

hot wadi
#

Good old “turning it off and on”, yes

spiral summit
#

thanks it worked there are some options of the app on the bottom right corner of the screen what should i do?

meager siren
#

Whats the Quaternion.Angle equivalent for transform.position?

meager siren
#

Right?

teal viper
spiral summit
#

thanks for the suggestion, i feel this unity version is quite good

hot wadi
teal viper
meager siren
#

hold on

hot wadi
#

Position is a vector entity but it only represents a point. Vector in general means direction

meager siren
#

im trying to replicate this but for position

#

and or vector

meager siren
#

wait I think I just figured it out

#

nope

#

im a dumbass

spiral summit
#

I don't know where the code is wrong but I don't have the "on collect effect" part like in the tutorial

hot wadi
#

‘GameObject’, not ‘gameObject’

#

Code is case-sensitive

teal viper
radiant voidBOT
teal viper
#

Configure your ide to see proper error underlines

#

And suggestions

hexed terrace
#

and don't ignore the errors in your console

spiral summit
#

why is it ide, i remember doing it?

hot wadi
#

Lol it’s still not properly configured

#

Clearly something is missing

#

No wonder the vs code did not show up

#

The option is VS Code, don’t mistake it with Visual Studio

plucky lintel
#

Hello, I am procedurally generating meshes at runtime. However, I want to use MeshLOD in the meshes I generate. Does anyone know how I can use its API?

teal viper
plucky lintel
# plucky lintel

The MeshLOD options are not visible in MeshRenderer. I think I need to generate a meshlod from somewhere in code

spiral summit
#

I followed the instructions in here, anyone having trouble with the ide?

hot wadi
#

That is not the link we pointed to…

meager siren
meager siren
#

im silly

#

anyways gnight

spiral summit
#

I have installed this extension, is this ide correct?

long scarab
#

Hi guys. Since I couldn't find shader channel, I ll post it here. Is it possible to do 2022.3.62f1 URP shader that occludes everything behind a plane except skybox? I never did shaders and forums & otherwise havent helped much.... Found some which made ghosting, so the skybox would make artifacts...

#

Or really any other way to hide something from both sides, so its not visible in either direction behind a plane. Does not have to be a shader.

timber tide
#

wouldn't everything behind a plane occlude anyway

#

or is this like some seethrough plane mask you mean that unrenders things behind it

long scarab
#

Transparent plane

#

so skybox is visible

#

Apologies for not specifying

timber tide
#

Only objects behind it?

long scarab
#

Yes

#

Yeah the use case is basically for a mod to a game where two side spawns shouldnt see each other for first X time.

#

so I thought about adding two planes in between and occluding everything but skybox/terrain etc

queen holly
#

im new to unity but i cant find out how to makea door. I have watched a few videos and none of them have seemed to work, would anyone be able to help?

long scarab
#

but the othe side needs to see the objects near them

#

hence why it must be invisible just for one side

#

and vice versa

timber tide
#

This discord server* doesn't really like to discuss modding unless specifically about your project, but you'll probably want to look into stencils and using this transparent plane to update the stencil buffer

long scarab
#

Doesnt stencil mean the materials on all the objs must be also adjusted?

timber tide
#

it means all objects you want to cull must be a buffer value of +1 (where 0 is default)

#

meaning the plane updates the buffer from 0 to 1

#

plane must be in opaque queue too

long scarab
#

Okay-ish 😄

#

I ll try to investigate thanks

#

Albeit also never using stencils 😄

timber tide
#

rather the objects should be 0, if you made them 1 then it would be a reveal shader, but rather you increment it to 1 from the plane meaning all further pixels behind must be 1 or they wont render. I forget if this causes problems with the skybox though hmm

#

alternativley you can just write to depth but not draw... but I think this wouldn't draw the skybox either

#

if the stencil idea doesnt draw the skybox it means you should render the skybox twice for both buffer value 1 and 0

#

anyway, complicated stuff

long scarab
long scarab
#

it would take me ages to do probably 😄

timber tide
#

I mean, stencils are more difficult in concept

#

you have the tools already available

long scarab
#

Well, thank you for pointing me in the right direction!

kindred dome
#

if ive got a script that says

private Renderer renderer = null;

void Start()
{
    renderer = GetComponent<Renderer>();  
}``` does it matter if i leave renderer unassigned or assign it null?
#

im guessing it probably doesnt matter

timber tide
#

that's fine

#

I would use awake though for when you're doing initial component referencing

shell sorrel
thorn crescent
thorn crescent
queen holly
#

alr thanks

grand snow
#

Valve put in lots of effort for the doors in HL a

thorn crescent
grand snow
timber tide
#

DukeNukem 3D doors would sometimes insta kill you

#

if geometry moved, it most likely was able to kill you

grand snow
#

There is a special door in half life 1 that gives you health!

shell sorrel
grand snow
shell sorrel
#

but yeah one of the old projects i been on, and stupidly complex doors

granite wharf
#

does anyone know how to make a square hold an item and then have it rotate towards the mouse like in dani's video? the closest i can get is making the whole square rotate but not the item by itself

thorn crescent
granite wharf
slender nymph
#

the transform will always rotate around the pivot

granite wharf
slender nymph
#

sprite editor

granite wharf
#

the blue circle thing?

grand snow
#

You can use the preset options or use a custom pivot

crimson dirge
grand snow
#

You are mixing the old and new input system which is already a bad sign

#

can you also expand the Events to show you set those up correctly?

#

@crimson dirge ^

crimson dirge
grand snow
#

Or change what Behaviour is

crimson dirge
#

I believe this happened in the process of trying to replace the player script, which i might have failed due to this

grand snow
blissful stratus
rough granite
blissful stratus
lunar coral
eternal needle
lunar coral
eternal needle
#

Id really just assume its a problem with the collider, though cant see the outline in these videos. You could just use box colliders for this though instead of mesh colliders

lunar coral
lunar coral
#

it works with box collider @eternal needle thank you so much

#

weird that it wasn't working with the mesh collider

eternal needle
knotty river
#

i forgot where the PP layer is

eternal needle
knotty river
#

oh yah

lunar coral
formal sleet
#

InputActionMap with path 'UI' in asset "" could not be found. The Input System's runtime UI integration relies on certain required input action definitions, some of which are missing. This means some runtime UI input may not work correctly. See Input System Manual - UI Support for guidance on required actions for UI integration or see how to revert to defaults.
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()

how to add UI to actionmap fast?

#

i cant play the game without add this?

light star
#

Hey, Im starting to learn coding in unity and I was wonderign about this sample code:
Is tooltip a custom function, or a comment? It has information that would be more helpful for a programmer than a user, but i thought comments were made with //.

sour fulcrum
#

tooltips show up when you mouse over those fields in the inspector

#

so it's kind of like an engine comment yeah

light star
sour fulcrum
#

Both! It's a function defined in another script built into unity 😛

The syntax of [SomethingRather] above a class, function, field etc. is called an Attribute, It's a C# feature Unity uses in a couple places

#

In this case, When you select your WeaponController instance in the editor, when Unity runs its code to show you it's current values in the inspector it will look for those kinds of attributes and if they exist, use that data to best render those values for you

polar acorn
light star
#

alr, thank you !

#

Is there an easy way to check in my project, where a variable is referenced?

sour fulcrum
#

In visual studio you can right click the variable name and click find references

fiery canopy
#

If it is a property, there is a small text that says references above it too

grand snow
#

(if this feature is enabled in visual studio)

#

Most IDEs have a way to find references of some variable or type

light star
sour fulcrum
#

Well it doesn't search your Unity project because we're talking about a variable, It just looks through all your project's scripts

wispy bison
#

Can someone help me? Why don't these red images scale properly with their parent object when I change the viewport size?

From my understand, I'm using the Vertical Layout Group and Content Size Fitter properly

wintry quarry
grand snow
wintry quarry
wispy bison
#

Doing that stretches them all the way to the edges

#

I just want them to be in the center

grand snow
#

what do you actually want them to do 😆

#

you need to describe it better in some way

wispy bison
#

To look like this

#

At all viewport sizes

#

And when I add more, they'll stay in the center

grand snow
#

thats too vague

#

how are the anchors set for the white box parent?

#

If you want padding on the left and right of the red elements then set the padding values on the layout group

wispy bison
#

The anshors on the parents are just at the edges

grand snow
#

That means the white box and thus the red elements will resize width and height as the screen changes size

wispy bison
#

So I added the padding which helps with the horizontal space, but the vertical space gets weird at some sizes. And if I check "control child size" the boxes just disappear

grand snow
#

when control width/height is OFF then the width and height set on each child rect transform is used

#

otherwise when control is enabled it will force expand width/height if enabled OR use settings from a layout element component

wispy bison
#

Thank you, I'll look into this layout element component

grand snow
wispy bison
#

I'm just having a hard time because every UI element I make scales correctly except these red boxes

#

Every time I change my window size, they change size

#

Only solution I can think of is to switch to a specific resolution

grand snow
#

Its just because you miss understand whats happening rn. The parents anchors make the parent size change but the layout group children by default will just keep their width and height defined on their rect transforms

#

you can enable child width/height control and disable force expand so it will downsize when they would "stick out"

#

you can play around with it all in editor to see

blissful stratus
#

guys when i start the game it makes me facing right even if i am mooving left this the code

void animationState()
{
if (movement.magnitude > 0.1f || movement.magnitude < -0.1f)
{
mooving = true;
}
else
{
mooving = false;
}
if (mooving)
{
anim.SetFloat("X", movement.x);
anim.SetFloat("Y", movement.y);
}
anim.SetBool("Moving", mooving);

if(movement.x < 0 && isFacingRight)
{
    transform.localScale = new Vector3(-1, transform.localScale.y, transform.localScale.z);
    isFacingRight = !isFacingRight;
}
else if(movement.x > 0 && !isFacingRight)
{
    transform.localScale = new Vector3(1, transform.localScale.y , transform.localScale.z);
    isFacingRight = !isFacingRight;
}

if(movement.y > 0 && !isFacingUp)
{
    swordSP.sortingOrder = 0;
    isFacingUp = !isFacingUp;
}
else if (movement.y < 0 && isFacingUp)
{
    swordSP.sortingOrder = 2;
    isFacingUp = !isFacingUp;
}

}

radiant voidBOT
wispy bison
grand snow
wispy bison
#

Yea, seemed like I was doing everything wrong, but once I found this setting it just works

#

Not sure why it's not on by default, my god

earnest patio
#

idk why unity is yelling at me about object reference not set an instance of object.

for my player i have:

public static playerMovement instance;
//Update to player branch
private void Awake()
{
    origSize = transform.localScale;
    body = GetComponent<Rigidbody2D>();
    boxCollider = GetComponent<BoxCollider2D>();

    if (instance != null && instance != this)
    {
        Destroy(gameObject);
    }
    else 
    { 
        instance = this;
    }
}

for my enemy base class i have:

protected virtual void Awake()
{
    rb = GetComponent<Rigidbody2D>();
    player = playerMovement.instance;
}

for my lizard enemy i have:

protected override void Update()
{
    base.Update();
    if (!isRecoiling)
    {
        transform.position = Vector2.MoveTowards(transform.position, new Vector2(player.transform.position.x, player.transform.position.y), speed * Time.deltaTime);
    }
}
#

so like the player is a singleton, why is it not letting me access it

#

enemy base is mono behaviour, player is too. lizard inherits from enemy base

sour fulcrum
#

enemy awake probably is running before player awake

earnest patio
#

how would i fix that?

tight oak
#

Stupidly simple question I'm just having a hard time finding the documentation for the UI Toolkit and style-sheets: how would I go about making my button-hover scale ONLY on the x axis? Like when I hover the mouse over it the button gets wider?

tight oak
#

Oops- thank you! I shall scoot over there sadok

sour fulcrum
# earnest patio how would i fix that?

could move from awake to start
could manually make player earlier than everything else in Project Settings => Script Execution Order
could reference the singleton directly instead of caching it

earnest patio
#

could you help me with the 3rd option

#

how would i go about referencing it directly

#

not exactlhy sure what caching it means here

sour fulcrum
#

(you already do that when you cache it in awake)

#

caching is saving the reference for later so you don't have to do the work every time (if there is work to be done)

earnest patio
#

oh so i could just use playerMovement directly

#

still giving me an error

#

i honstly dont know how i got this error. what i did worked perfectly some time ago

earnest patio
#

can anyone help me with my player, base enemy, and enemy code? i cant seem to get my enemy to reference my player despite the player being declared as a singleton

polar acorn
radiant voidBOT
languid pagoda
#

where does unity load that list of dlls from when you try to add a precompiled reference to an assembly definition file?

teal viper
#

Could maybe run a project wide search in vs code or something

languid pagoda
teal viper
languid pagoda
#

where does unity build the asmdefs out to any clue?

#

i bet i can find them there

teal viper
#

The player and editor ones are probably in the library somewhere

#

Searching for one of the names in vs code or similar text editor tool, might find you a file that has the mapping of name to path.

#

But it could also be working on the basis of include paths, so the editor searches through the include paths for these names and doesn't have an explicit mapping anywhere. This is very common in build systems.

hybrid cobalt
#

In Godot, Search Help and documentation was amazing. I could just look up what I wanted to do and it would explain clearly what something does, all the properties, functions, etc.

In Unity, I'm meant to use the Unity Documentation Website the same way, right? (and, is there a dark mode version?)

cosmic dagger
mighty prairie
spiral summit
#

I can't enter play mode

hot wadi
knotty river
#

hey i have a bug

#

i dont know how it categorize

#

but whenever i have buttons and put an animator on it, it gets automically bigger

spiral summit
#

it says some name is wrong but i don't understand why

cosmic dagger
ivory bobcat
hot wadi
#

I already told him earlier 🤦

astral flame
spiral summit
#

just one code with instructions but i made so many mistakes i am really frustrated

#

every error keeps happening

astral void
#

Hey y'all, I'm trying to make my variable set privately in only the same class but gettable in any class. so I thought solution would be to make a property? but it doesn't seem to work. here is an example.

 public Bounds TestArea { get; private set; }
    private void TestFunction()
    {
        TestArea.center = new Vector3(4, 0, 0);
    }

I would like to edit the value of TestArea.center, but I cannot.
I have looked at the error message.
"Cannot modify the return value of 'GridManager.TestArea' because it is not a variable"
It seems odd but I guess I cannot change TestArea in parts (like one field in it), only all at once.
Here I have an alternative that seems to work to avoid this issue

 public Bounds TestArea { get; private set; }
    private void TestFunction()
    {
        Bounds newArea = TestArea;
        newArea.center = new Vector3(4, 0, 0);
        TestArea = newArea;
    }

but I'm not a fan. I think I've found a solution to the issue but it feels messy and unnecessary. Is there something that just lets the first example work? or a nicer solution? I'm very new to properties so there's a lot I'm probably missing. I would just like advice or any suggestions of how to do this differently if possible.

I am aware of the alternative of making a private field and then getter methods to get them in other classes, but this is my attempt at an alternative to that because I don't like it much :p feels even messier tbh

naive pawn
astral void
#

god damnit
ok and what is a value-typed property?

naive pawn
#

give me a sec, there's a page explaining this that im trying to find

eternal needle
#

Am too lazy to apply the formatting on mobile.
You just modify testArea in the script and other scripts get the value through TestArea

naive pawn
naive pawn
#

there are 2 kinds of types in c#, value types and reference types. these effect how they're stored and how they're copied/referenced
you can look up those terms to learn more

by "value-typed property", i just mean a property that has a value type

astral void
#

...that site looks very useful

#

bookmarking that ty

hot wadi
meager siren
#

heya agaain

#

how the hell do you add an inventory?

#
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class Inventory : MonoBehaviour
{
    [Header("Gameobjects")]
    [SerializeField] private RectTransform[] inventory;

    [Space]
    [Header("Positions")]
    [SerializeField] private Vector2 slot1TargetPosition = new Vector2(-50, 50); 
    [SerializeField] private Vector2 slot2TargetPosition = new Vector2(40, 40); 
    [SerializeField] private Vector2 slot3TargetPosition = new Vector2(50, -50); 
    [SerializeField] private Vector2 slotStartPosition = new Vector2(-55, -55);
    
    [Space]
    [Header("Other Variables")] 
    [SerializeField] private float speed = 2500f;
    [SerializeField] private bool isAnimating = false;
    [SerializeField] private bool isOpened = false;

    public void InventoryPosCheck(InputAction.CallbackContext context)
    {
        if (context.phase == InputActionPhase.Started && !isAnimating)
        {
            if (!isOpened)
            {
                StartCoroutine(MoveSlots(slot1TargetPosition, slot2TargetPosition, slot3TargetPosition));
                isOpened = true; 
            }
            else
            {
                StartCoroutine(MoveSlots(slotStartPosition, slotStartPosition, slotStartPosition));
                isOpened = false;
            }
        }
    }

    IEnumerator MoveSlots(Vector2 targetPosition1, Vector2 targetPosition2, Vector2 targetPosition3)
    {
        isAnimating = true;

        Vector2 endPosition1 = targetPosition1;
        Vector2 endPosition2 = targetPosition2;
        Vector2 endPosition3 = targetPosition3;
        
        const float STOPPING_DISTANCE = 1.0f; 

        while (Vector2.Distance(inventory[0].anchoredPosition, endPosition1) > STOPPING_DISTANCE ||
               Vector2.Distance(inventory[1].anchoredPosition, endPosition2) > STOPPING_DISTANCE ||
               Vector2.Distance(inventory[2].anchoredPosition, endPosition3) > STOPPING_DISTANCE)
        {

            Vector2 slot1CurrentPosition = inventory[0].anchoredPosition;
            Vector2 slot2CurrentPosition = inventory[1].anchoredPosition;
            Vector2 slot3CurrentPosition = inventory[2].anchoredPosition;
            
            slot1CurrentPosition = Vector2.MoveTowards(slot1CurrentPosition, endPosition1, speed * Time.deltaTime);
            slot2CurrentPosition = Vector2.MoveTowards(slot2CurrentPosition, endPosition2, speed * Time.deltaTime);
            slot3CurrentPosition = Vector2.MoveTowards(slot3CurrentPosition, endPosition3, speed * Time.deltaTime);

            inventory[0].anchoredPosition = slot1CurrentPosition;
            inventory[1].anchoredPosition = slot2CurrentPosition;
            inventory[2].anchoredPosition = slot3CurrentPosition;
            
            yield return null;
        }

        inventory[0].anchoredPosition = endPosition1;
        inventory[1].anchoredPosition = endPosition2;
        inventory[2].anchoredPosition = endPosition3;

        isAnimating = false;
    }
}

That alligns with my current script.

#

I genuinely do not know how to make an inventory script but I know it has something to do with scriptable objects

teal viper
meager siren
#

can you give me an example

#

like of code

teal viper
#

private Item[] basicInventory;

meager siren
#

touche

#

and Im guessing if I pick something up you delete the object and store the data in the dictionary?

teal viper
#

Basically, yes. In the case above it's not a dict, but an array, though.

meager siren
balmy vortex
#

I'm trying to make it just move the player to the empty game objects position on the other side of the map but clearly I'm stupid or something

frail hawk
#

it could be because the object is a parented object and there is an offset

knotty river
#

hey guys

#

i have a problem

#

in this video are a lot of bugs

#

like there are 4 UI components one for health, one for the time one for cooldown fo the dash abilty and one of the score being the number of enemy killed

#

then the enemies, their bullets dont work as expected

#

then the buttons i have a button animation that when applied makes the button bigger than wanted

#

in other words this has a load of bugs

#

should i restart from zero or is this still savable ?

eager spindle
#

its important to learn how to salvage a project you think is broken

knotty river
#

so how can i salvage it, its a burning pile of trash that if i change a singular line of script the whole game breaks

eager spindle
#

you're gonna be doing that a lot in any software engineering job

eager spindle
knotty river
#

it doesnt fully get out

#

it should go towards the enemy

humble grove
#

hi guys, i wanna make a sticking throwable knives and make them move with sticked objects. Currently using setParent but it make weird visuals when add my knife as child to not 1,1,1 object. Anyone can help me about that issue? Code: https://paste.mod.gg/rkywnqmbijnw/0

knotty river
#

but as a you can hear when the bullet spawns it stays in the enemy

eager spindle
# knotty river it doesnt fully get out

When you spawn a bullet, I assume you're setting the velocity of the bullet to enemy's position minus the player's position. The concept is right, but you also need to consider that the enemy is moving.

Think of it this way; when you're running and throw a ball, the ball's speed = the speed you're running at + the speed that you throw the ball.

You need to set the bullet's velocity to the speed of the enemy + the speed of the bullet.

knotty river
#

ok

#

but what about the UI

#

the buttons

#

or the fact that when i try to set up a game over system it doesnt work

eager spindle
knotty river
eager spindle
#

Hmm what's wrong with the animation then?

knotty river
#

the button size gets WAY bigger no matter what happens

knotty river
#

maybe

#

i need to take a break

#

i already made two games this monthy

#

maybe in late december i will do it

frail hawk
#

just take a small break

#

it helps sometimes

tired junco
#

hey i'm having a bit of a struggle with the unity input system: when unity reloads scripts at runtime it obviously resets all the references set in awake my question is: do i have to set the references that i set in Awake in OnEnable again - since something inside me tells me that this can't be how its being done - even tough it does work then. (and please ignore the unused method) https://pastebin.com/xEK9MSh3

frail hawk
#

make sure you only have one Instance

#

also you are assigning the object 2 times, in Awake and OnEnable

tired junco
#

but isn't that the case here - only having one instance

frail hawk
#

it is, but you are not checking if Instance is null, otherwise you are overriding it

tired junco
#

ur right but this did not rly answer my question - do i need to reset it when unity recompiles the scripts

frail hawk
#

i dont think that this is required

astral void
#

What the difference between polymorphism and interfaces? They seem very similar to me

glad dagger
#

pls help cuz i dont understand the issue

blissful stratus
#

what is this?

grand snow
radiant voidBOT
# grand snow !input ⬇️
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

grand snow
#

you are using the Input class which is for the OLD input manager

glad dagger
blissful stratus
#

can some one help please

frail hawk
#

did you try a unity restart

blissful stratus
frail hawk
#

yeah just ignore it , it is a warning not an error on your side, seems like some internal bug

blissful stratus
blissful stratus
frail hawk
#

hide the console then

#

what render pipeline is that

blissful stratus
frail hawk
#

unity version?

blissful stratus
#

6000

#

.1.8f1

blissful stratus
frail hawk
#

or google for the warning message you ´ll find something in the forums

tired python
#

umm, what would you do differently?

blissful stratus
frail hawk
tired python
#

wait what the actual mess did i concoct then

tired python
frail hawk
#

kind of you are mixing sprite renderer and ui elements

astral cedar
#

alright thank you

hot wadi
astral cedar
#

im gonna delete this

frail hawk
#

ty

humble summit
#

hello i have this script here and it's very simple. it should on collision destroy the gameobject it collided with, if its called "player"

#

i have a collider on both the sphere and the "player" being collided

#

and the sphere has a rigibody

#

i launch the game and it when it collides nothing happens. no logs no nothing even

frail hawk
#

did you assign the Tag to the Player

#

do you have cooliders on both objects and at least one rigidbody

humble summit
frail hawk
#

in the inspector of your player top right

humble summit
#

🙏

frail hawk
#

you are welcome

humble summit
frail hawk
#

nothing to worry about if you are new to unity

glad dagger
#

can somebody help me not get instantly private void start

#

like this

radiant voidBOT
glad dagger
#

stupid

grand snow
#

i question why you want Start() to not be private automatically

#

unity monobehaviour messages should ideally be private so you dont call them externally

hot wadi
#

That too

#

Idk what u expect from auto-complete

glad dagger
#

cuz the tutorial shows not private

sour fulcrum
#

Tutorials wrong then

hot wadi
#

Instead of following tutorial blindy, take a second to question the purpose of each step

glad dagger
#

plus idk why my character doesnt move too

#

heres my script for fp controller

#

and this is for player for now

hot wadi
#

Ok, does the console show any red error?

#

Because I see a red underline right there

glad dagger
#

oh i fixed it

#

but it doesnt show any

grand snow
glad dagger
hot wadi
#

Btw u can just remove the namespace keyword

glad dagger
#

ye just used to using it when im on c++

#

in school

#

so would it move like my character

#

and look

#

like the handling input i think is the problem

hot wadi
#

Are u using PlayerInput "Send Messages" mode?

glad dagger
#

nah any

hot wadi
#

I mean this

glad dagger
glad dagger
hot wadi
#

Your callbacks have to be exactly like what the component generated for u
OnMove, OnLook

glad dagger
#

but where ?

wintry quarry
#

Wdym by "where"?

#

In your code.

wintry quarry
# glad dagger

Look at your code right now. You have onmove, for example

#

that's not correct

glad dagger
wintry quarry
#

You don't have any what?

glad dagger
#

onmove

wintry quarry
#

yes you do

wintry quarry
#

it's right there

glad dagger
polar acorn
# glad dagger onmove

You should consider actually checking before saying you don't have something in your code

pliant dome
#

if I wanted to make an airdash to not occur on the first few frames on a jump, would I have to turn my jump into a coroutine so that I can use WaitForSeconds ?

wintry quarry
pliant dome
#

Hmm okay Ill make a seperate one then and see what I can do

hot wadi
#

Tried something similar. Gotta say coroutine is way more complicated with physics steps

vast talon
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Parts")]
    public Rigidbody rb;
    public Transform playerTransform;
    public Transform camTransform;

    [Header("Constants")]
    public float movementSpeed = 100f;
    public float jumpForce = 250f;
    public float offset_x = 10f;
    public float offset_y = 5f;

    void FixedUpdate()
    {
        // Main movingness

        rb.AddForce(0, 0, movementSpeed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce * Time.deltaTime, 0);
        }

        var camPosition = camTransform.transform.position;
        var playerPos = playerTransform.transform.position;

        camPosition = new Vector3(playerPos.x + offset_x, playerPos.y += offset_y, 0);

    }
}
``` My camera is still fixed to its original position and its not changing it to match the players with the offset why isnt it working
wintry quarry
hot wadi
wintry quarry
#

All you're doing is modifying your local Vector3 variable camPosition

#

by the way, doing camera movement in FixedUpdate is a guaranteed way to make your game look "jittery"

vast talon
#

well that makes sense im a bit of a dumbass sorry

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Parts")]
    public Rigidbody rb;
    public Transform playerTransform;
    public Transform camTransform;

    [Header("Constants")]
    public float movementSpeed = 100f;
    public float jumpForce = 250f;
    public float offset_x = 10f;
    public float offset_y = 5f;

    void Update()
    {
        // Main movingness

        rb.AddForce(0, 0, movementSpeed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce * Time.deltaTime, 0);
        }

        var playerPos = playerTransform.transform.position;

        camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
    }
}
``` Ok so i tried to change it up a little it still dont work buh.
#

its been a long time from unity dont blame me

wintry quarry
wintry quarry
#

And I'll jump ahead a bit here - you can't do Input.GetKeyDown in FixedUpdate either 😛

#

Realistically the camera stuff should move to an entirely different script

#

And the movement code is going to need to be broken up between Update and FixedUpdate with variables to share information between

maiden cliff
#

!code

radiant voidBOT
maiden cliff
#
     if (AmmoManager.Instance.ammoDisplay != null)
        {
            AmmoManager.Instance.ammoDisplay.text = $"{bulletsLeft / bulletsPerBurst}/{magazineSize/bulletsPerBurst}";
        }
#

im following a tutorial so this may be a dumb question but its telling me the code does not contain a definition for "instance", however thats exactly what the guy the video did and it worked for him. can someone help?

ivory bobcat
#

Maybe show the console error

wintry quarry
maiden cliff
#

Assets\GunShoot.cs(80,25): error CS0117: 'AmmoManager' does not contain a definition for 'Instance'

wintry quarry
#

Because in your code you have Instance here, but if there's an error talking about instance sounds like you miscapitalized it somewhere

maiden cliff
#

ah ok ill check rq

wintry quarry
#

you never defined Instance in AmmoManager

hot wadi
#

U have to define ‘public static AmmoManager Instance’

#

It’s a singleton

wintry quarry
#

it may be a property too - just double check what the tutorial did in AmmoManager

maiden cliff
#

i found what i did, i had two spaces in between the words AmmoManager and Instance, it works now thanks

ivory bobcat
#

White space doesn't matter. Likely misspelling.

#

Or the script hadn't been saved etc

tired python
#

why doesn't this print the mouse_pos O_O

rough granite
tired python
#

oh wait no

rough granite
#

well that would suggest OnClick() isn't called lol

tired python
#

didn't set it up apparently

grand snow
#

why update the mouse world pos each frame?

#

or is this just testing. Looks like you are heading in the right direction

tired python
#

i am trying to create a draggable sprite when i click on the droplet button thingy. i have the sprite attached to the script, but problem is, OnClick() gets called only when i am pressing it once, i wanna be able to update the sprite image to my current mouse position until i stop clicking on it

#

like this

rich adder
#

why not just use the event system interface if it's UI

grand snow
#

Remember what i explained. you will need to respond to a drag event and spawn the real object and make it follow the cursor

tired python
#

ahh the dreaded ui system

grand snow
#

the UI element should remain in place

tired python
#

i am only drawing a sprite at mouse position

vast talon
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Parts")]
    public Rigidbody rb;
    public Transform playerTransform;
    public Transform camTransform;

    [Header("Constants")]
    public float movementSpeed = 100f;
    public float jumpForce = 250f;
    public float offset_x = 10f;
    public float offset_y = 5f;

    // Main movingness
    void FixedUpdate()
    {
        rb.AddForce(0, 0, movementSpeed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce * Time.deltaTime, 0);
        }
    }

    private void LateUpdate()
    {
        var playerPos = playerTransform.transform.position;

        camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);
    }
}
``` I rewrote the code noesnt work still (the camera doesnt follow the player)
rich adder
#

Just use cinemachine lol
No code needed

grand snow
ivory bobcat
grand snow
#

You do not want a Button component to do this work

vast talon
rich adder
#

Also should not use time.deltaTime in add force its already moved on fixed physics tick

grand snow
ivory bobcat
vast talon
ivory bobcat
ivory bobcat
#

Preferably the position of the player etc

#

If anything, you may have referenced the wrong object (a prefab perhaps)

vast talon
#

and the positions

ivory bobcat
#

Did anything print in the console?

vast talon
#

yup

#

everything

ivory bobcat
#

Were the values correct?

vast talon
#

yessum

#

i have no idea

rough granite
#

what did you log and where?

#

also is there anything else that'd affect the camera position?

vast talon
vast talon
#

all of these should help

wintry quarry
#

My friend

#

something is going horribly wrong here

glad dagger
#

guys idk what to do after getting the movement down

wintry quarry
#

anyway from your logs it's clear the camera is, in fact, moving

glad dagger
#

like double jump and run

#

and walk

tired python
#

demn, camera into the stratosphere

wintry quarry
#

the player is in the Andromeda galaxy

rough granite
bleak kernel
#

Hi, i just downloaded Unitiy. Has anyone a suggestion for a guide or a tutorial on how to code in Unity? And maybe an idea for a project which is simpel? (I have adhd so I need things that dont take too much time 🙁 )

radiant voidBOT
bleak kernel
vast talon
rough granite
#

not sure that would fix this though just bugged me

glad dagger
#

what should i do cuz i did this rn double jump and run and walk look around

#

im new to this

tired python
#

guys i am having problems implementing a delegate all over again...this

#
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class buttonScript : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    [SerializeField] private Button button = null;
    [SerializeField] GameObjectHolder objectHolder;
    [SerializeField] spriteRender soritToRender;
    Vector2 mouse_pos;

    // Update is called once per frame
    private void Start()
    {
        
    }
    void Update()
    {
        mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
    }
    public void OnClick()
    {
        Debug.Log("Button was clicked.");
        Debug.Log($"{mouse_pos.x}");
    }
    void OnDrag(PointerEventData eventData)
    {

    }
}```
wintry quarry
#

You need:

public class buttonScript : MonoBehaviour, IDragHandler```
#

(P.S., the convention for class names is PascalCase, so ButtonScript)

#

Also there aren't really any delegates in this code

tired python
rough granite
tired python
wintry quarry
wintry quarry
tired python
#

ahhh shiiii

ivory bobcat
# vast talon player moves, the camera doesnt.

So just for clarity, the camera's x and y values are properly updating whereas you've got its z value set to zero. The camera should be following the player relative to x and y unless... you're moving sometime else.

vast talon
#

The player moves perfectly

#

I checked its transform its fine

#

The camera dont move

#

At all

#

I think my codes autistic

ivory bobcat
ivory bobcat
# vast talon The camera dont move

The object is moving according to the logs. Concern would be if it's your actual camera. Another concern would be if you've got constraints with the camera.

tired python
wintry quarry
tired python
sour fulcrum
#

(You also might be combining the terms event,delegate and the concept of events together)

wintry quarry
tired python
wintry quarry
#

The only thing special about an event is that it can only be invoked by the class that declared it

#

otherwise it's identical to all other delegates

#

there are no special rules about how it is called

tired python
#

oh wait

wintry quarry
#

some code must simply invoke it

tired python
#

so like....a is basically a list which holds functions and when you call a, you call all the functions present inside a

wintry quarry
#

yeah, sort of

tired python
#

what's Action type?

#

or is it a data type

wintry quarry
#

just a delegate type - it means a function that returns void and has no parameters

tired python
#

or a modifier

wintry quarry
#

delegate types describe the "shape" of the functions that can fit in the variable

#

Action is any function with void return type and no parameters.
So:

void Hello() {}```is an action but:
```cs
int Blah() { return 5; }``` is not
#

You can also do like Action<int> which would be any function that returns void and has a single int parameter'

#

e.g.

void Goober(int x) { print(x); }``` that would fit in `Action<int>`
tired python
#

aight, another question, how do you begin to decipher this? as in, for you guys, looking at this makes you understand exactly how you can use it, to me, it just seems to be unrelated stuff.

grand snow
sour fulcrum
#

So first of all, the second screenshot is called an Interface, hence the naming convention of it starting with I

#

Are you familiar/comfortable with inheritance currently?

tired python
#

as in, you can only inherit one type, but you can inherit multiple interfaces

sour fulcrum
#

ok so you get how inheritence works with normal classes then

tired python
#

you can inherit the parent class's methods and stuff

sour fulcrum
#

interfaces are like a primitive version of inheritance where the Interface defines what the deriving thing will have, like a promise

#

then when some code has a reference to the interface (eg. IDragHandler), it can call those promised functions knowing whatever the interface actually is has some implementation of those promises

#

Interfaces exist because very different things can share similar behavior

#

here's a cursed example

#
public interface IPromiseToKillMyselfOnRequest
{
    public void Die();
}

public class Car : IPromiseToKillMyselfOnRequest
{
    public void Die()
    {
        Explode();
    }

    private void Explode()
    {

    }
}

public class Human : IPromiseToKillMyselfOnRequest
{
    public void Die()
    {
        HaveHeartAttack();
    }

    private void HaveHeartAttack()
    {

    }
}
#

a Car and a Human are very different things, but both share the idea that they could "Die" in some shape or form

#

they have very different interpretations of what that means, as you can see

tired python
#

demn, it turned rly morbid all of a sudden

sour fulcrum
#

i've been up awhile forgive me

#

anyway, going off that

#

lets say we have this

public class WorldManager
{
    public List<IPromiseToKillMyselfOnRequest> AllKillables = new List<IPromiseToKillMyselfOnRequest>();

    public void KillEverything()
    {
        foreach (IPromiseToKillMyselfOnRequest killable in AllKillables)
            killable.Die();
    }
}
#

this WorldManager does not need to know if something is a Human or a Car or whatever, that's not it's job to know

tired python
#

👀

#

aig-ehm....aight

sour fulcrum
#

but because of the promised Die() function in the interface, it can call that on all of them knowing that whatever has implemented that Interface, has provided some sort of answer for that function

#

so going back to your draghandler

unkempt tundra
#

hey i have a question if i have a big scene with many objects rendering in the scene. instead if i converted all the fbx files to stl and made a mesh reader and render all the object dynamically would that be better in term of memory or performance?

sour fulcrum
#

you would implement that interface (eg. class ButtonScript : MonoBehaviour, IDragHandler) and provide an answer to that promised function OnDrag() and whatever Unity has to manage the dragging systems will call that for you when it finds it

blissful stratus
wintry quarry
#

shadows don't render past that distance

tired python
wintry quarry
#

It will get called by the game engine when you are dragging things.

#

not as part of Update though

#

Maybe you mean "every frame"?

tired python
#

so for every frame that i am dragging, it gets calles right

sour fulcrum
#

Update() is completely unrelated to this.

Unity has some way of finding all the things that implement IDragHandler that currently exist and will iterate through them and call that function when relevant

wintry quarry
tired python
#

and it does so outside of the update()?

sour fulcrum
#

update or frame

tired python
#

for every frame that i am dragging

wintry quarry
#

you can see this in the profiler

sour fulcrum
#

At most I think every frame yeah, but as mentioned in that doc every time the cursor is moved so on frames where you haven't moved the cursor and are still dragging it won't fire

#

Worth pointing out just in case that the frequency of when the OnDrag function is based just on how that specific interface was implemented in Unity, nothing fundamentally with interfaces as a concept defines when they will be called

tired python
#

it's an actual mystery the fact that unity can call the correct stuff inside every update method available across all the scripts in the right order

sour fulcrum
#

Once you get more comfortable with Unity you'll be even more weirded out with how Update, Start, Awake work etc.

#

it's certainly not standard / "good" practice

#

Also there is no "right" order btw, it just depends on how your code is setup for if it will or will not be affected by a "bad" order

glad dagger
#

i finished my double jump mechanic but when i double jump and then go a bit down i can double jump again what should i do to fix it

tired python
#

got it working, now what is the difference between this and what the drag handler is doing?

#

why doesn't it call onComplete() by itself

sour fulcrum
rough granite
glad dagger
tired python
sour fulcrum
#

i woke up at 11pm and it's 8am now 😭

rough granite
tired python
radiant voidBOT
#

success @gus_fring__ muted

Reason: Sending too many attachments.
Duration: 29 minutes and 54 seconds

rough granite
#

!code

radiant voidBOT
sour fulcrum
#

for that first one though, they are both two different ways of achieving the same outcome yeah.

This is a super rough "idea" of what Unity is doing but with the interfaces Unity might be doing something like

private void EventHandler : MonoBehaviour
{
  private List<IDragHandler> activeDragHandlers; //They collect these using some kinda magic dw about it
  private Vector2 lastMousePos;

  private void Update()
  {
    //They might even use some event from the new input system stuff instead of this update check
    if (Mouse.current.position != lastMousePos)
    {
      lastMousePos = Mouse.current.position;
      foreach (IDragHandler handler in activeDragHandlers)
        handler.OnDrag()
    }
  }
pliant dome
#

https://paste.ofcode.org/d3PmZAcQMdUKTiHnptqx3c In the coroutine I set up so that I can airdash but I noticed that when I airdash I angle ever so slightly downwards so Im assuming that gravity is having some influence over my airdash when Im trying to go exactly straight

keen dew
#

You have to disable the rigidbody's gravity for the duration

wintry quarry
pliant dome
#

isnt gravityscale a unity 2d thing?

wintry quarry
#

useGravity or something

#

it's on the Rigidbody

keen dew
#

Unrelated but StopCoroutine(AirDash()); doesn't do anything. You have to save the reference to the coroutine when starting it and then use the reference to stop it

wintry quarry
#

I was just gonna mention that haha

pliant dome
#

Oh okay I made multiple changes when I added that and assumed that was the reason

#

that made my airdash work

keen dew
#

It's a bit of a mess, that made it "work" only because it didn't stop the coroutine immediately

timber mesa
#

Can someone help me understand why I keep getting an "Unauthorized" log when it comes to this function

[CloudCodeFunction("SavePlayerData")]
    public async void SavePlayerData(
        IExecutionContext context,
        IGameApiClient gameApiClient
    ) {
        try {
            await gameApiClient.CloudSaveData.SetProtectedItemBatchAsync(
                context,
                context.AccessToken,
                context.ProjectId,
                context.PlayerId!,
                new SetItemBatchBody(new List<SetItemBody> {
                    new SetItemBody("test", 1),
                    new SetItemBody("test2", 2),
                    new SetItemBody("test3", 3),
                    new SetItemBody("test4", 4)
                })
            );
        }
        catch (ApiException e) {
            _logger.LogError($"Failed to save PlayerData: {e.Message}");
        }
    }
glad dagger
#

Was making movement added double jump its bow infinite pls help km new at this

wintry quarry
#

presumably you tried to save data to a project id or player id that you don't have permissions for

#

or maybe the access token itself is bad

timber mesa
#

Could it have something to do with the fact that I'm testing it in play mode? So I'm signing in anonymously and could not have a player id?

#

Because the function is on CloudCode, it should have access to everything

wintry quarry
#

Now would be a good time to start debugging

#

print your access token, project id, and player id

timber mesa
#

all are not-null

wintry quarry
#

are they even nullable types? It's not about if they're null

#

it's if they're valid and sensical

timber mesa
#

Yeah they're valid, I probably shouldnt send a ss of them right?

wintry quarry
#

The server is clearly telling you that you're not authorized to do what you're trying to do

#

see if there is any other data in the exception

#

there should be a message

timber mesa
#

this is all it says

wintry quarry
#

what api is this

timber mesa
wintry quarry
#

you're using accessToken

#

is that the issue?

#

I would certainly expect an unauthorized error if you're using the wrong token

timber mesa
#

Some use AccessToken some use ServiceToken apparently, I guess I can try with service token

wintry quarry
timber mesa
#

ok so it was because I needed to use the ServiceToken

#

Thank you for the help

lament linden
#

can someone give me tips to start coding in unity?

radiant voidBOT
lament linden
grave frost
#

Hey does unity not support .NET 5? For some reason I can't use IReadOnlySet even though it was added in .NET 5.

valid violet
#

only these supported: .NET Standard 2.1 .NET Framework 4.x

#

I used last dot net version on my server when I need .NET latest support and just communicate from game with server

mint mica
fickle plume
mint imp
#

Any one have advice how i might make make an object "float" around a sphere (a planet)
Im made a prototype using physics to "attract" the player to a specific radius around a planet and it work but breaks if you move too fast,
Are there other ways i could acheive this effect? like attaching to player to an empty game object and rotating it around the planet maybe?

wintry quarry
astral void
#

is there a way to call StartCoroutine in an abstract class? I'm seeing a lot of "no" and it ruins stuff ;-; basically I'm trying to run a function in a class that inherits from an abstract class, polymorphism stuff, and in that function i want to call a bunch of coroutines. I'm thinking I could switch to an interface instead of polymorphism and that might fix it but hoping for other solutions

wintry quarry
#

just note that StartCoroutine is a method on MonoBehaviour, so you, as always, need a reference to a MonoBehaviour instance to call it on

astral void
#

yes... but i get "An object reference is required for the non-static field, method, or property" error

#
public abstract class ActionClass
{
    public abstract void Activate();
}

public class NewAction : ActionClass
{
    public override void Activate()
    {
        MonoBehaviour.StartCoroutine(MatchManager.instance.ChangePhaseVisualRpc("phaseName"));
    }
}

example code, error here

wintry quarry
astral void
#

oh I read your message wrong oops

wintry quarry
#

you need an actual instance to call it on

astral void
#

yeah...

wintry quarry
#

it's not a static method

#

StartCoroutine(MatchManager.instance.ChangePhaseVisualRpc("phaseName"));
This is a code smell

#

is there a reason you don't just start the coroutine right there?

#

MatchManager.instance.StartChangingPhase("phaseName"):

astral void
#

because i want to yield return it (forgot to put that in oops)

wintry quarry
#

then on MatchManager:

public void StartChangingPhase(string phase) {
  StartCoroutine(ChangePhaseVisualRpc(phase));
}```
#

no, look

#

this is how you should do it^

#

and call this

#

MatchManager.instance.StartChangingPhase("phaseName");

astral void
#

I want to run a few coroutines and have them happen in order, I don't know how to do that with your method

wintry quarry
#

I just showed you

#

Use the MatchManager instance to run the coroutines

astral void
#

ok lemme edit it to better show what I mean

wintry quarry
#

MatchManager is a MonoBehaviour, right?

wintry quarry
#

just FYI

astral void
#
public abstract class ActionClass
{
    public abstract IEnumerator Activate();
}

public class NewAction : ActionClass
{
    public override IEnumerator Activate()
    {
        yield return StartCoroutine(FirstRoutine());
        yield return StartCoroutine(SecondRoutine());
        yield return StartCoroutine(ThirdRoutine());
        //function that called Activate will now continue their own code since this has finished
    }
}

this is more what I'm trying to do, I hope it's clear enough-

wintry quarry
#

Yes it's very clear, but you need a MonoBehaviour to run coroutines

astral void
#

ok yes yes

#

got that

wintry quarry
#

So - you need to create a dedicated monobehaviour for running the coroutines

#

and run them on that component

#

That could be your MatchManager if you want

#

or some other singleton

astral void
#

A big part of the ActionClass though is that it is called from MatchManager and then MatchManager waits for the coroutines to end... not sure how to make the code wait for the functions to end in that case... is there a way to pause a function like that?

wintry quarry
astral void
#

oh yes sorry

wintry quarry
#

then you have no problem

#

You start the coroutines from MatchManager

astral void
#

but I need to know when the coroutines are finished-

wintry quarry
#

you use a coroutine

#

show me an example of how and when you call Activate

astral void
#
 private IEnumerator ChangeAction()
    {
        yield return StartCoroutine(ActionOrder[CurrentActionIndex].Activate(new PhaseActionParams()));
        CurrentActionIndex++;
        CurrentActionIndex %= ActionOrder.Count;
    }

the code is incomplete and I plan to change this, but currently this is what I have

#

this is in MatchManager

wintry quarry
#

Ok so looks like you're already doing it in a coroutine

#

so there should be no issue

#

but Activate certainly needs to return IEnumerator for this to work

#

not void

wintry quarry
astral void
#

yeah like that

#

wait

wintry quarry
#

Instead of:

yield return StartCoroutine(FirstRoutine());```
You can just do:
```cs
yield return FirstRoutine();```
#

it works the same

astral void
#

so it won't move then until the coroutines in MatchManager is done?

wintry quarry
#

that's what yield return does

astral void
#

oh i didn't know that

wintry quarry
#

if you really needed to call StartCoroutine, you can always do MatchManager.Instance.StartCoroutine(...);

#

but it's not needed here

mint imp
wintry quarry
#

Perhaps like, hovering around a mario galaxy planet? It's tougher to do with Rigidbody

astral void
mint imp
#

I want to do it with a rigidbody because my game is expected to have many collisions.
but if its way easier to do without im all ears

timber mesa
#

2 questions. 1. is this efficient? 2. How would I be able to discern an actual string and a JSON serialized string?

public static async Task ModifyPlayerData<T>(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string key,
        Func<T?, T> modifier
    ) {
        string playerId = context.PlayerId!;
        try {
            var result = await gameApiClient.CloudSaveData.GetProtectedItemsAsync(
                context,
                context.AccessToken,
                context.ProjectId,
                playerId,
                new List<string> {key}
            );
            
            T? currentData = default(T);

            if (result.Data.Results.Count > 0) {
                object value = result.Data.Results.First().Value;
                if (value is string stringValue) {
                    currentData = JsonSerializer.Deserialize<T>(stringValue);
                } else {
                    currentData = (T) value;
                }
            }
            
            T newData = modifier(currentData);
            
            await gameApiClient.CloudSaveData.SetProtectedItemAsync(
                context,
                context.ServiceToken,
                context.ProjectId,
                playerId,
                new SetItemBody(key, newData!)
            );
        }
        catch (ApiException e) {
            _logger.LogError($"Failed to modify PlayerData: {e.Message}");
        }
    }
wintry quarry
#

Ok let me ask a different question actually, now that I read this a little

#

Why are you not sure if the data you're getting back is a json string or... something else?

#

are you expecting both things to come back?

timber mesa
#

Because CloudSave will serialize all objects on save, when getting, if the value can be deserialized into a .NET object, it will auto do that, otherwise it stays as a JSON serialized string

wintry quarry
#

Why would the value ever not be able to be deserialized

#

If it's not able to deserialize it, you can probably just give up, and spit out an error, no?

#

Presumably you should know the actual data type you expect to come back you call this I would think

timber mesa
#

Well if I ever had like a custom class/type that I wanted to be saved, it would be JSON serialized on save, but would not be auto deserialized on get

wintry quarry
#

would you ever be saving a raw string that wasn't json?

timber mesa
#

I mean, currently idk, I'm just still setting up the foundation before I dig into actual player data

#

I would like the option to be available if it ever arose. Maybe like DisplayName, that could be a string

wintry quarry
#

For any given key, you will know ahead of time the type of data or will be

#

It's a non issue

timber mesa
#

true, maybe I can just have the Function deal with deserializing and return object, so when saving back it will just serialize

wintry quarry
#

I kinda hate that the api is trying to serialize/deserialize for you

timber mesa
#

Well it has to serialize from what I understand, like you cant just store actual objects. It's like compression.
I did however change my code

#
public static async Task ModifyPlayerData<T>(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string key,
        Func<T?, dynamic> modifier
    ) {
        await ModifyPlayerData<T>(context, gameApiClient, key, modifier, false);
    }

    public static async Task ModifyPlayerData<T>(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string key,
        Func<T?, dynamic> modifier,
        bool deserialize
    ) {
        string playerId = context.PlayerId!;
        try {
            T? currentData = await GetPlayerData<T>(context, gameApiClient, key, deserialize);
            
            var newData = modifier(currentData);
            
            await SavePlayerData(context, gameApiClient, key, newData);
        }
        catch (ApiException e) {
            _logger.LogError($"Failed to modify PlayerData: {e.Message}");
        }
    }
wintry quarry
#

json

#

and expect you to serialize it yourself

#

that's what I mean

timber mesa
#

ohhh

wintry quarry
#

or even a byte[]

minor goblet
#

Did unity remove go language?

ivory bobcat
#

Unity uses C#

minor goblet
#

i meaaan...

keen dew
#

Unity has never had anything to do with Go

vast talon
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Parts")]
    public Rigidbody rb;
    public Transform playerTransform;
    public Transform camTransform;

    [Header("Constants")]
    public float movementSpeed = 100f;
    public float jumpForce = 250f;
    public float offset_x = 10f;
    public float offset_y = 5f;

    // Main movingness
    void FixedUpdate()
    {
        rb.AddForce(0, 0, movementSpeed);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce, 0);
        }
    }

    private void LateUpdate()
    {
        var playerPos = playerTransform.transform.position;

        camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y + offset_y, 0);

        Debug.Log("Camera position: " + camTransform.position);

        Debug.Log("Player Position: " + playerPos);
    }
}
``` Im trying to make the camera follow the player but it isnt working.the player is moving but the camera isnt can somebody help me with this its been a while since i was a dev on unity twin
tired python
#

halp pls

frail hawk
frail hawk
#

maybe somethig is prevent it from moving

#

and make sure you dont have any errors shown up in the console

vast talon
ivory bobcat
# vast talon ```using System.Collections; using System.Collections.Generic; using UnityEngine...

I think I've seen you here for a few days now. You might want to provide the screenshots that you've last had or a link to the latest discoveries. Last I recall, your coordinates were being updated (although extremely high in value) but supposedly the object (camera) wasn't moving. Either it's referring to a different object (main camera etc) or you've got some constraint that prohibits the camera from moving (physics constraint, Character Controller component, code or something other)

vast talon
#

dj giggle nuts signing off for now

tired python
#

dj jiggle nuts

#

💀

frail hawk
frail hawk
#

never mind the debug is working, you said it is not working, i can see the debug log

tired python
frail hawk
#

yeah ok. it must be the mouse Position

#

mouse_pos = Mouse.current.position.ReadValue();

#

ScreenToWorldPoint expects a vector3

ivory bobcat
# tired python

Just to be clear, if you want the end drag function to occur as well, you'll need to interface it.

#
class A: B, Drag, DragEnd, etc```
frail hawk
#

yep that too

ivory bobcat
#

IEndDragHandler

frail hawk
tired python
ivory bobcat
#

You can find all of the event handlers on the left side of the documentation site

frail hawk
#

do what i said and it will work, change the line with mous_pos

tired python
ivory bobcat
tired python
#

asdfsfashdfsdhfuiuasdguoiyhuryn

#
public void OnClick()
{
    
    Debug.Log("Mouse Clicked.");
}
public void OnDrag(PointerEventData eventData)
{
    if (!ImageToRender.enabled) ImageToRender.enabled = true;
    ImageToRender.transform.position = mouse_pos;
    Debug.Log("Mouse being dragged.");
}
public void OnEndDrag(PointerEventData eventData)
{
    Instantiate(GameObjectHolder, mouse_pos, GameObjectHolder.transform.rotation);
    ImageToRender.enabled = false;
    Debug.Log("Mouse stopped dragging.");
}```
#

this is how my code is now

frail hawk
#

show the whole script. we need to see if you are implementing the Interfaces

tired python
#
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class ButtonScript : MonoBehaviour, IDragHandler, IEndDragHandler
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    [SerializeField] private Button button;
    [SerializeField] GameObject GameObjectHolder;
    [SerializeField] Image ImageToRender;
    Vector3 mouse_pos;
    
    // Update is called once per frame
    void Update()
    {
        mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
    }
    public void OnClick()
    {
        
        Debug.Log("Mouse Clicked.");
    }
    public void OnDrag(PointerEventData eventData)
    {
        if (!ImageToRender.enabled) ImageToRender.enabled = true;
        ImageToRender.transform.position = mouse_pos;
        Debug.Log("Mouse being dragged.");
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        Instantiate(GameObjectHolder, mouse_pos, GameObjectHolder.transform.rotation);
        ImageToRender.enabled = false;
        Debug.Log("Mouse stopped dragging.");
    }
}


#

ondrag and onendrag did shwo on the debug log, onclick too, if i click it...

ivory bobcat
tired python
ivory bobcat
#

Clones are being spawned but they aren't visible for some reason

frail hawk
#

change the rotation to Quaternion.identity instead GameObjectHolder.transform.rotation

tired python
ivory bobcat
tired python
ivory bobcat
#

You could quickly verify by clicking on a cloned object in the hierarchy and checking it's position, rotation etc

frail hawk
#

exactly

#

you need to learn debug techniques and analysing problems, this will save you alot of headache

ivory bobcat
#

Were those values acceptable? (note that they're all low and negative values)

tired python
#

why would they show up the right way on the scene but not the right way in game

ivory bobcat
tired python
tired python
#

wait then why does it show up in scene O_O

#

i don't understand, if its below the cavas, it shouldn't show it

ivory bobcat
#

The scene view isn't necessary from the camera's view.

#

Either way, check those values and see if they're acceptable

frail hawk
#

i am assuming something is wrong with your camera, did you change any settings there

tired python
#

ignore the mousescript, it's what i was using before to do this

ivory bobcat
# tired python

Show us the inspector and components of the visible droplet. How does it differ from those not visible?

tired python
ivory bobcat
ivory bobcat
tired python
#

i am sorry if it takes me sometime to upload images, my pc is pretty 🥔

ivory bobcat
#

So manually try changing the z value for a non visible cloned object and see if it becomes visible.

tired python
#

this is my mouse position's z component

#

ya well, it becomes visible

#

my mouse position's z component is under the whole thing probably

ivory bobcat
#

So maybe you ought to edit that value before using it to instantiate your clones or use a edited vector 3 copy of position etc

tired python
ivory bobcat
#

You do understand that converting mouse pointer from screen to world disregards the z component

tired python
#

i need a fix for it...

frail hawk
#

if you really want to use it you need to give it a z value manually

ivory bobcat
#

I tried, good luck.

tired python
frail hawk
#

but i see that as a work around and i woudl not recomend it. instead fix the sorting layers etc

ivory bobcat
tired python
#

so i should just hardcode it then?

ivory bobcat
ivory bobcat
tired python
ivory bobcat
tired python
#

just for clarification, when would you consider hardcoding something to not be a malpractice

frail hawk
#

may i ask why you are using ui lement to drag and drop but then instantiate a sprite

ivory bobcat
tired python
frail hawk
#

but you can do that with ui lements too

tired python
#

but it's not ui, as in, the object instantiated ain't a part of ui right

#

could you clarify or elaborate what you are trying to say?

frail hawk
#

you can use animations on ui elements too

tired python
#

is a tower considered ui O_O

#

or is ui basically any interactable object on screen

frail hawk
#

good question.

tired python
#

what's the answer O_O

frail hawk
#

i´d probably use a sprite

tired python
#

THANK GOD!!!!

ivory bobcat
tired python
#
public void OnDrag(PointerEventData eventData)
{
    if (!ImageToRender.enabled) ImageToRender.enabled = true;
    ImageToRender.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
    Debug.Log("Mouse being dragged.");
    Debug.Log($"{mouse_pos.z}");
}
public void OnEndDrag(PointerEventData eventData)
{
    GameObject GameObjectToSpawn = Instantiate(GameObjectHolder, new Vector3(mouse_pos.x, mouse_pos.y, 0), Quaternion.identity);
    ImageToRender.enabled = false;
    GameObjectToSpawn.SetActive(true);
    Animator anim_temp = GameObjectToSpawn.GetComponent<Animator>();
    anim_temp.enabled = true;
    Debug.Log("Mouse stopped dragging.");
}```
ivory bobcat
naive pawn
#

does ImageToRender have a sprite set

tired python
naive pawn
#

didn't say it's a sprite

#

i asked if it has a sprite set

tired python
#

this is the image being held

tired python
naive pawn
#

is that what's assigned as the ImageToRender?

naive pawn
#

droplet_notarget_0 is a sprite there, it's set to the source image field there.

tired python
tired python
formal sleet
#

Anyone who could teach me an easy way to implements states for a player?

naive pawn
#

well, given that it's a UI element, it generally shouldn't be moved via position iirc? but anchoredPosition of the RectTransform instead

ivory bobcat
#

Can you show more of the script?

naive pawn
#

also how are you setting mouse_pos

tired python
#
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class ButtonScript : MonoBehaviour, IDragHandler, IEndDragHandler
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    [SerializeField] private Button button;
    [SerializeField] GameObject GameObjectHolder;
    [SerializeField] Image ImageToRender;
    Vector3 mouse_pos;
    
    // Update is called once per frame
    void Update()
    {
        mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
    }
    public void OnClick()
    {
        
        Debug.Log("Mouse Clicked.");
    }
    public void OnDrag(PointerEventData eventData)
    {
        if (!ImageToRender.enabled) ImageToRender.enabled = true;
        ImageToRender.transform.position = new Vector3(mouse_pos.x, mouse_pos.y, 0);
        Debug.Log("Mouse being dragged.");
        Debug.Log($"{mouse_pos.z}");
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        GameObject GameObjectToSpawn = Instantiate(GameObjectHolder, new Vector3(mouse_pos.x, mouse_pos.y, 0), Quaternion.identity);
        ImageToRender.enabled = false;
        GameObjectToSpawn.SetActive(true);
        Animator anim_temp = GameObjectToSpawn.GetComponent<Animator>();
        anim_temp.enabled = true;
        Debug.Log("Mouse stopped dragging.");
    }
}
naive pawn
#

why are you getting the world coordinates

#

is this a world-space canvas?

tired python
#

i know world space means the scene coordinate system, whereas local space is the relative position of an object to another object, so...local space uses an object as its origin

naive pawn
#

there is another

tired python
#

O_o

naive pawn
#

two more, actually.
there's screen space and viewport space too, which are both relative to the plane of the screen
one is in pixels and the other is normalized, i don't remember which, probably screen space in pixels

#

what mode is the canvas set to?

#

you should be able to choose between screenspace overlay/camera and worldspace

tired python
naive pawn
#

is it scaled?

tired python
#

if so, then ya..?

naive pawn
#

in the transform, shouldve been more specific

tired python
#

it's the original

#

i didn't tamper with it...

naive pawn
#

alright, so that all checks out (though tbh, having it as a non-UI object would probably be easier, and then you could keep the canvas in screenspace)

#

have you checked the position of that preview image at runtime at all

tired python
naive pawn
#

this stuff shows up in the inspector, not the hierarchy

#

select the preview image, look at its position, see if that changes as expected when you move stuff

#

if it does, it might just be layered incorrectly

naive pawn
rapid spruce
#

Lets say I made a simple little error when initially setting up my project and might have created a 2D project instead of a 3D project. Is it possible to convert it somehow?

naive pawn
#

it basically just affects the default packages installed and the default scene template/scene view setup

#

if you change all of them to how they'd be in 3d (installing the 3d feature, removing the 2d feature, etc) you could "convert" it

#

but it's not really anything intrinsic to the project

rapid spruce
#

Yeah makes sense, I noticed that e.g. its using a 2d renderer etc.

naive pawn
#

if you aren't super familiar with unity yet and you haven't done much work, it'd probably be easier to just make a new 3d project and copy your work over

vast talon
#
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Parts")]
    public CharacterController CharCont;
    public Transform playerTransform;
    public Transform camTransform;
    public Transform GroundCheck;

    public LayerMask ground;

    [Header("Constants")]
    public float movementSpeed = 100f;
    public float jumpHeight = 250f;
    public float offset_x = 10f;
    public float offset_y = 5f;

    public const float GRAVITY = -9.81f;

    public float sphereRadius = 0.5f;

    private bool isGrounded = true;

    void FixedUpdate()
    {
        var velocity = Vector3.zero;

        isGrounded = Physics.CheckSphere(GroundCheck.position, sphereRadius, ground);

        velocity.z += movementSpeed * Time.deltaTime;

        if (Input.GetKeyDown(KeyCode.Space))
        {
            var target_velocity = Mathf.Sqrt(2 * jumpHeight * GRAVITY);

            velocity.y = target_velocity;
        }

        velocity.y += GRAVITY * Time.deltaTime;

        CharCont.Move(velocity);
    }

    private void LateUpdate()
    {
        var playerPos = playerTransform.transform.position;

        camTransform.position = new Vector3(playerPos.x + offset_x, playerPos.y += offset_y, playerPos.z);
    }
}
``` Ive decided to use a character controller instead of a rigid body and i am horrible at physics but can somebody tell me how to fix this?
naive pawn
#

CharacterController uses Update, not FixedUpdate

vast talon
#

okilt dokily

naive pawn
#

aside from that self-evident issue, can't really answer much

#

you haven't said what issue you have to fix lol

naive pawn
#

just btw, CC does provide its own isGrounded if you apply a constant gravity

vast talon
#

so i havent tested the game with the update function but the ground check doesnt work and the player is jittery when it touches the groud

naive pawn
#

you're modifying props of the prefab, not an actual gameobject in the scene

tired python
naive pawn
#

so.. why didn't you figure out that it wasn't showing up in the scene because it's not in the scene

#

that's pretty straightforward

tired python
#

so i assign the prefab to a null object and then reference it?

naive pawn
tired python
naive pawn
#

that's not really what i was asking

tired python
#

then i prolly misunderstood

naive pawn
#

the hierarchy is the list of things in the scene

#

if it's not there, it's not in the scene

tired python
#

so what do i do then...create a empty object, attach a script to it, which references this prefab and then reference that script ?

naive pawn
#

no, you don't need to reference the prefab at all

#

you aren't instantiating it at runtime

tired python
#

oh wait a sec then

ivory bobcat
naive pawn
#

prefabs are gameobjects turned into assets, that can be referenced and reused
right now you need a gameobject actually in the scene

tired python
#

ayo what

#

i copied it, and it doesn't show up O_O

naive pawn
#

you didn't put it in the canvas

ivory bobcat
#

Rect Transform usually indicates that they are part of a canvas

tired python
#

oh ya, i do remember someone telling me to not just yank it outta the canvas

ivory bobcat
#

Order may matter btw

tired python
#

now that i can instantialise the droplet onto the screen, i wanna know how you guys would recommend me to pick and drag those objects...should i use rays or smth else

frail hawk
#

glad you were able to fix it

tired python
#

i also wanna know how you might go about erasing them cus the dragon in the corner, that's a gameobject with an animator component, what i wanna do is basically, if anyone wants to sell a deploye dobject, they should be able to pick it up, then drop it in front of the dragon and then the dragon animation plays and the object gets destroyed

#

oh rob i finally implemented what you told me to use

naive pawn
grand snow
tired python
naive pawn
#

is it..?

tired python
naive pawn
#

oh, yeah, that's a mistake

#

spriterenderers aren't

#

the mistake is spriterenderer + canvas

#

it's either spriterenderer on its own, or canvas+image

#

but i did mention before, that having the preview and actual placed objects be non-ui objects would probably be easier tbh

#

just the UI things should be UI

tired python
naive pawn
#

im not basing it off of moving or not moving

grand snow
#

here we go again

naive pawn
#

i'm basing it off of what is actually UI

#

UI should be UI
nonUI should be nonUI

#

that's all im saying

tired python
#

is UI considered whatever you can click on

#

yes or no

naive pawn
#

no

grand snow
#

no

tired python
#

O_O

ivory bobcat
#

Anything interacting with the scene would probably not be ui.

grand snow
#

Look at any other game, you KNOW what is user interface and what is not

ivory bobcat
#

UI would be like data input, controller or whatnot

grand snow
#

pause menu? User interface
health text? user interface
unit on the ground? gameplay sprite/model

#

sometimes things mix but knowing when to use one solution over another is important

naive pawn
#

the things in red here are UI. the placement/range preview could be considered UI, but it'd be easier to treat it as not

naive pawn
#

ah shit. what color would be better

tired python