#š»ācode-beginner
1 messages Ā· Page 395 of 1
why the exact same? the example you were shown here is completely different
#š»ācode-beginner message
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?
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
Really feels like extra needless code
But that's not really the case, I'm choosing Vector2 instead of Vector3
Anyway, I dunno
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.
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
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.
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
if the data is a class that you need to modify, then you can create a copy constructor (
) for that class. If you dont modify it then you could even just not copy it, and just read it directly from the SO
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
Guys, can someone help me here, no one has answered me? #š»ācode-beginner message
Ok 'im googling it
Well, for starters, you're setting the PreviousHorizontalPos to be the CurrentHorizontalPoo after you've set the current one to the new value. So they're always going to be the same.
I don't think I understand, do you mean the order is wrong, do I have to do this?
CurrentHorizontalPos = transform.position.x;```
Instead of this:
``` CurrentHorizontalPos = transform.position.x;
PreviousHorizontalPos = CurrentHorizontalPos;```
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.
ohh that makes sense, let me try that
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?
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.
thats a good idea
//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? ^^'
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...
Every answer starts with "it depends"
But generally for 2d, the camera is orthographic. A canvas for ui could be screenspace-overlay kr camera.
The gameobjects would likely be placed in worldspace btw. The camera has methods for converting, like ScreenSpaceToWorld
Lastly, this is not really a code question. Better for #š»āunity-talk
Sorry, and thank you.
It's all good.
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
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
Both are about the same if you just need a grouping of fields
How are you determining a dropdown's "expensiveness" anyway
I was about to delete the question a second ago, because I thought about it for a second and realized it wouldnt be expensive either way.
Thank you, I will look into those
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;
}
this is pretty much what I said you shouldn't do
one thing that could be happening is that there are some special cases where you have both A and D pressed, in which -1 would always be returned since the A check is first in your if else check. So depending on how you run the movement logic there could be a mismatch between your movement logic and your switch logic
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
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;
}```
Have you found a fix for the CodeAnalysis error?
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
@eternal needle any help?
Might want to share more details and code in a thread, as it is not exactly clear what you're trying to do.
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.
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. :-/)
wdym by "no help as everything is maxed out"??
1 sec
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.
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)
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.
Hmm. Can't find any documentation about hierarchy mode or how to get to it. lol.
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.
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?
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.
What value did you change it to?
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.)
Yeah, I don't know why it didn't affect it last night. Not enough info.
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.
Fixed update also has a tendency to snowball. So perhaps it just didn't meet the snowballing condition yesterday.
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 š
I'd recommend not touching that setting at all.
Missing collisions usually have a better solution.
Okeydoke. I'd seen a lot of posts online about missing collisions and adjusting that setting was always the 'go to' solution.
Nah, internet is full of awful recommendations. That's one of them.
lol. Fair play.
Guys how can i let my game look the same and have the same quality on different mobile sizes and resolutions
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;
}
Well, because of the pixels, it's impossible for them to look exactly the same, but you'll have to e.g. work on your Canvas
The type of variables that hold enum values is the enum type, not enum. So public KeyCode forwardMovementKey = KeyCode.W; and so on
It's just the quality idw it to deteriorate cause on my PC it's fine on my phone it looks straight out of a 2000 movie
that is not how you define Enums
public enum Direction { Forward, Backward, Left, Right }
Sounds like different quality settings for different platforms.
Not really a coding question btw.
Check the project settings - quality
enum is just a type, so it's the same as creating an integer or string like this:
public struct myInt = 10;
public class myString = "string";
Ohhh Thank y'all for helping
Well, it realy shouldn't happen..
Yeah thatās what I came up with (additionally it doesnāt work) than I saw your statement and was like āeh dang how should I do it?ā
With .clamp? š¤
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
You're not gonna get private tutoring here. You should ask your question and provide context on the issue and if someone can and is willing to help you, they will.
alr mb
If it's a lot of info, you should create a thread.
???? You mistyped int for struct and string for class?
See the [original question](#š»ācode-beginner message) for the reference
I just don't understand how your code applies as an answer because it's neither valid nor what you mentioned in the message
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
enumis just a type, so it's the same as creating an integer or string like this:
They used enum as the variable's type instead of its name KeyCode, so I said it's the same as using struct for int and class for string. All are not valid in this context.
Yes, I thought they could understand it better this way
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.
Read the message. It's telling you how to fix it
yh but where do i need to execute it
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);
}
}
}
At a guess, the default pivot directions of cj and targetLimb do not match
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
What JSON? Nothing in this code has anything related to JSON
at the end of a game, it saves _replay to a json.
public struct Replay
{
public List<ReplayPlayer> _replayPlayers;
public LevelEnum level;
}
That's where the problem is then I guess
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?
You can just not add force when over the speed limit
Tried that, but than i can decelerate/turn either
lists of lists are apparently not serialisable
but is there a way for me to see if a reference exists at least
Is there a reason that your speed is above the top speed? Because if you are on flat ground for example, if you dont add force you decelerate due to drag and forces should be added again
Disabled gravity for testing as I want it to work in no grav thus my player doesn't experience any "world deceleration"
I know I could just add a tiny bit, but thats not what I'm looking for
You could apply a sort of drag force when above the max speed to limit the velocity
Thats also just a workaround.. there must be some "clean" way I assume..
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
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
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);
}
}
movementDirection should not be a field.
I guess it can be one, but you'd better zero it out each frame (:
Someone know this problem?
didn't i answer that like, last night
yes bro, i saw your message but i can't fix it
and don't crosspost please
you need to specify which namespace you are using DecalProjector from . . .
ok, so say it. don't just ignore the messages and ask the same thing again
you're mixing stuff up, according to that other message
sorry
where can i do it?
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
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;
If it shouldn't be one. How should I replace/change?
Just make it a local variable
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
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
"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
But you canāt use that to affect the results of the actual Move or MoveSimple call?
@swift crag i think i solved the replay system š sending a vid in a second
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
you could simply use another variable for the switch and have that be 0 if both are pressed as the other user suggested
Also, OnControllerColliderHit doesnāt get called and doesnāt seem to be recognized as a built-in method
The CharacterController's job is to move in a way that respects colliders.
You're expected to provide the movement logic on your own
One useful way to check your work: figure out a "hash function" for the entire game state
you can then check if you desync
Well, thatās the plan, but it doesnāt expose much of the inner workings
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
Yeah, that's the rough idea.
maybe i'd make 1 struct with the two lists, LT and RT pressed and stuff
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
the only problem im thinking is that midway through a multiplayer game if theres any desync idk how i'd fix that
explode
you can also pause the game and have one player transmit their game state to everyone else
what, like character positions or whatever?
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
how would i make a procedural camera shake based of off players movement
in first person?
yes something like a realistic horror game
sounds like "view bobbing", have you tried googling that
ive tried googling everything it does not say anything about using procedural animation
its usually based of off already made keyframes
and what does "procedural animation" entail here, exactly?
my fault not procedural animation i just need something that moves the camera based of off player movement
you can use the current velocity of your character to control the strength of Cinemachine noise
why is vector3.forward called that if it doesnt know which way forward is for the object
it's what unity knows is forward, not what the human thinks is forward
It doesn't know what way is forward for a specific object!
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
so why are there two options for it
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)
It converts a local-space "forward" (which is a constant) into a world-space "forward" (which depends on your rotation)
cause transformdirection can do more things
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
yeah whats the point of local spaace
is try expensive even when not erroring
it seems to mess things up for no reason
how do i control again the camera in scene tab using wasd?
have you ever parented an object to another object?
yh
if so, you're specifying the child's position, rotation, and scale in its parent's local space
and then the 0,0,0 vector is no longer 0,0,0
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
ohh okay, i understand
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
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
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
for what reason?
Yes
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
the parents position is in world space right
only the top level parent
In that case, the server can be the arbitrator
yh
The position in the inspector is, yes
Having no parent is like being parented to a transform with default position, rotation, and scale
so what did you mean by making the childs local spaace the same as the parents
i mean position
it's relative to the parents'
If your local position is [0,0,0], then your position will be your parent's position.
oh right
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.
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
how people tend to use single int to store multiple bools in it
everything in a computer is in binary
a boolean theoretically takes up 1 bit
an integer has a lot of bits
i know bitmask stuff but they quite annoying to work with
what about enums?
thought they purpose is for this
enums are just numbers with names
Sorry Idk if I got the terminology right but I mean like the guy hosting would be the deciding factor, like peer to peer hosting
enums can be used to give bitfields or layers names, but they aren't equivalent
enums are named integers . . .
so couldnt i bind name to multiple numbers?
in that case, whoever is the "host" would be the arbitrator
yes, but remember, an entire bitfield is a single number
for example 1 and 3 would both use first number
i have no idea what you mean by that
cant enum retrieve like this?
I cannot understand what you are talking about.
do you mean the first (rightmost) bit?
You can use an enum and assign each value a power of 2, then use bitwise operators to check for individual values
You can use enums like bitflags. Make sure to put the Flags attribute above the enum and set each enum field to a proper value.
some boolean info stored in first digit couldnt i retrieve same data whether its 1 or 3 or 7
yes
Yes that's how bits work
@late burrow This is what you want https://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c
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
and then how i overwrite it adding value to it
What do you mean "overwrite"?
you would not
Just add values to the enum the same way as is specified
You will still need to bitshift for this
Perhaps you should consider writing some basic methods that do this, bitshifting is not hard
or just bitwise OR, it sounds like you're thinking of?
So if you want to add a flag to an existing bunch of flags, you can just call the method
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
If you want to forbid adding Monday if you already have Sunday | Tuesday, then you need to write a method.
Generally I would use method anyway to add restrictions, as Fen specified
not forbid just bool setting without erasing data
So adding a flag? I don't know what else you would mean
You are not adding 1 + 2 = 3
yes its 11
Read this page.
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
i think that answers what i wanted
Right
will need to test still
you really don't need it
they're just numbers you're trying as a list of booleans
just the | thing really
you can just use the bitwise or directly
there's 7 bitwise ops, it's not that complicated
This page has a bit of code you can try: https://medium.com/@victorakwara83/bitwise-operators-in-c-and-how-they-are-used-a499cd89d194
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;
}
}
What is the purpose of bitmasks and stuff like that
operating with bitfields
bitfield & bitmask filters for the fields in the mask
bitfield ^ bitmask toggles the fields in the mask
etc
public variables are only accesible in the class its made in?
not through other classes right
For example, you have a set of options that influence your game (infinite ammo, god mode). You can specify a value on this and configure a general flag setting that specifies what options are enables or not, instead of having a separate setting for each
no, that's private
No, private
public is available to everything
private is the default as well, so if you don't have access modifiers it's private
but if you have a variable called health that's public, you cant just write health = 100 in another class
right, because that's out of scope
you would have to reference that class
so you could have two public health variables, the public just means you can make references to it from other classes?
class A {
public int x = 0;
}
class B {
void incAX(A a) {
a.x++;
}
}
Also, in networking bitwise operations are used a lot to pack data into packets. For example, using a single integer (32 bit number) I can reference 32 players based on a single true-false value.
yes
It's a lot better than writing 32 packets, for example
you're confusing "access levels" and "scoping", try looking those up for more info
yeah, thought they were the same
though i think it should work for bare ints too?
What?
it does
if i 5 | 2 it will be 7
yes
but 7 | 2 it will still be 7
This is not related to integers
cool i dont need enum then
i told you that since the start
i didnt liked idea of using >>
why?
it was really bad when i was making layermasks like that
Bitwise operations are on the binary level, so it is not related to integers. You can do it on floats and strings to.
it's much better than writing down powers of 2 as magic numbers
It just makes the most sense on numbers integers
you can't semantically
Point is that it's not related to integers
floats and strings have specific meanings in their binary arrangement, some arrangements are invalid
integers are just... integers in a different base, nothing fancy
That's why it makes most sense on integers
Ah like one bit is one Boolean kinda? So 0 is false and 1 is true?
yes, that's what booleans are
Still, it's not even that weird to do it on float values. Rounding, for example, is done by bitshifting
Yep
That's how it works
not on the entire value though
In my game I synchronize a state on 64 players using a single long (which is 64 bits) by cramping it full of booleans
also of course the legendary fast invsqrt
BTW, a boolean is actually 4 bits because it's a byte
Interesting, what are you storing?
So it takes some extra work
8 bits
In this case it is a zombie game and I need to inform clients of the state when somebody gets infected or cured for example
4 bits is a nybble
It's not actually Unity but same rules apply
1 sec
also technically 32 bits or 64 bits with modern architectures, though im sure that's optimized
Cool! I plan on adding online multiplayer to my fighting game, I suppose I could send inputs via a bitmask somehow
https://gdl.space/kohacutele.cpp SyncSpecies synchronizes to the client, "SyncSpecies_Client" is called clientside to unpack the incoming data and ClientSyncSpecies does the actual work
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
what, c++? it's had 64 bit integers since forever
This is not C++, the site merely assumes it is C++
Looks tough to deal with
oh, i see the script thing, yeah
what is that language?
(man i forget how that site does that...)
You get used to it, and it's pretty easy to deal with once you know the limitations
What network library are you working with?
None, this is the Zandronum engine
The language is ACS, updated with networking abilities. Looks like that technically makes the language 29 years old, although Zandronum exists since 2012
(meanwhile me using unsigned char[3] to get 48-bit integers...)
Oh right, I thought you were showing me a unity project lmao
Why would you need that?
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
optimizing memory for competitive programming
Something I've realised is that despite going above what my university asks for me I really don't know that much about programming lmao
My code is horribly written probably
I guess you can't store complicated information like vector3s in a bitmask or something though can you
Sure you can, just write three integers/floats
a vector3 is just a float[3] with some properties attached
it wouldn't be a bitmask, since you can't really condense it
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
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
Isn't decimal bigger than long as well?
it's 16 bytes, I want to say
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
What's arbitrary precision?
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
yeah it's just not IEEE 754 float
I clearly need to read up on some things
"arbitrary precision" numbers are variable-size
"however much precision you need"
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
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
there are things like "BigDecimal" in other languages
might have been thinking of that
yeah, java, definitely coming from that
base7 floating point when š
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
clamp the speed you pass to the rigidbody dont clamp the whole rigidbody velocity
I'll show you an example when I get home in a few
Tyvm, ill see if I can make it work, an example would be much appreciated š
Side note:
Is there any way to get the world axis vector?
Clamp the speed you pass to the
Rigidbody
// An example with only x axis being assigned
_rigidbody.velocity = new(Mathf.Clamp(newVelocity, velocityMin, velocityMax),
_rigidbody.velocity.y, _rigidbody.velocity.z);
Surely, you have to convert it
What's your current space?
how do i majke it so something happens when i press a sertain button? atm i have this but it doesn't work
Use KeyCode enum and specify the number after Alpha.
if (Input.GetButtonDown(KeyCode.Alpha1))
Also make sure you use a proper Unity Message, which is Update, not update. It's case-sensitive.
I wanna calculate this:
playerRotationPreCameraRotation = Vector3.SignedAngle([worldspace.forward], playerRigidBody.transform.forward, playerRigidBody.transform.up);```
Additionally, it seems like Visual Studio. Input should have another color. Configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
tyvm, i'll look into that once I got this world axis problem done š
ty but it gives me this error
What's [worldspace.forward]?
You'll have you show your code
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
That would be the world axis im looking for..
like the blue world axis š
I'm trying to get the angle between the world axis and said object
for the unity learn tutorials is it better to watch and then repeat, or do it while the vid is playing
My bad. It should be GetKeyDown, not mouse button
ty
first one
Watch, then repeat. Definitely
Get your IDE Configured
your editor should be underlining the errors among other things
alr, do i just click on the link here?
The world space axis is Vector3.forward, which is always (0, 0, 1). transform.local is the local one
yes
because im already using visual studio
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
Why doesn't Application.Quit() work? I have a Debug.Log("Clicked!") right above it, and it prints that, but the game keeps running.
doesn't work in the Editor
Oh thanks!
But it's not configured. You don't see the errors
Also not sure why I'm more concerned about the Input's color than the error
Hm.. I tried Vector3.forward earlier but that didn't work.. maybe my problem is something else.. or that I need to convert my localAxis into world space or something.. :/
yeah the color is off they have a separate theme thats why
appears correct but isn't. Methods are default yellow
I would be able to assist you further if you tell me the actual problem
it says the package is already installed
what does
this isn't clear enough, we dont see what you see
I don't think it's a separate theme. Visual Studio just doesn't seem to recognise Input as a class
@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?
this isn't even the important part
yeah I know its not configured but the theme is also different from the default I'm saying lol
Sure ā if you seed the rng with a consistent number, and then call rng in the same order everywhere, youāll get the same results
oh sorry didnt see the rest
yes make sure the workload is installed.
Regen Project Files afterwards or if its installed already.
you will see where the button is if you look at screenshots
make sure VS is closed while all this, after open script from unity
Go to
Preferences -> External Tools -> External Script Editor
Can you give random.range a seed?
Look at Random.InitState
int UnityEngine.Random.seed
But it should not be used
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) š
Use what Fen has mentioned
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
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?
Not sure why you tyvm, as I haven't even helped you yet, but do you have any actual questions now?
If I use a seed will it generate the same number every time? Or will it generate the same sequence of numbers
each call of an rng generates the value and the next seed, so you will get the same sequence
!status
:gear: Unity Services Status ā
Because this: "Vector3.forward" was the problem.. despite me trying that earlier it was wrong now..
Nothin rn, ill get back on that acceleration clamp problem tyvm! š
huh didnt even know command was there lol
I've just visited #854851968446365696 and wanted to check it out
oh right wop
is there a way to access newitem from chargeupdate
sorry if this is a dumb question
store it in a field
You mean access the newItem that is a parameter passed to InitializeItem?
If so, then Fen's got it
okay thanks
how can I load an image into a sprite from its png url?
https://stackoverflow.com/questions/31765518/how-to-load-an-image-from-url-with-unity
I found this but its a little bit old, is there an updated method to do it?
yes use the WebRequest one
UnityWebRequestTexture
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
the only thing deprecated there is the WWW class as mentioned in replies
also someone in #š»ācode-beginner who actually searched their question š®
you're already ahead of most..
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
Screenshot the error message, then.
this is how i call it
void Update() {
if (loaded) return;
if (data == null) return;
StartCoroutine(RequestImageFromURL(data.iconUrl));
loaded = true;
}
Ah, it's a webgl build
That produces more inscrutable errors
It looks like you wound up with a null sprite
is the url correct
the reason i thought the code for loading the image was deprecated or old is because UnityWebRequest is in that error at some line
have you tested this in the editor
I console logged the url and head to it myself on the browser it is infact correct
no, and i don't think it can be null sprite because the gameobject is an image and it does have a sprite
Im just changing the sprite to the texture from the url
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
yes, and that new sprite is probably null
@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?
how could the new sprite be null if the url works? could it be something with the UnityWebRequest failing?
to load it
you hash together all of the game state (positions, current actions, etc.) to get a checksum
This would just help you detect a desync
It won't fix anything
maybe the webrequest is failing to retrieve an image
set sprite fails if the image wasn't download
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
thats fine, i just want to detect when that happens. how do you make a hash like that?
well i think its another domain, i fetch images from discord
like icon url for discord members
nah it should work okay
but if they hosted local webgl that could be prblem
you could use https://docs.unity3d.com/ScriptReference/Hash128.html
uhm, im hosting it locally but tunneling it through cloudflared, that could be it?
I have my goofy
https://navarone77.github.io/navarone77/RandomImgWebGL/
that loads random Image from url
its a webgl build on Github idk if they deal with CORS differently
is this open-source?
Can you explain how that works? me dumb
how do you assign this "new(mathf.." to a Vector3?
oh forgot to post it but if you want to code I'll just give it to you
i just want the code for fetching the image off the web
that's just target-typed new
How do I make it a local variable??
and the one editing the sprite for the image
declare the variable inside the method
its using the TextureWebRequest method
Ill grab code for you one sec
Ooooooh tyvm im stupid, lol!
awesome, thank you! i guess each physics frame I'd create a hash and then create a list of these hashes and compare them as the replay plays?
I think so. let me double check, gotta find the project lol
take your time
ive been on this exceptions ass for too damn long man
Right.
webgl debugging is cancerous
public local š
lmao
haha yeah the wasm errors don't help.
Its should be working fine, i grab mine from an API of random images and download the url that way
the same method within the unity docs link i sent?
why does it not show the gun if i press 2?
because if you don't press 1 then it gets set to inactive wait i'm dumb ignore that
yes all CRUD requests can be done in unity with webrequest
Such as GET etc..
wdym
ahh I see you got your VS finally configured
Try logging InHand after you set it to make sure that code is running
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? š¤
i asked wdym on the origanal thing you said but then you edited it
idk how to do that, but i just found out that if i press 1 the gun disappears but if i press 2 it doesnt reappear
logging = Debug.Log
Debug log should literally have been the first line of code you wrote
Debug.Log should have been the very first line of code you wrote for unity
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);
}
}
well i didnt lol
there are beginner courses pinned in this channel. start there.
where do i put it in my code?
Then you are getting ahead of yourself and you should head to !learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
I told you where to put it already
i didnt but i already made a shooter game and im adding the feature to switch guns now so i want to finish this first
you do know there could be other errors than Connection Error don't you?
i will later
Then you're on your own because I'm not going over how to do basic logging
"i want to finish this first"
"i will later"
do you have absolutely any idea how many times i've heard that shit from people who refuse to bother learning the fundamentals? and guess how many of them actually go and do it?
yea i guess that could be it, ill edit my code
however, is there anyway to debug in webgl? all of the exceptions are obfuscated within the .wasm files
i will go and do it later but i don't have time to now since i have to finish this fast for school
Really quick question. What is the code or thing called between the {}. I forgot what it is called
well good luck then
you just debug.log as normal and the messages end up in the browser web developer console
codeblock?
depends on the scope
that's what im doing atm
is there any compile or build options to make it readable?
class X {} = class body
void Foo {} = method body
X() {} = constructor body
if () {}/while () {}/else {} = block
new X() {} = initializer block
thank you
wdym. Show an example
just use Debug.Log and log everything inside Unity Editor before doing webgl build
maybe they want to know the word "scope" which is what a pair of curly braces creates
Ohhhh thank you
@languid spire this is what i was asking about
see for yourself the exception
all of it is just referencing .wasm files
not my actual code files
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
Ah, you mean the stack trace. No, there is no correlation between your source code and the compiled wasm code.
So put in meaningful Debug.Log's which tell you where in the code you are.
most of my game code requires connection to the discord api to work, i cannot physically do anything in the editor with the project im on right now
I can try your URL if its not a private thing, to see if it works on my WEBRequest
i just added the debug and it doesnt give me anything back, what does that mean exacly?
that means its not runnig at all
oh well, it is what it is
afaik you should still be able to at least see logs in Webgl, don't they get browser console printed?
Debugging is an Art
it should be right? bc its in the void update
but it isn't reaching the if
did you put this script on an active gameobject
does it log when you press 1
let me check
so you're disabling the object the script is on...?
i just figured it out, so when i press 1 for some reason the entire script goes off
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
this is the entire script, it shjould only disable 1 section right?
you can't disable a section of a script
@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?
your script is on Gun. you disable Gun. that disables everything on Gun, including that script
technically they are right. setting it inactive does disable only one section of that. just the update method lmao
oh wait i think i used the wrong piece of code, i meant do disable the mesh so you couldn't see the gun, not disable the entire gun
wouldn't messages also not register
yeah correct I dont create the Sprite but if the texture is there your method should have no problem
first I would log if you have an actual texture there.
also FixedUpdate and anything else
whats the line of code to hide something so you cant see it?
there are no other messages in that code
in general though?
well yes, but i was referring specifically to the code they showed
but not disable the entire code
also Texture2D inherits from Texture so its a non-issue
you mean Renderer.enabled=false?
you would disable the mesh component then
or whatever you're using to render
idk 3d
idk, im very new to coding in unity
the gun can still shoot though
no bc of InHand
then go and look it up in the docs so you might actually learn something
just disable the entire wep object, dont put weapon switching on the guns. Simple
InHand needs to be true for the gun to shoot
inb4 "i will later"
why not just disable it entirely if you want to disable the gun as a whole
im trying to but i dont understand much thats written there so thats why im asking here...
i will try that and let you know
really is its that simple š¤·āāļø
bc i want to enable it later if i press the button to equip it
exactly, which is why you shouldn't have it on the gun
No, you are asking here because, time and time again, you have proven yourself to be too lazy to make any effort
wait im stup[id
the only script on the gun should be the weapon behavior itself.. not gun switching
no? i am just not that smart
Then it is simple, don't do game dev. Find another hobby
that's how you get smart along the way
thats what im doing, ive already worked on this for 10 hours in 2 days
... i like doing coding im ont just not going to not do it bc im not that smart, atleast ill try to code some stuff
start from the basics. Start with a simpler game first..
if you invest a few hours learning you can be 10 times more productive when you actually get to work
your first project is never going to be your "dreamproject"
i did
i made a ball rolling platformer game before this
all your first projects are gonna be crap until you refine your craft
not enough..
i know, im just trying to make my gun switching work
inventories are already complex within themselves
weapon switching involves inventory
im not making an inventory
player holds weapons, thats not inventory ?
gun switching
yeah that's an inventory
i just want it so if i press 1 or 2 that it switches gun
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
so you're only going to have 2 guns ?
maybe 3 but then ill just make it so they also hide when i press 3 to keep the code simple
but yea
so you realize that is an inventory right
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
no i don't ig
you have multiple things and you're keeping track of what thing is active
what a person with a bit more experience would do here use an array
you probably never used an array
yep
exactly, these are the basics stuff you would learn before doing an entire game..
i basically hit a wall here head first, unless the problem is with localhosting
since im currently localhosting and tunnelling
ok? i didn't know i needed to learn that first
i just started by trying to make a game
if only there were structured courses you could do that taught you the fundamentals of game development
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();
}```
ty, i changed this code a little but it works now
okay but thats just a band-aid. Just do a little bit more C# tuts , no one saying you should not work on the project but you cannot continue if the knowledge doesn't grow. You're gonna be stuck at the same dead ends
all the resources that you need are pinned in this channel
there also sites like https://www.w3schools.com/cs/index.php that are decent
alr
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);
}
}
first off - that's not a constructor body, that's just a method body
secondly, you put it too local.
movementDirection is used throughout Movement, not just in that specific if
That's not a constructor body but it has a condtion () and a scope {}?
Ohhh it's to local. How should I put it in movement? Movement doesn't have a body or block {}
a constructor is for constructing a class
condition
that's a parameter list.
what is professional practice when referencing between scripts and gameobjects
do people actually use tags
Movement doesn't have a body or block {}
it does
and find
You should usually use Components when not able to assign a field via Inspector. For example, you shouldn't really find the player by the tag if it has a PlayerController script
the usual..inspector imo
so dragging and dropping?
@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")
I'm not really following but I would mention that local variables usually need to be initialized before they can be used
So it would be Vector3 moveDirection = Vector3.zero
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
This value variable equals 0 constantly. It's supposed to equal 3 when the sensitivity variable equals 100, it is always returning 0.
Integer division, 3 / 100 is 0. Dividing two ints produces an int
Oh! Thats annoying, thank you!
It's intended behavior. Convert one of the two operands to a float (eg. 3 / 100f) so the division is made on floats
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;
}
}
This isn't a variable
You should make your class static, first of all
It now throws errors about needing an "explicitly declared constructor"
Well, how do you reference it?
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."
Have character calling a method in your non-static GameManager Singleton
I'm not that far yet, I'm for now just setting up the variables so I can grab and modify them later.
Copy-paste a generic Singleton from the web and derive your GameManager from it
Then create a scene in your GameManager, which manages the transition to the next Scene
I'll try...?
Got it a bit above too #archived-code-general message
I tried that and got these errors.
Why is Singleton<T> static?
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;
}
I've told you to merely copy-paste the Singleton from the site
You shouldn't have changed it to static
I didn't change anything except the name and type of the variable.
Haven't I just told you what you've changed that you shouldn't?
I copy pasted it like you said. All I did was replace the bool yourBool with int health
Alright, could you show your Singleton class?
Where did you copy this from?
This. This is my entire code.
I'm asking you to show Singleton.
From this: #š»ācode-beginner message
Looks like some built in visual scripting type
Oh, UnityEngine.VisualScripting.Singleton, I see
yeah, remove that directive
You should remove your VisualScripting namespace and copy-paste the full Singleton<T> code I've sent you above
why are hash128's serialised like this?
You'd have to actually create the singleton script like illustrated in the link
When pasting it in, it automatically adds the using Unity.VisualScripting;
Because you didn't create a class called Singleton
He said to copy paste the code. I did that.
I was defining it inside another method š¤¦āāļø
Copy-paste a generic
Singletonfrom the web and derive yourGameManagerfrom it
I'll try
Are we now going to argue about what I've suggested you?
Now this link has been sent 4 times already
It's the same link š
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.
Yeah, if you look on the messages above, this link has been sent twice by me
I have mentioned copying a full Singleton<T> class and deriving your GameManager from it
the visual scripting package has its own Singleton class, which is what's getting dragged in by your IDE.
If you open the first link I've send, you can figure out a bit more about Singletons from the conversation 1 month ago
You need to create your own Singleton class.
I tried asking ChatGPT what it meant but it made it more complicated, so I struggled to try to understand what that meant.
Do not use a spam generator to try to learn how to program.
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;
}
}
How is creating a script and copy-pasting the code from the site complicated to you?
I have to use it because people explain things very complicated, which I can't understand.
perhaps you could clarify what you don't understand
instead of just throwing your hands up
- please clarify what part you don't understand
- if you don't understand a lot, you may be in too deep; consider reviewing c# basics first
Well, I have literally told you to copy-paste the code from the site and create another class to derive from that code's class
Also, no, this is wrong
-
- How are you going to derive from an
abstractclass?
- How are you going to derive from an
-
- You can only have 1
MonoBehaviourper script
- You can only have 1
How are you going to derive from an abstract class?
normally
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
Oh, sorry, I have confused it with the sealed keyword 
I don't know what "derive from an abstract class" means, and I don't know where I put more than 1 Mono Behavior there.
Yeah, my bad. Mentioned above
Okay.
you don't put it there, you have to put it in a seperate file
Another MonoBehaviour should be put in a separated script that you create
make a file named Singleton.cs and put your Singleton class there
What does 1 public type per script mean? Surely, you can have several public types per script
Okay. And then I make a file called "GameManager" and put the project-wide variables there with the public class Foo : Singleton<Foo> thing, yes?
ah, im remembering that from java, mb.
yes
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!
It's 1:1 now
i mixed up Decimal and java's BigDecimal earlier today too, i can't escape java lmao
How do i take only the x?
can i bit edit without referencing like +=
without referencing
how are you going to change it then
i mean referencing twice
anyways yes c# has bitwise assignment operators
This is for the position not rotation so it didnt work
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?
read this too: https://unity.huh.how/quaternions/members
@swift crag i dont think im doing the hash thing right, could you possibly have a look? im only getting warnings lol
https://gdl.space/dilasajehi.cs
leaving it for tonight cus i dont wanna burn myself out
the point of the hash is to check that the game states are in sync
not the inputs -- those are a given
what so just the positions?
yeah, i thought the inputs could get out of position which is why i put that in the hash
but probably not actually now that i think of it
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
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.
could the order of appending stuff to the hash affect how it comes out?
you can't -- and there's no way you're getting such a precise framerate anyway
Okay. Thanks!
Just shoot for 60 here
Unity tries to wait for roughly the right amount of time, but it's not perfect
i dont think anyone would notice anyway
does the order of adding hashes affect the result?
that might be the problem then?
Ideally, each player shouldn't really care which character they control
i might be adding 1 then 2 in the first one, then 2 and 1 in the first one
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?)
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?
also, if you want to use randomness for anything that isn't synchronized, you'll want to create a separtae random number generator
Just once.
Thanks!
you can use System.Random or Unity.Mathematics.Random
okay, thanks! im using LinQ to order the lists, so maybe that will help
wouldnt positions and velocities have floating point precision errors which could change the hash tho?
As long as the calculations are deterministic, it's fine
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)
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
Does anyone know what to when a character controller's isGrounded value keeps alternating between true and false?
i just use a checkbox instead
that isGrounded thing has given me too much strife lmao
Wdym
the CC's isGrounded property is updated each time Move is called. if the Move call does not move it downward onto the surface of another collider then isGrounded will be false.
If you need something more precise than that, then use a physics query like an OverlapSphere, CheckBox, etc
what he said
i'm unclear how you'd using a "checkbox" to detect if you're grounded
Shouldnt this line make it work though?
checkoverlapbox lmao
ah
CheckBox
checkbox is technically right
parsed that as a ā
captialisation is important
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
in my charactercontroller, when i prress 2 inputs, my character moves faster, what can i do?
normalize the input
or clamp its magnitude to 1 if you want to support magnitudes below 1
Based on this the character controller is being pushed into the ground everytime move is called is it not?
how have you confirmed that it "keeps alternating between true and false"
I have Debug.Log(isGrounded) at the bottom of Update()
show the logs then
and maybe consider logging some other useful information like the movement vector
hashes match for the first 28 frames before it breaks lol
I'd make a class that stores all of the data that will get hashed
so that you can manually compare the states once it goes wrong
what like a list of positions and stuff?
@slender nymph could you help me out on explaining how to clampmagnitude?
okay will try that
did you google it
yes it was a little confusing
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
@swift crag did you check this out?
@slender nymph it seems to alternate like every second
inputDirection.Normalize();```
so do you plan to take my suggestion of printing some actually useful information or are we just supposed to guess at what is happening instead?
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.
can u give us the full script to look at !code.. use a paste-bin website
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
see above
it's a couple messages above that
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
The gizmo only shows up in scene view though when i clikc on the banana
that was an unrelated question, I think
Those remind me of Animation Rigging #š»āunity-talk message
one of his original questions in #š»āunity-talk
ahh it could be animation rigging
Thats what i thought at first but the issue persisted when i deactivated the animator
the animation rigging stuff is its own component
it relies on the animator but the gizmo's arent from the animator
@slender nymph is there a better way to paste the logs than snipping tool?
but thats a non-issue.. ur ground check is the main issue
not really, no