#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 395 of 1

remote osprey
#

The game session might end but I'm planning on adding a Deck Collection Manager Menu later

eternal needle
remote osprey
#

There will be a Data_SO class and a Data Class

#

The only difference will be that one is not SO

#

Which is confusing to me

#

Plus, how do I get the SO data without instantiating it?

eternal needle
#

then name it differently, or really just learn the difference. With the example, its not like you can call the exact same lines of code because you'd be using the SO to get the class data.
This is almost similar to saying "Idk the difference between Vector2 and Vector3 so i dont use either". the difference is clear, especially after you start to use it

remote osprey
remote osprey
#

Anyway, I dunno

eternal needle
#

a scriptable object is mostly used to just create an asset. You drag and drop this into the slot of scripts, so you immediately just have the SO and the data associated with it that you made at editor time.

fallen apex
#

Uhm i was doing a Texture2D by code, basically reading a text file and using it to generate an image, if i take the image and use EncodeToPNG() then save the bytes into a png image, the image is exactly what i want, but if i use EditorGUI.DrawPreviewTexture the editor just show me a white image.

#

how can i fix that?

#

i am doing this on a OnInspectorGUI

eternal needle
# remote osprey Really feels like extra needless code

Really, 2 lines is extra code? You realize the alternative is managing the lifetime of the scriptable object if you want many instances with mutable data. Thats more lines for instantiating, destroying, AND you need to reference the asset anyways so you can instantiate the one you want with pre-existing data. If you arent doing this, then you arent using SO for the purpose of the editor, and then this doesnt need to be a scriptable object at all.

remote osprey
#

Ye, ok, I guess

#

How do i use them properly tho?

#

Do i need to instantiate them to copy their data?

#

How do i do that, etc?

#

I just want to know the right way to do stuff so I don't make mistakes

eternal needle
remote osprey
#

Ok, so something like this?

public class ThingSO : ScriptableObject{

int property1;
....

public Thing Instantiate(){
 new Thing( ... \\ copy ThingSOs properties here )
}
#

Almost like a factory method

warm condor
frosty hound
warm condor
frosty hound
#

Yes, I mean, just take a second to think about it

#

You want to cache the previous position of something, so naturally you need to save the position before you assign a new one to it.

warm condor
#

ok so I have tried what you have said and it does work, but it also has a problem. When I walk right, there will be a change in the position regardless weather or not I change sides, which means that the if statement will return true.

#

should I consider the input that the player gives or is there another easier method?

frosty hound
#

Changing it wouldn't fix your actual problem, no, I was just pointing out that it could never be true because the order was wrong.

#

You can't do things like check floating values using ==, they will never be the same value.

#

If you want to actually know if the player is changing directions, you should just cache the direction the player is in with a bool for example: isFacingRight. The set that bool based on the horizontal input from the player.

vast sandal
#
        //calculate movementDirection from the Camera
        nextMovement = cinemachineCamera.transform.forward * movementDirection.z + cinemachineCamera.transform.right * movementDirection.x;
        nextMovement.y = 0f;
        nextMovement.Normalize();

        //calculate force to achieve desired acceleration
        movementForce = characterMass * movementAcceleration * Time.deltaTime;
        movementVelocity = playerRigidBody.linearVelocity;
        playerRigidBody.AddForce(nextMovement * movementForce, ForceMode.Force);
        if (playerRigidBody.linearVelocity.magnitude >= topSpeed.magnitude)
        {
            playerRigidBody.linearVelocity = movementVelocity;
            Debug.Log("LIMIT HIT! linearVelocity = " + playerRigidBody.linearVelocity);
        }
        else
        {
            Debug.Log("linearVelocity = " + playerRigidBody.linearVelocity);
        }

I'm stuck on this and was reading thru the search.. how would I go about this to implement said speed limit? ^^'

chilly raptor
#

Question:

For a 2D game, like a puzzle game, how should you set up the Main Camera (Perspective/Orthographic)? How about the Canvas? (Screen Space - Overlay/Screen Space - Camera/World Space)? Basically, I want the camera to be looking right at the play field.. my issue is that when ever I try placing game objects onto the play field, I can't use pixel coordinates. For example, my play field is 1080x1920 (portrait), I want to be able to put gameobjects randomly at -540/540 and -960/960, but I can't, as those coordinates are too big. I'm assuming it's worldspace. Obviously Unity is using positions like -5 through 5, lol, yes yes i'm all confused. But how should I set up my project so that I can use the actual camera size (1080x1920) ? Do I even make sense? Sorry...

summer stump
summer stump
#

It's all good.

elder osprey
#

What's the least expensive way to create a dropdown in the inspector? Using a separate class inside the same script, or using a struct?

#

Sorry, misclicked

slender nymph
#

neither of those options is really expensive. but you could create a custom inspector or use an asset like NaughtyAttributes that has a Foldout attribute

brave robin
zenith cypress
#

How are you determining a dropdown's "expensiveness" anyway

elder osprey
elder osprey
warm condor
# frosty hound If you want to actually know if the player is changing directions, you should ju...

So, I have been working on this for a while, and it has not really working for me. The thing is, I already have a variable that determines when the player's direction is at with an integer value (where the value 1 is facing right, and the value -1 facing left). I am using this to my advantage, but the problem is the program does not always detect the side switch, which is weird. Here is my code for more clarification:

  void Update(){
        PreviousMovementDirection = CurrentMovementDirection;
        if (Input.GetKey(KeyCode.A)) CurrentMovementDirection = -1;
        else if (Input.GetKey(KeyCode.D)) CurrentMovementDirection = 1; 
  }
  private void EnabledSideSwitch(){
        if(PreviousHorizontalPos != CurrentHorizontalPos) hasSwitchedSides = true;
        else hasSwitchedSides = false;
    }
rich adder
quiet willow
#

idk if GetKeyDown might be what you're looking for but its worth paying attention to that edge case, whether that's the only issue you have or not is hard to know with the current context

rocky canyon
#
        if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D))
        {
            CurrentMovementDirection = 0;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            CurrentMovementDirection = -1;
        }
        else if (Input.GetKey(KeyCode.D))
        {
            CurrentMovementDirection = 1;
        }```
south flower
#

Have you found a fix for the CodeAnalysis error?

remote osprey
#

Now that I stopped using scriptable objects my code logic broke :/

#

I used to be able to create scriptable objects and put them in another Event scriptable object with its own custom attributes and everything

#

Then I'd use that scriptable object to execute Events throughout the code

#

But people told me to stop using SOs for storing mutable data, so I did and now I have no way of passing my events from the inspector into the code

#

I just have no idae how to pass a object with it's own identity and attributes to the inspector, which gets converted to a generic Event abstract object, and then get that information that was lost back

#

wait, maybe that doesn't matter(!??)

#

Or maybe it does, how do i convert a SO to a non SO anyway?

#

they don't even share the same superclass!

#

any help would be extremely appreciated

remote osprey
#

@eternal needle any help?

teal viper
remote osprey
#

So I want to create custom Card Objects from a set of other objects and values. I want cards to have composable effects that are executed during specific Events (See the lists of effects in the inspector, e.g. "On Play From Hand Card Effects"). These effects are themselves Events.

I want to have a way to convert each of these events to a non scriptable object Event.

#
public class BeginTurnEvent : GameEvent
{
    public override IEnumerator ExecuteCoroutine()
    {
        GameManager.Instance.ChangePlayerTurn();
        GameManager.Instance.BeginTurn();
        yield return null;
    }

    public override IEnumerator UndoCoroutine()
    {
        throw new System.NotImplementedException();
    }
}

This is an example of an Event

#
[CreateAssetMenu(fileName = "Card Draw Event", menuName = "Game Events/Card Draw Event")]
public class CardDrawEventSO : GameEventSO
{
    public int numberOfCardDraws;

}

This is an example of a SO Event

#

This is the code to the Card Data SO:

[CreateAssetMenu(fileName = "NewCard", menuName = "Card Database/New Card")]
public class CardDataSO : ScriptableObject
{
    public string cardName;
    public CARD_TYPE type;
    public int cost;
    public int power;
    public int health;
    public string description;
    public Sprite sprite;
    public List<GameEventSO> OnPlayFromHandCardEffects;
    public List<GameEventSO> BeginTurnCardEffects;
    public List<GameEventSO> EndTurnCardEffects;
    public List<GameEventSO> CardDrawEffects; // When this is drawn
    public List<GameEventSO> CardDrawEventEffects; // When any card is drawn
    public List<GameEventSO> SpellCardPlayEffects; // When any spell is played
    public List<GameEventSO> SummonCardPlayEvent; // When any summon is played
}

As you can see, the Effects lists are Lists of GameEventSOs

Converting between the two is impossible because the implementation details of CardDrawEventSO get lost in GameEventSO.

ruby python
#

Okay, weirdest issue I've ever had with Unity. Last night before I went to bed my current project was working great, 300-400fps, pc was left on overnight (as it usually is), came to it this morning, nothing changed, simply ran the project, all of a sudden I'm getting 20fps. Reset my machine (full shutdown), and still getting 20fps.

Profiler is no help as literally everything is maxed out. Would anyone have any ideas as to what's going on please? (I know it's a difficult thing without any specifics, but I don't have any, just wondering if anyone had experienced anything similar before. :-/)

teal viper
ruby python
#

1 sec

teal viper
#

profiler is the ultimate source of truth for any performance issues.

#

If you can't solve it with the profiler, you can't solve it at all.

ruby python
#

tbh, the thing that's baffling the crap out of me is that between last night when I was getting 300-400fps and this morning, literally nothing has changed (as I was asleep lol)

teal viper
# ruby python

You'll need to learn to use the profiler.
Use the hierarchy mode to sort by CPU time and see what's coming up at the top.

ruby python
#

Hmm. Can't find any documentation about hierarchy mode or how to get to it. lol.

ruby python
#

Wow, I need to wake up properly, was staring right at it. lol.

Anyway. Looks like it's my players FixedUpdate that's causing the issue. Just weird that it wasn't an issue last night.

teal viper
# ruby python

Looks like the fixed update is called a hella lot of times per frame.

#

I'd check the Time settings in the project

#

Specifically the fixed timestep

#

Is it the same value for you?

ruby python
#

I did change that because my collisions were 'missing'. I can dial it back, but still really confused as to why it was fine before I went to sleep. lol.

teal viper
ruby python
#

Okay that seems to have sorted it out (changed it back to default). Very weirdness imo. lol. (I understand that the timestep value would affect the performance, just odd that it wasn't last night.)

teal viper
#

Yeah, I don't know why it didn't affect it last night. Not enough info.

ruby python
#

Yeah, that's all the info I've got though. Ran it last night, was fine, went to bed, woke up, ran it, it shat itself. lol.

teal viper
#

Fixed update also has a tendency to snowball. So perhaps it just didn't meet the snowballing condition yesterday.

ruby python
#

Aah okay. Yeah maybe. Ah well, tis sorted now, will just have to dial the timestep setting in later to get the balance.

#

Thank you for the help šŸ™‚

teal viper
#

I'd recommend not touching that setting at all.

#

Missing collisions usually have a better solution.

ruby python
#

Okeydoke. I'd seen a lot of posts online about missing collisions and adjusting that setting was always the 'go to' solution.

teal viper
#

Nah, internet is full of awful recommendations. That's one of them.

ruby python
#

lol. Fair play.

errant pilot
#

Guys how can i let my game look the same and have the same quality on different mobile sizes and resolutions

solar canyon
#

I want to create a variable for forward, backward, left, right movementkey. But it gives the error. 1. It says backward, left, right movementkey is not valid in this context. 2. = and ; invalid token. 3. A,S,W,D does not exist in this current context. What did I do wrong?

//
 public enum forwardMovementKey = KeyCode.W;

 public enum backwardMovementKey = KeyCode.S;
 public enum leftMovementKey = KeyCode.A;
 public enum rightMovementKey = KeyCode.D;
 */
 //Movement 
 public float movementSpeed = 5.0f;
 private Vector3 movementDirection;
 


 // Update is called once per frame

 void Update(){
    movement();
 }
 void movement(){
     if (Input.GetKey(forwardMovementKey)) {
         movementDirection += transform.forward;
     }       
     if (Input.GetKey(backwardMovementKey)){
         movementDirection -= transform.forward;
     }
     if (Input.GetKey(leftMovementKey)){
         movementDirection -= transform.right;
     }
     if (Input.GetKey(rightMovementKey)) {
         movementDirection += transform.right;
     }
willow scroll
keen dew
errant pilot
languid spire
teal viper
#

Not really a coding question btw.
Check the project settings - quality

willow scroll
solar canyon
#

Ohhh Thank y'all for helping

willow scroll
vast sandal
shut ivy
#

hey, can any experienced unity coder help me in a project i am stuck in. iam getting way too many errors and i dont know how to fix it. pref 18+ and dc vc

teal viper
teal viper
#

If it's a lot of info, you should create a thread.

burnt vapor
willow scroll
burnt vapor
#

I think you mean this

public int myInt = 10;
public string myString = "string";
#

Either way I suppose it's not actually part of the problem so carry on

#

Just though I'd point it out to avoid confusion

willow scroll
burnt vapor
#

I see, this was merely a comparison on what is not the correct way

#

Then I get it

willow scroll
shut ivy
#

does someone know how to fix this issue:

NotConfiguredClientException: Unity VCS client is not correctly configured for the current user: Client config file C:\Users\Yousef\AppData\Local\plastic4\client.conf not found. Please execute 'cm configure' to perform a text mode configuration or 'plastic --configure' for graphical mode.

languid spire
shut ivy
#

yh but where do i need to execute it

wet aurora
#

I am making an active Ragdoll and am trying to get it to mimic an animation from another, still model which does the animation. For some reason however, the active ragdolls legs just lift up and shake, is there anything wrong with my code or is it another issue?

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

public class CopyMotion : MonoBehaviour
{
    public Transform targetLimb;
    public bool mirror;
    ConfigurableJoint cj;
    void Start()
    {
        cj = GetComponent<ConfigurableJoint>();
    }

    // Update is called once per frame
    void Update()
     {
         if (!mirror)
        {
            cj.targetRotation = targetLimb.rotation;
        }
        else
        {
            cj.targetRotation = Quaternion.Inverse(targetLimb.rotation);
        }
     }
}
languid spire
stuck palm
#
private void FixedUpdate()
    {
        if (!started) {return;}
        foreach (ReplayPlayer rep in _replay._replayPlayers)
        {
            rep._buttonRecording.Add(rep.inputController.buttonList);
            rep.moveRecords.Add(rep.inputController.moveList);
            print("Added " + PrintList(rep.inputController.buttonList) + "to buttonlist");
            print("Added " + PrintList(rep.inputController.moveList) + "to movelist");
            rep.frameLength++;
            rep.lastMove = rep.inputController.moveList;
            rep.lastButton = rep.inputController.buttonList;
        }
    }

I'm getting proper console logs, but when I actually go to check the Json, it doesnt actually add them to the list. why is this?

#

I'm trying to add lists of inputs to a a List each frame

keen dew
#

What JSON? Nothing in this code has anything related to JSON

stuck palm
keen dew
#

That's where the problem is then I guess

vast sandal
#
    private void MovePlayer()
    {
        //calculate movementDirection from the Camera
        nextMovement = cinemachineCamera.transform.forward * movementDirection.z + cinemachineCamera.transform.right * movementDirection.x;
        nextMovement.y = 0f;
        nextMovement.Normalize();

        //calculate force to achieve desired acceleration
        movementForce = characterMass * movementAcceleration * Time.deltaTime;
        movementVelocity = playerRigidBody.linearVelocity;
        playerRigidBody.AddForce(nextMovement * movementForce, ForceMode.Force);
    private void CheckMaxSpeed()
    {
        if (playerRigidBody.linearVelocity.magnitude > topSpeed.magnitude)
        {
            playerRigidBody.linearVelocity = Vector3.ClampMagnitude(playerRigidBody.linearVelocity, topSpeed.x);
        }
    }

I use this to limit my player to topSpeed, but it doesn't work very well.. how do people usually do this?
I heared setting rb.velocity = topSpeed is a bad idea but what other way is there?

raven token
vast sandal
stuck palm
#

lists of lists are apparently not serialisable

#

but is there a way for me to see if a reference exists at least

raven token
vast sandal
#

I know I could just add a tiny bit, but thats not what I'm looking for

raven token
vast sandal
stuck palm
#

JsonConvert doesnt seem to be deserialising my list of lists properly.

#

its serialising it just fine

#

but when it comes to deserialisation it seems to fail

#

nvm, it turns out i was using JsonUtility to deserialise

cosmic dagger
#

!ide

eternal falconBOT
solar canyon
#

This is my code right now. When I hold WASD it moves the object in unity but when I stop holding/pressing it. The object keeps moving but it has to stop. How do I create that?

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

public class PlayerMovement : MonoBehaviour {  
        //Movement controlls
    
    public KeyCode forwardMovementKey = KeyCode.W;
    public KeyCode backwardMovementKey = KeyCode.S;
    public KeyCode leftMovementKey = KeyCode.A;
    public KeyCode rightMovementKey = KeyCode.D;
    
    //Movement 
    public float movementSpeed = 5.0f;
    private Vector3 movementDirection;
    

   
    // Update is called once per frame

    void Update(){
       Movement();
    }
    void Movement(){
        if (Input.GetKey(forwardMovementKey)) {
            movementDirection += transform.forward;
        }       
        if (Input.GetKey(backwardMovementKey)){
            movementDirection -= transform.forward;
        }
        if (Input.GetKey(leftMovementKey)){
            movementDirection -= transform.right;
        }
        if (Input.GetKey(rightMovementKey)) {
            movementDirection += transform.right;
        }
      
       // if (Input.GetKey(KeyCode.Space)) {
      //      jump += transform.up;
       // }

        // Prevent diagonal movement being faster (optional)
        if (movementDirection.magnitude > 1.0f){
            movementDirection.Normalize();
        }

        // Apply movement
        transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
    }
}
swift crag
#

movementDirection should not be a field.

#

I guess it can be one, but you'd better zero it out each frame (:

polar parrot
#

Someone know this problem?

naive pawn
#

didn't i answer that like, last night

polar parrot
#

yes bro, i saw your message but i can't fix it

naive pawn
#

and don't crosspost please

cosmic dagger
naive pawn
#

you're mixing stuff up, according to that other message

polar parrot
#

sorry

naive pawn
#

your using directives

warm condor
# quiet willow one thing that could be happening is that there are some special cases where you...

The problem with using this when detecting a side switch is that I am using CurrentMovementDirection for movement by multiplying it to the RidgidBody2D.velocity. So setting the CurrentMovementDirection to 0 is not going to work. I have also tried GetKeyDown, and it has worked better for me but it still has issues. I think I need to provide more context so ill just show you a video and my whole code:
Code: https://gdl.space/ocawakovib.cs

scarlet shuttle
#

im trying to spawn a object infront of the editor camera with a editor script but it ends up nowhere near the camera
Vector3 spawnPosition = SceneView.lastActiveSceneView.camera.transform.position + SceneView.lastActiveSceneView.camera.transform.forward * 5f;

solar canyon
swift crag
#

You don't need to remember its values from frame to frame

#

The problem is that you're just adding to it when the key is held down

#

If no keys are pressed, you don't change the value from last frame at all

#

thus, you keep moving

faint valley
#

Using the built-in character controller for the first time and I have some issues

#

It seems like the character can land on slopes that should be too steep for the slope limit

#

They will be considered grounded, they just can’t move up the slope

swift crag
#

"Grounded" just means that you hit something below you

#

If you need more information than that, you'll need to do some extra querying

#

for example, you could raycast downwards and measure the angle of the slope you find

faint valley
#

But you can’t use that to affect the results of the actual Move or MoveSimple call?

stuck palm
#

@swift crag i think i solved the replay system šŸ˜„ sending a vid in a second

faint valley
#

I’ve avoided the character controller because it seemed very limited, and I guess it’s true

#

I’ve had to make a workaround with raycasts to even make it step down stairs/slopes

quiet willow
faint valley
#

Also, OnControllerColliderHit doesn’t get called and doesn’t seem to be recognized as a built-in method

swift crag
#

You're expected to provide the movement logic on your own

stuck palm
#

@swift crag check it out šŸ˜Ž

swift crag
# stuck palm

One useful way to check your work: figure out a "hash function" for the entire game state

#

you can then check if you desync

faint valley
stuck palm
# swift crag One useful way to check your work: figure out a "hash function" for the entire g...

i was thinking something like making a struct for all the player inputs that get sent out every frame instead of having each of those seperately.

protected virtual void FixedUpdate()
    {
        if (!player) {return;}
        player.currentButtonState = buttonList.Count > 0 ? buttonList[0] : ButtonState.None;
        player.currentMoveState = moveList.Count > 0 ? moveList[0] : MoveState.None;
        player.LTPressed = LTPressed;
        player.RTPressed = RTPressed;
    }
#

this is how i do it right now

stuck palm
#

maybe i'd make 1 struct with the two lists, LT and RT pressed and stuff

swift crag
#

I'm working on a turn-based multiplayer game on the side

#

I transmit player actions to a router

#

The router bounces your own actions right back to you, and it tells you about other players' actions when it receives them

stuck palm
#

the only problem im thinking is that midway through a multiplayer game if theres any desync idk how i'd fix that

swift crag
#

explode

#

you can also pause the game and have one player transmit their game state to everyone else

stuck palm
#

wrong reply

#

because right now the only thing im actually sending out probably would be inputs, im not storing the positions of players or anything just yet

swift crag
#

The actual game state, yeah

#

You'd be re-synchronizing everyone

paper snow
#

how would i make a procedural camera shake based of off players movement

naive pawn
#

in first person?

paper snow
naive pawn
#

sounds like "view bobbing", have you tried googling that

paper snow
#

ive tried googling everything it does not say anything about using procedural animation

#

its usually based of off already made keyframes

swift crag
#

and what does "procedural animation" entail here, exactly?

paper snow
swift crag
#

you can use the current velocity of your character to control the strength of Cinemachine noise

carmine sierra
#

why is vector3.forward called that if it doesnt know which way forward is for the object

naive pawn
#

it's what unity knows is forward, not what the human thinks is forward

swift crag
#

Vector3.forward is [0, 0, 1]

#

This is "forward" in world-space

#

It's also "forward" in a Transform's own local-space.

#
Vector3 one = transform.TransformDirection(Vector3.forward);
Vector3 two = transform.forward;
#

Both lines produce the same result

#

a world-space direction in the direction the transform is facing

#
Vector3 one = Vector3.forward;
Vector3 two = transform.InverseTransformDirection(transform.forward);
#

These also produce the same result.

#

a local-space direction in which the transform is facing

#

which is, by definition, a constant

#

from your point of view, your forward direction is a constant

#

from the world's point of view, your forward direction is constantly changing as you rotate

carmine sierra
swift crag
#

Because they're two ways of calculating the same thing.

#

well, I shouldn't say that

#

They're literally the same thing

#

When you ask for transform.forward, Unity computes transform.TransformDirection(Vector3.forward)

carmine sierra
#

do they have use cases where they differ

#

is what i mean

#

yh mb i see

swift crag
#

It converts a local-space "forward" (which is a constant) into a world-space "forward" (which depends on your rotation)

carmine sierra
#

cause transformdirection can do more things

swift crag
#

Your local space doesn't change as you move, rotate, and scale.

#

But the conversion from local space to world space does change

#

You can see this by parenting an object to another object and then moving/rotating/scaling the parent

#

The child's inspector shows that its local position, rotation, and scale never change

carmine sierra
#

yeah whats the point of local spaace

late burrow
#

is try expensive even when not erroring

carmine sierra
#

it seems to mess things up for no reason

hoary ice
#

how do i control again the camera in scene tab using wasd?

swift crag
swift crag
#

if so, you're specifying the child's position, rotation, and scale in its parent's local space

carmine sierra
#

and then the 0,0,0 vector is no longer 0,0,0

swift crag
#

When you move your arm, you expect the sword you're holding to move with it

#

and if you rotate your arm, the sword should rotate, too

swift crag
#

But the sword shouldn't fly out of your hand or start spinning randomly in it

#

From your hand's point of view, the sword is staying perfectly still

carmine sierra
#

yeah exactly so if the sword wasnt parented and you used the same vector that would usually work

#

it would end up swinging in the middle of nowhere

swift crag
#

If the sword's local position is [0,0,0], its local rotation is [0,0,0], and its local scale is [1,1,1]

#

then you could just copy the parent's position/rotation/scale to the child's

#

But this is often not the case. You need to align the sword just right with the hand

#

and you probably need to rotate it a bit, too

#

So you adjust its local position and rotation

#

Now, no matter how the parent's position and rotation change, the sword will stay in the right spot

polar acorn
stuck palm
# swift crag You'd be re-synchronizing everyone

Interesting, I was planning on doing hosted lobbies, so I guess the host would be the point of reference for everyone to synchronize to. Maybe the host would have a store of all the positions somehow? My main issue when I first started trying multiplayer lobbies was that I found it hard to make something that was for the host only and stuff

carmine sierra
#

the parents position is in world space right

naive pawn
swift crag
carmine sierra
#

yh

swift crag
#

Having no parent is like being parented to a transform with default position, rotation, and scale

carmine sierra
#

so what did you mean by making the childs local spaace the same as the parents

#

i mean position

naive pawn
#

it's relative to the parents'

swift crag
carmine sierra
#

oh right

swift crag
#

If it isn't, then you'll be offset from your parent's position

#

How much you are and in what direction you are depends on your parent's rotation and scale.

naive pawn
#

like if you have a hand holding a sword, the sword stays at [0, 0, 0], relative to the hand, so the hand can move and rotate with the sword in the same spot relative to the hand

late burrow
#

how people tend to use single int to store multiple bools in it

naive pawn
late burrow
#

i know bitmask stuff but they quite annoying to work with

#

what about enums?

#

thought they purpose is for this

naive pawn
#

enums are just numbers with names

stuck palm
naive pawn
#

enums can be used to give bitfields or layers names, but they aren't equivalent

cosmic dagger
#

enums are named integers . . .

late burrow
#

so couldnt i bind name to multiple numbers?

swift crag
naive pawn
late burrow
#

for example 1 and 3 would both use first number

naive pawn
#

i have no idea what you mean by that

late burrow
#

cant enum retrieve like this?

swift crag
#

I cannot understand what you are talking about.

naive pawn
#

do you mean the first (rightmost) bit?

polar acorn
burnt vapor
late burrow
#

some boolean info stored in first digit couldnt i retrieve same data whether its 1 or 3 or 7

naive pawn
#

yes

burnt vapor
#

Works the same as manually navigating bits, but be aware this is less performant than doing it yourself.

#

Here's an easy way to write it, for example.

[Flags]
public enum Weekday
{
  None = 0,
  Sunday = 1 << 0,
  Monday = 1 << 1,
  Tuesday = 1 << 2,
  Wedday = 1 << 3,
  ThursDay = 1 << 4,
  Friday = 1 << 5,
  Saturday = 1 << 6,
}

When you do this, your value will have a HasFlag method that you can compare against

late burrow
#

and then how i overwrite it adding value to it

burnt vapor
naive pawn
#

you would not

burnt vapor
#

Just add values to the enum the same way as is specified

late burrow
#

it has 1 now i want add 2

#

but if it would be 3 adding 2 should be not possible

naive pawn
#

what do you mean by either of those

#

i have no idea what you mean

burnt vapor
#

Perhaps you should consider writing some basic methods that do this, bitshifting is not hard

naive pawn
#

or just bitwise OR, it sounds like you're thinking of?

burnt vapor
#

So if you want to add a flag to an existing bunch of flags, you can just call the method

naive pawn
#

or just, mask | newflag

#

you really don't need a method for that

burnt vapor
#
public static class FlagExtensions
    {
        public static Weekday AddDay(this Weekday me, Weekday toAdd)
        {
             return me | toAdd;
        }
    }

@late burrow, adding a flag for example

#

There are examples online

swift crag
burnt vapor
#

Generally I would use method anyway to add restrictions, as Fen specified

late burrow
#

not forbid just bool setting without erasing data

burnt vapor
#

So adding a flag? I don't know what else you would mean

swift crag
late burrow
#

yes its 11

swift crag
naive pawn
#

anuked you need to figure out how to express yourself more clearly, i really have no idea what exactly you're referring to

#

are you referrring to the layer order or the bits or what

late burrow
burnt vapor
late burrow
#

will need to test still

naive pawn
#

they're just numbers you're trying as a list of booleans

late burrow
#

just the | thing really

naive pawn
#

you can just use the bitwise or directly

#

there's 7 bitwise ops, it's not that complicated

burnt vapor
#

I suggest you just try it yourself and find out how it works

#

For example, this is how you would remove a flag again, using a method:

public static class FlagExtensions
    {
        public static Weekday AddDay(this Weekday me, Weekday toAdd)
        {
             return me & ~toAdd;
        }
    }
stuck palm
#

What is the purpose of bitmasks and stuff like that

naive pawn
#

bitfield & bitmask filters for the fields in the mask

#

bitfield ^ bitmask toggles the fields in the mask

#

etc

carmine sierra
#

public variables are only accesible in the class its made in?

#

not through other classes right

burnt vapor
naive pawn
naive pawn
#

public is available to everything

#

private is the default as well, so if you don't have access modifiers it's private

carmine sierra
naive pawn
#

you would have to reference that class

carmine sierra
naive pawn
#
class A {
  public int x = 0;
}

class B {
  void incAX(A a) {
    a.x++;
  }
}
burnt vapor
burnt vapor
#

It's a lot better than writing 32 packets, for example

naive pawn
#

you're confusing "access levels" and "scoping", try looking those up for more info

carmine sierra
late burrow
#

though i think it should work for bare ints too?

naive pawn
late burrow
#

if i 5 | 2 it will be 7

naive pawn
#

yes

late burrow
#

but 7 | 2 it will still be 7

naive pawn
#

yes

#

that's how bitwise works

burnt vapor
late burrow
#

cool i dont need enum then

naive pawn
#

i told you that since the start

late burrow
naive pawn
#

why?

late burrow
#

it was really bad when i was making layermasks like that

burnt vapor
naive pawn
#

it's much better than writing down powers of 2 as magic numbers

burnt vapor
#

It just makes the most sense on numbers integers

burnt vapor
#

Point is that it's not related to integers

naive pawn
#

floats and strings have specific meanings in their binary arrangement, some arrangements are invalid

#

integers are just... integers in a different base, nothing fancy

burnt vapor
#

That's why it makes most sense on integers

stuck palm
naive pawn
burnt vapor
#

Still, it's not even that weird to do it on float values. Rounding, for example, is done by bitshifting

burnt vapor
#

That's how it works

burnt vapor
naive pawn
#

also of course the legendary fast invsqrt

burnt vapor
stuck palm
burnt vapor
#

So it takes some extra work

burnt vapor
naive pawn
#

4 bits is a nybble

burnt vapor
#

1 sec

naive pawn
stuck palm
burnt vapor
#

It's a bit weird because this is a 20-ish year old language, and we only have 32 bit integers

#

But the important bit is line 31 and 91 where the conversions happen

naive pawn
burnt vapor
#

This is not C++, the site merely assumes it is C++

naive pawn
#

oh, i see the script thing, yeah
what is that language?

#

(man i forget how that site does that...)

burnt vapor
#

You get used to it, and it's pretty easy to deal with once you know the limitations

stuck palm
burnt vapor
#

The language is ACS, updated with networking abilities. Looks like that technically makes the language 29 years old, although Zandronum exists since 2012

naive pawn
#

(meanwhile me using unsigned char[3] to get 48-bit integers...)

stuck palm
stuck palm
burnt vapor
# stuck palm Looks tough to deal with

Also, luckily there is now a compiler that supports structs, namespaces and other features that just make it a ton easier to work with. Before that there wasn't even a good way to write objects 🄹

#

If it didn't exist I would have definitely not done this

naive pawn
stuck palm
#

My code is horribly written probably

stuck palm
burnt vapor
naive pawn
swift crag
#

it just wouldn't be a bitmask

#

but that's fine

naive pawn
#

it wouldn't be a bitmask, since you can't really condense it

swift crag
#

you use a bitmask to efficiently pack booleans

#

otherwise, you just send the data directly

#

You can pack button inputs into an int, then add controller inputs as floats

#

You could also convert the input into a byte or something

#

you probably don't need 4 billion possible X and Y input values

naive pawn
#

bitfields are based on bits
if your data isn't based on yes/no questions, then it isn't a bitfield

#

discord uses a bitfield for their permissions system, for example

#

bitfields are just about storing/sending data concisely

#

true has 1 bit of information but takes 40 bits to transmit or store

#

1 hexadecimal digit has 4 bits, takes 8

#

1 base64 digit has 6 bits, also takes 8

stuck palm
#

Isn't decimal bigger than long as well?

swift crag
#

it's 16 bytes, I want to say

naive pawn
#

yes, but it's not a pure binary format

#

decimal, as the name implies, supports decimals, and it's arbitrary precision

#

it's more akin to a bigger double than a bigger long

stuck palm
swift crag
#

no, C#'s decimal is just a 16 byte number

#

It says it's floating-point, but it also says that it can exactly represent numbers like 0.1 and 0.01

#

ah, it's just a decimal floating-point number, rather than a binary floating-point number

naive pawn
#

yeah it's just not IEEE 754 float

stuck palm
#

I clearly need to read up on some things

swift crag
#

"arbitrary precision" numbers are variable-size

naive pawn
swift crag
#

you can have "BigInteger" types for cryptography and counting very very high

#

or arbitrary-precision rational numbers

#

which can represent 1/7 more accurately than floating point ever could

naive pawn
#

which often has practical limitations still, but much higher than fixed-width types like double or long
but i guess Decimal isn't arbitrary precision, im just conflating it with other stuff

swift crag
#

there are things like "BigDecimal" in other languages

#

might have been thinking of that

naive pawn
#

yeah, java, definitely coming from that

naive pawn
#

typical floating points are like scientific notation, a mantissa and an exponent

#

IEEE 754 floats (float, double) are in base2, using the bits directly, while Decimal is base10

#

float supports ~6 digits of decimal precision and double supports ~17

rich adder
vast sandal
vast sandal
#

Side note:
Is there any way to get the world axis vector?

willow scroll
willow scroll
#

What's your current space?

mystic lake
#

how do i majke it so something happens when i press a sertain button? atm i have this but it doesn't work

willow scroll
vast sandal
willow scroll
#

Additionally, it seems like Visual Studio. Input should have another color. Configure your !ide

eternal falconBOT
vast sandal
willow scroll
willow scroll
mystic lake
rich adder
#

Buttons don't have KeyCode

#

also !ide @mystic lake

eternal falconBOT
vast sandal
carmine sierra
#

for the unity learn tutorials is it better to watch and then repeat, or do it while the vid is playing

willow scroll
mystic lake
#

ty

willow scroll
rich adder
#

your editor should be underlining the errors among other things

mystic lake
willow scroll
rich adder
mystic lake
#

because im already using visual studio

rich adder
#

I understand you are

#

its not configured, the error you shown should've been highlighted in the editor

#

follow all the instructions in the Visual Studio link

pliant oyster
#

Why doesn't Application.Quit() work? I have a Debug.Log("Clicked!") right above it, and it prints that, but the game keeps running.

pliant oyster
#

Oh thanks!

willow scroll
willow scroll
vast sandal
rich adder
willow scroll
mystic lake
rich adder
#

this isn't clear enough, we dont see what you see

mystic lake
willow scroll
stuck palm
#

@swift crag just realised an issue with my replay system, some ultimates in the game have randomly generated things such as random positions and random rotations which could mess some things up. Is there a way to make the randomness deterministic somehow?

rich adder
rich adder
swift crag
mystic lake
rich adder
#

make sure VS is closed while all this, after open script from unity

willow scroll
stuck palm
swift crag
#

Look at Random.InitState

willow scroll
#

But it should not be used

vast sandal
# willow scroll I would be able to assist you further if you tell me the actual problem

Tyvm, I appreciate that A LOT!

I actually think it's working now, unfortunately it doesn't feel as good as I was expecting..

I'm trying to code a rigid body character controller who's just working with acceleration (addforce) (thus my other question on how to set topSpeed without clamping velocity)

So in order for it to feel "snappier" I tried to implement a "momentum change" when you turn the character/camera
Say you run forwards, turn 90° --> you keep your momentum.. that works now (tyvm!) but it really feels as if I was flying a spaceship (got no gravity/friction rn) šŸ˜„

willow scroll
#

Use what Fen has mentioned

stuck palm
# swift crag Look at Random.InitState

At the start of the match I guess I could generate a seed that would be stored in the replay/ network manager that everything with random stuff would use

still pond
#

Hello, I hope im in the right section. Sometimes when I close a project all the level layout disappears but only the game objects, but the scripts and the assets are still there. Anybody has any idea why this happens?

willow scroll
stuck palm
#

If I use a seed will it generate the same number every time? Or will it generate the same sequence of numbers

naive pawn
willow scroll
#

!status

eternal falconBOT
vast sandal
rich adder
willow scroll
compact nymph
#

is there a way to access newitem from chargeupdate

#

sorry if this is a dumb question

swift crag
#

store it in a field

brave robin
#

If so, then Fen's got it

compact nymph
#

okay thanks

latent magnet
#

how can I load an image into a sprite from its png url?

rich adder
#

UnityWebRequestTexture

brave robin
#

There's an answer from 2018, so that code is probably still the valid way. It's only stuff from pre-year-numbered unity versions you should be careful of

rich adder
#

the only thing deprecated there is the WWW class as mentioned in replies

#

you're already ahead of most..

latent magnet
#
    private IEnumerator RequestImageFromURL(string url) {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.ConnectionError) {
            Debug.Log($"{request.error}");
        } else {
            var texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
            gameObject.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100f, 0, SpriteMeshType.FullRect);
        }
    }

this is what I currently have, and well i tried it but the only reason for asking my question here is because of some error i got

#

i cant send it here because its too long

#

and kinda obfuscated somehow

swift crag
#

Screenshot the error message, then.

latent magnet
latent magnet
swift crag
#

Ah, it's a webgl build

#

That produces more inscrutable errors

#

It looks like you wound up with a null sprite

rich adder
#

is the url correct

latent magnet
# latent magnet

the reason i thought the code for loading the image was deprecated or old is because UnityWebRequest is in that error at some line

rich adder
#

have you tested this in the editor

latent magnet
latent magnet
#

i currently cannot test it inside of the editor because it is a webgl build, it must be put into javascript as a webapp then executed there as a nested framework

swift crag
stuck palm
#

@swift crag tried playing with a friend and ran into a desync with the replay 😭 whats that hash function thing u were talkib about earlier?

latent magnet
#

to load it

swift crag
#

This would just help you detect a desync

#

It won't fix anything

swift crag
rich adder
swift crag
#

I don't know how Sprite.Create handles a null texture

#

If you're fetching an image from another domain, then you might have problems with cross-origin resource sharing

stuck palm
latent magnet
rich adder
#

but if they hosted local webgl that could be prblem

latent magnet
rich adder
#

its a webgl build on Github idk if they deal with CORS differently

vast sandal
rich adder
latent magnet
solar canyon
latent magnet
swift crag
rich adder
swift crag
#
public void Foo() {
  int bar;
}
#

bar is a local variable.

stuck palm
rich adder
latent magnet
#

ive been on this exceptions ass for too damn long man

latent magnet
#

webgl debugging is cancerous

naive pawn
swift crag
#

ooooops

#

You saw nothing šŸ˜‰

naive pawn
#

lmao

rich adder
latent magnet
mystic lake
#

why does it not show the gun if i press 2?

slender nymph
#

because if you don't press 1 then it gets set to inactive wait i'm dumb ignore that

rich adder
rich adder
mystic lake
#

yep

#

thx for the help earlier btw

polar acorn
slender nymph
# mystic lake wdym

why is it that you waited until after i'd edited that to reply? or are you asking what i mean when i say ignore that? šŸ¤”

mystic lake
mystic lake
naive pawn
#

logging = Debug.Log

polar acorn
slender nymph
latent magnet
# rich adder yes all CRUD requests can be done in unity with webrequest Such as GET etc..

alright, i didnt want it to head south
but i guess we're going south
theres no other way of debugging this

    private IEnumerator RequestImageFromURL(string url) {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.ConnectionError) {
            Debug.Log($"{request.error}");
        } else {
            var texture = DownloadHandlerTexture.GetContent(request);
            if (texture == null) {
                Debug.Log("TEXTURE IS NULL FOR URL => {" + url + "}");
            }
            gameObject.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100f, 0, SpriteMeshType.FullRect);
        }
    }
slender nymph
#

there are beginner courses pinned in this channel. start there.

mystic lake
#

where do i put it in my code?

polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
mystic lake
languid spire
polar acorn
slender nymph
latent magnet
mystic lake
solar canyon
#

Really quick question. What is the code or thing called between the {}. I forgot what it is called

languid spire
latent magnet
#

is there any compile or build options to make it readable?

naive pawn
#

class X {} = class body
void Foo {} = method body
X() {} = constructor body
if () {}/while () {}/else {} = block
new X() {} = initializer block

languid spire
rich adder
slender nymph
solar canyon
#

Ohhhh thank you

latent magnet
#

see for yourself the exception

#

all of it is just referencing .wasm files

#

not my actual code files

rich adder
#

because a WEBGL build gets made into wasm

#

in order to run inside a browser

#

it takes your C# code and turns it into wasm

#

thats why said before doing anything you should Debug.Log inside the editor first, to rule out its not webgl alone

languid spire
latent magnet
rich adder
#

I can try your URL if its not a private thing, to see if it works on my WEBRequest

mystic lake
#

i just added the debug and it doesnt give me anything back, what does that mean exacly?

rich adder
rich adder
#

afaik you should still be able to at least see logs in Webgl, don't they get browser console printed?

languid spire
mystic lake
naive pawn
#

but it isn't reaching the if

rich adder
mystic lake
#

yea

#

i put it on my gun

naive pawn
#

does it log when you press 1

mystic lake
#

let me check

naive pawn
mystic lake
naive pawn
#

yes, because you disabled it lmao

#

you need to put the script on something persistent, probably the player which would be the parent of the gun

mystic lake
#

this is the entire script, it shjould only disable 1 section right?

naive pawn
#

you can't disable a section of a script

latent magnet
#

@rich adder
line 32 in your gist
the method GetTexture returns type Texture
and my code uses Sprite.Create() which requires Texture2D as the first parameter, could that cause issues or can i safely parse Texture to Texture2D?

naive pawn
#

your script is on Gun. you disable Gun. that disables everything on Gun, including that script

slender nymph
mystic lake
naive pawn
rich adder
#

first I would log if you have an actual texture there.

naive pawn
#

also FixedUpdate and anything else

mystic lake
#

whats the line of code to hide something so you cant see it?

slender nymph
naive pawn
#

in general though?

slender nymph
#

well yes, but i was referring specifically to the code they showed

naive pawn
#

ah, ok

#

missed that nuance

mystic lake
rich adder
languid spire
naive pawn
#

or whatever you're using to render

#

idk 3d

mystic lake
mystic lake
#

no bc of InHand

languid spire
rich adder
#

just disable the entire wep object, dont put weapon switching on the guns. Simple

mystic lake
naive pawn
mystic lake
naive pawn
#

and just put the script on the controller of the gun

#

ie, the player

#

like i said

latent magnet
rich adder
mystic lake
naive pawn
languid spire
mystic lake
rich adder
naive pawn
#

this isn't controlling aspects of the gun, this is controlling presence of the gun

naive pawn
#

you don't need to be smart to make a game

#

you just need to put in the effort

languid spire
naive pawn
#

that's how you get smart along the way

mystic lake
naive pawn
#

not effort on the game

#

effort on learning how to make the game

mystic lake
rich adder
naive pawn
#

if you invest a few hours learning you can be 10 times more productive when you actually get to work

rich adder
#

your first project is never going to be your "dreamproject"

mystic lake
#

i made a ball rolling platformer game before this

rich adder
#

all your first projects are gonna be crap until you refine your craft

rich adder
mystic lake
rich adder
#

inventories are already complex within themselves

#

weapon switching involves inventory

mystic lake
rich adder
#

player holds weapons, thats not inventory ?

naive pawn
#

gun switching
yeah that's an inventory

mystic lake
#

i just want it so if i press 1 or 2 that it switches gun

naive pawn
#

yeah

#

so you need to know what guns you have

#

and what gun is active

#

that makes an inventory

#

inventory isn't just about storage, it's about what you have as a whole

rich adder
mystic lake
#

but yea

rich adder
#

so you realize that is an inventory right

latent magnet
# latent magnet
    void Update() {
        if (loaded) return;
        if (data == null) return;
        StartCoroutine(RequestImageFromURL(data.iconUrl));
        loaded = true;
    }

    private IEnumerator RequestImageFromURL(string url) {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
        yield return www.SendWebRequest();
        yield return new WaitUntil(() => www.isDone);
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            if (myTexture == null) {
                Debug.Log("NULL TEXTURE FOR URL => {" + url + '}');
            }
            gameObject.GetComponent<Image>().sprite = Sprite.Create((Texture2D)myTexture, new Rect(0, 0, myTexture.width, myTexture.height), new Vector2(0.5f, 0.5f), 100f, 0, SpriteMeshType.FullRect);
        }
    }

it produced the exact same error message as before and not logging anything

mystic lake
naive pawn
#

you have multiple things and you're keeping track of what thing is active

rich adder
#

you probably never used an array

mystic lake
rich adder
#

exactly, these are the basics stuff you would learn before doing an entire game..

latent magnet
mystic lake
#

ok? i didn't know i needed to learn that first

#

i just started by trying to make a game

slender nymph
#

if only there were structured courses you could do that taught you the fundamentals of game development

rich adder
# mystic lake ok? i didn't know i needed to learn that first

eg

    public Gun[] Guns;
    int currentGunIndex = 0;
    public void NextGun()
    {
        Guns[currentGunIndex].gameObject.SetActive(false);
        currentGunIndex = (currentGunIndex + 1) % Guns.Length;
        Guns[currentGunIndex].gameObject.SetActive(true);
    }
    public void Fire()
    {
        Guns[currentGunIndex].Fire();
    }```
mystic lake
rich adder
#

all the resources that you need are pinned in this channel

solar canyon
#

How do I make this line of code:

//
 private Vector3 movementDirection;

into a local variable in the Full Code:
A local variable should be a variable in a function itself. So I thought it would be something like putting Vector3 movementDirection into a constructor body like so.

//
 if (Input.GetKey(forwardMovementKey)) {
    Vector3 movementDirection;
    movementDirection += transform.forward;
    } 

But it doesn't work. It says ** Use of unassigned local variable 'movementDirection' ** Could someone explain why it doesn't work?
Full Unedited Code


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

public class PlayerMovement : MonoBehaviour {  
        //Movement controlls
    
    public KeyCode forwardMovementKey = KeyCode.W;
    public KeyCode backwardMovementKey = KeyCode.S;
    public KeyCode leftMovementKey = KeyCode.A;
    public KeyCode rightMovementKey = KeyCode.D;
    
    //Movement 
    public float movementSpeed = 5.0f;
    private Vector3 movementDirection;
    

   
    // Update is called once per frame

    void Update(){
       Movement();
    }
    void Movement(){
        if (Input.GetKey(forwardMovementKey)) {
            movementDirection += transform.forward;
        }       
        if (Input.GetKey(backwardMovementKey)){
            movementDirection -= transform.forward;
        }
        if (Input.GetKey(leftMovementKey)){
            movementDirection -= transform.right;
        }
        if (Input.GetKey(rightMovementKey)) {
            movementDirection += transform.right;
        }
      
       // if (Input.GetKey(KeyCode.Space)) {
      //      jump += transform.up;
       // }

        // Prevent diagonal movement being faster (optional)
        if (movementDirection.magnitude > 1.0f){
            movementDirection.Normalize();
        }

        // Apply movement
        transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
    }
}
naive pawn
solar canyon
naive pawn
carmine sierra
#

what is professional practice when referencing between scripts and gameobjects

#

do people actually use tags

naive pawn
#

Movement doesn't have a body or block {}
it does

carmine sierra
#

and find

willow scroll
rich adder
carmine sierra
#

so dragging and dropping?

rich adder
#

ye

#

if inspector is not possible then simple DI

#

or singleton

naive pawn
#

@solar canyon if you can't make a variable local to a method, you should probably seek out a guide on c#
you're also misusing a lot of terms, so you clearly don't understand these ("constructor", "scope", "condition")

rough lynx
rich adder
# carmine sierra so dragging and dropping?

or if you need runtime components, like a collision,raycast etc.
then TryGetComponent or GetCompeonnt.
so basically no matter wat you want to be working with Components, stay away from Strings like names, CompareTag is acceptable but fragile

elder osprey
#

This value variable equals 0 constantly. It's supposed to equal 3 when the sensitivity variable equals 100, it is always returning 0.

short hazel
elder osprey
#

Oh! Thats annoying, thank you!

short hazel
#

It's intended behavior. Convert one of the two operands to a float (eg. 3 / 100f) so the division is made on floats

pliant oyster
#

Is this the correct way to make a variable that will be referenced throughout the game in various different scenes?

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

public class GlobalVariables
{
    public struct Cirno
    {
        public static int health = 3;
    }
}
willow scroll
#

You should make your class static, first of all

pliant oyster
#

It now throws errors about needing an "explicitly declared constructor"

willow scroll
#

Well, how do you reference it?

pliant oyster
#

Well, I would have referenced it as "if the character takes a hit, the health gets lowered by 1, and it carries over to the next level."

feral palm
#

how do i get rid of all this

#

ping me if anyone knows

willow scroll
pliant oyster
willow scroll
#

Then create a scene in your GameManager, which manages the transition to the next Scene

pliant oyster
#

I'll try...?

rocky canyon
willow scroll
pliant oyster
willow scroll
pliant oyster
#

Idk. This is my entire code:

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class GameManager : Singleton<GameManager>
{
    public int health;
}
willow scroll
#

I've told you to merely copy-paste the Singleton from the site

#

You shouldn't have changed it to static

pliant oyster
#

I didn't change anything except the name and type of the variable.

willow scroll
pliant oyster
#

I copy pasted it like you said. All I did was replace the bool yourBool with int health

willow scroll
#

Alright, could you show your Singleton class?

ivory bobcat
#

Where did you copy this from?

pliant oyster
willow scroll
ivory bobcat
willow scroll
naive pawn
#

yeah, remove that directive

willow scroll
stuck palm
#

why are hash128's serialised like this?

ivory bobcat
pliant oyster
ivory bobcat
pliant oyster
#

He said to copy paste the code. I did that.

faint valley
willow scroll
willow scroll
willow scroll
ivory bobcat
#

It's the same link šŸ˜…

pliant oyster
#

I'm trying to desperately figure out what you meant because I don't know these complicated terms. I'm now trying to do this with the link.

willow scroll
#

I have mentioned copying a full Singleton<T> class and deriving your GameManager from it

swift crag
#

the visual scripting package has its own Singleton class, which is what's getting dragged in by your IDE.

willow scroll
#

If you open the first link I've send, you can figure out a bit more about Singletons from the conversation 1 month ago

swift crag
#

You need to create your own Singleton class.

pliant oyster
swift crag
#

Do not use a spam generator to try to learn how to program.

pliant oyster
#

Is this correct?

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

public abstract class Singleton<T> : MonoBehaviour
    where T : Singleton<T>
{
    public static T Instance { get; private set; }

    void Awake()
    {
        // Destroy this object if we already have a Singleton defined
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        DontDestroyOnLoad(gameObject);
        Instance = (T)this;
        DoAwake();
    }

    // Virtual method to allow implementations to use Awake
    protected virtual void DoAwake() { }
}

public class GameManager : Singleton<GameManager>
{
    public class Cirno
    {
        public int health;
    }
}
willow scroll
pliant oyster
swift crag
#

instead of just throwing your hands up

naive pawn
willow scroll
willow scroll
#
    1. How are you going to derive from an abstract class?
    1. You can only have 1 MonoBehaviour per script
naive pawn
#

you can derive from abstract classes just fine

#

the code you linked also uses an abstract class

#

also, you can only have 1 public type per script, not 1 monobehaviour

willow scroll
pliant oyster
willow scroll
pliant oyster
#

Okay.

naive pawn
willow scroll
naive pawn
#

make a file named Singleton.cs and put your Singleton class there

willow scroll
pliant oyster
naive pawn
pliant oyster
#

I also am sorry that it is hard for me to understand it, I'm mentally disabled so it takes a lot more effort to explain things to me. Thank you for helping me!

willow scroll
naive pawn
#

i mixed up Decimal and java's BigDecimal earlier today too, i can't escape java lmao

lethal bolt
#

How do i take only the x?

late burrow
#

can i bit edit without referencing like +=

naive pawn
#

without referencing
how are you going to change it then

late burrow
#

i mean referencing twice

naive pawn
#

anyways yes c# has bitwise assignment operators

late burrow
#

+= doesnt needs second same code

#

ok i see |= is a thing

lethal bolt
slender nymph
#

well for starters, you shouldn't be modifying the individual axes of a quaternion. and also, you do realize that page is about the error and is not specific to assigning a single axis of a position, right?

stuck palm
#

leaving it for tonight cus i dont wanna burn myself out

swift crag
#

the point of the hash is to check that the game states are in sync

#

not the inputs -- those are a given

stuck palm
swift crag
#

positions, velocities, states...

#

anything that could get out of sync

stuck palm
#

but probably not actually now that i think of it

swift crag
#

You send your controller input to the other player, and they use that to simulate the game

#

you need to find out if that simulation is wrong

pliant oyster
#

How do I set Application.targetFrameRate to a float/double instead of the usually required int? Specifically 59.727500569606 to make it authentically like a GameBoy.

stuck palm
swift crag
pliant oyster
#

Okay. Thanks!

swift crag
#

Just shoot for 60 here

#

Unity tries to wait for roughly the right amount of time, but it's not perfect

stuck palm
#

i dont think anyone would notice anyway

#

does the order of adding hashes affect the result?

swift crag
#

Yes.

#

You must do it exactly the same on every client.

stuck palm
#

that might be the problem then?

swift crag
#

Ideally, each player shouldn't really care which character they control

stuck palm
#

i might be adding 1 then 2 in the first one, then 2 and 1 in the first one

swift crag
#

each player is just producing inputs that the game happens to use to control one of the characters

#

You might still care about who you control for visual effects (maybe your camera shakes if you're damaged?)

pliant oyster
#

Do I have to specify the framerate at the start of every scene, or is it fine if I just have it in my GameManager?

swift crag
pliant oyster
#

Thanks!

swift crag
stuck palm
stuck palm
swift crag
#

Floating point math isn't inherently "random". There are well-defined rules for how it works.

#

Between Windows/Mac Standalone, Android native, iOS native, and WebGL (via a browser in Windows, Android, iOS and Mac), the only non-deterministic results reported were in trig functions contained in System.Math. There are a couple likely reasons for this.

#

It sounds like Mathf is well-behaved

#

(you're exploring a topic that i've been meaning to try for a while now :p)

stuck palm
#

okay cool

#

im not even using rigidbodies or anything, im using my own physics system which should work pretty deterministically, idk why it keeps desyncing, it must be something with the inputs not being recorded properly 😭

#

the players move like this

keen pecan
#

Does anyone know what to when a character controller's isGrounded value keeps alternating between true and false?

stuck palm
#

that isGrounded thing has given me too much strife lmao

keen pecan
#

Wdym

slender nymph
stuck palm
#

what he said

swift crag
keen pecan
#

Shouldnt this line make it work though?

swift crag
#

ah

swift crag
#

CheckBox

stuck palm
#

checkbox is technically right

swift crag
#

parsed that as a āœ…

stuck palm
#

captialisation is important

swift crag
#

!code

eternal falconBOT
keen pecan
topaz fractal
#

in my charactercontroller, when i prress 2 inputs, my character moves faster, what can i do?

slender nymph
#

normalize the input
or clamp its magnitude to 1 if you want to support magnitudes below 1

keen pecan
slender nymph
#

how have you confirmed that it "keeps alternating between true and false"

keen pecan
#

I have Debug.Log(isGrounded) at the bottom of Update()

slender nymph
#

show the logs then

#

and maybe consider logging some other useful information like the movement vector

stuck palm
keen pecan
swift crag
#

so that you can manually compare the states once it goes wrong

stuck palm
#

what like a list of positions and stuff?

swift crag
#

give it a Hash() method that produces the fixed-size hash to share

#

yeah

topaz fractal
#

@slender nymph could you help me out on explaining how to clampmagnitude?

stuck palm
#

okay will try that

topaz fractal
#

yes it was a little confusing

slender nymph
# keen pecan

this does not appear to be "alternating" between true and false. this appears to be true for a while then false for a while, likely due to your CC not being grounded for those frames

keen pecan
#

@slender nymph it seems to alternate like every second

rocky canyon
#
 inputDirection.Normalize();```
slender nymph
swift crag
# keen pecan

Does the rate of "flickering" increase while you're moving?

#

I wonder if the minimum move distance for a CharacterController is causing it to get stuck on "False" for several frames

#

The default value is a bit high.

rocky canyon
eternal falconBOT
swift crag
#

see above

slender nymph
rocky canyon
#

thats not the entire code.. im wondering if theres more to it.. he also has Gizmo's being drawn that he said he didnt do

keen pecan
#

The gizmo only shows up in scene view though when i clikc on the banana

swift crag
#

that was an unrelated question, I think

rocky canyon
#

ahh it could be animation rigging

keen pecan
#

Thats what i thought at first but the issue persisted when i deactivated the animator

rocky canyon
#

the animation rigging stuff is its own component

#

it relies on the animator but the gizmo's arent from the animator

keen pecan
#

@slender nymph is there a better way to paste the logs than snipping tool?

rocky canyon
#

but thats a non-issue.. ur ground check is the main issue

keen pecan