#💻┃code-beginner
1 messages · Page 699 of 1
yup
are you like doing all this last minute 🤔
Made the script a component of an object, then passed in the object and grabbed the component
so in the inspector ?
Yes. Grandmother got injured, very minor but at her age everything is major
ohh alr.. teacher didn't want to give you extension time ?
Let's see if it works now:)
feel like there is a group of uni students doing everything last minute currently we just had another person that was talking about it being their uni assignment
nnope. cause the semester ends toda
+1 Last minute is the way
IM SORRYYYY lfmao
All my courses so far are 2 months, I do everything the last 2 weeks lol
Can I not like, do this on the editor? Do I have to make a script for that?
had a coworker complain to me cause i called my classes scripts 😅
think I removed it, give me one more sec
Like, the whole point is, I wanna keep it simple, not use a script, that's why I am using the legacy animation on these and not an animator lol
its almost giving nigel thornberry 😄
Thanks
OK LAST QUESTION FOR ME YALL
so i have it such that the pause menu is an additive scene
is that the best idea? who knows but not important
I have the system like this, where theres a variable set to 0 at the top
that way you cant spam pause and create a million pause menus
but now, when I unpause and puase normally, the pause menu does not show up again
you load a scene for when pausing? odd
correct
but rn it gets the job done
is there anything that would cuase this behavior?
this is the pause trigger
its also where i stop time
cause what behaviour?
I pause and resume, everytihng is fine
but when i puase a second time, the pause menu never shows up
though time does freeze
not sure i don't use scenes for my pause menu also isnt common to do it this way
Are u like.... loading the pause menu as an additive scene???
yes
Why???
cause i dont have time for a better solution rn
That's like way more complex than it needs to
That's probably the worse solution you could have
wouldn't doubt if they have a few minutes left for this project :/
Just pack the scene that is the menu into a gameObject, place it on the main scene and toggle the object on and off when pausing and resuming
yup, thanks for the advice!
got it in after a bandaid fix
dang grandma tripping like 3 days ago 😭
/j to be clear
I wrote the code gay instead of say
hello everyone, is this where i ask for help?
yes
ok i'm new to unity. i have an issue with player movement, i have two scripts controlling 1) Basic Movement left and right 2) Jumping. How do i get the movements to be able to be pressed together? example press "D" and "Space" together
do they not already work like that?
(why not a bool for this though btw. still not good, but still better than an int)
Hello everyone, how are you all
sorry if i dont respond after this, im gonna be out for a bit but ill check suggestions when i come back. Thanks alot 😄
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
your movement script is resetting y velocity to 0
your jump script is resetting x velocity to 0
change both to only modify the dimension they actually care about
Can i ask a question in here ? its about the camera following the sprite
screenshots are fine
yes
just add current vertical velocity to your move script and current horizontal velocity to your jump script
text is much better, period.
!screenshots
!screenshot
ah, which command is it...
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
I'm stuck with getting my camera to follow the sprite without turning, I moved the camera out so its not a child of the sprite and added a script i found on google but when i add the sprite to the script the camera background covers everything in the scene with the background colour
is the camera perhaps getting flung off the map
god this is even worse, see the code command above
Sorry im very new and dont know what the code command is
this
programmers trying to read code without brainrot syntax highlighting
O i thought screen shots were ok
Also, just use cinemachine, it's worth learning as in most cases you'll end up making your camera logic more complicated in the future anyway
i don't need the syntax highlighting, i don't even get it on mobile
i want it as text
You sent a message directly after a bot reply saying not to send them
if you have nothing of value to add you're free to leave, quartz
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform Player;
public Vector3 Offset;
void LateUpdate()
{
if (Player != null)
transform.position = Player.position + Offset;
}
}
thank you
couldn't this logic in particular just be having the camera as a child of the player? or are you planning to add more logic in the future?
truthfully im not sure
what about the second question
im trying to jsut get my sprite to turn without the camera turning as a input movement
what do you mean by turn?
what have you set offset as
is that supposed to be a gif, or...?
so at the moment the camera changes direction but the spaceship always points upwards
screen shot of the game
ok, so you didn't actually answer my question
so you cna see the stars moving underneath the sprite but the sprite never turns
youre sure camera isnt a child of the sprite?
so your player is rotating on z?
I did the new movement in unity (atleast the tutorial said it was new )
you are not answering my question
just to be sure you havent got the movement script attached to the background right?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField]
private float _speed;
[SerializeField]
private float _rotationSpeed;
private Rigidbody2D _rigidbody;
private Vector2 _movementInput;
private Vector2 _smoothedMovementInput;
private Vector2 _movementInputSmoothVelocity;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
SetPlayerVelocity();
RotateInDirectionOfInput();
}
private void SetPlayerVelocity()
{
_smoothedMovementInput = Vector2.SmoothDamp(
_smoothedMovementInput,
_movementInput,
ref _movementInputSmoothVelocity,
0.1f);
_rigidbody.velocity = _smoothedMovementInput * _speed;
}
private void RotateInDirectionOfInput()
{
if (_movementInput != Vector2.zero) {
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
Quaternion rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
_rigidbody.MoveRotation(rotation);
}
}
private void OnMove(InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
}
}
and this is on the player, correct?
yes sir
check
that is why youre here
The offset is set to 0, so your camera will be directly on top of the player?
wouldnt be a very good code beginner channel if you werent welcome
should fine for orthographic projection
I can change the offset but i was doing a topdown not a isometrical view , does that matter?
set it to 0, 0, -10 see what happens
you're working in 2d, so you'll be using X and Y and ignoring Z
what x/y represent is dependant on the perspective, but it'll still be x/y
z issue fixes rendering issue, not rotation
[when adding] the script the camera background covers everything in the scene with the background colour
Rotation was never the issue
I took a moment to think about this and i understand now the problem
I needed to back teh camera up above my scene so it could see it
Thats right ?
yes
as vertx and Chris said camera only sees whats infront of it
Hey in my top-down game I'm trying to make it so when I hit this enemy it goes in the direction the player is facing (the player is facing the mouse btw). The first method is for when it bounces off of walls which works and the second one is when it gets hit which doesn't work, it usally makes the enemy's velocity slow waaay down. Any help is appreciated
how/where is lastVelocity set, also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
private Vector2 lastVelocity
in the class
this is the declaration, where do you set it?
private void LateUpdate()
{
transform.rotation = Quaternion.identity;
rb1 = GetComponent<Rigidbody2D>();
if ( rb1 != null )
{
lastVelocity = rb1.linearVelocity;
}
}
🤨 where is TakeDamage called from? specifically via what message
also you should cache or serialize the rigidbody instead of getting it every update
public class Weapon : MonoBehaviour
{
public float damage = 1;
private void OnTriggerEnter2D(Collider2D collision)
{
NormalEnemy enemy = collision.GetComponent<NormalEnemy>();
if (enemy != null )
{
enemy.TakeDamage(damage);
}
}
}
(and there you should use TryGetComponent, but we can worry about that later)
wouldn't you want to set lastVelocity in FixedUpdate so it syncs with the loop cycle where the trigger happens
can you Debug.Log the mousePosition please? how does it look like, you are using a Vector2
I think it is the x,y coordinates of where the mouse is positioned in the world
bc the camera follows the player and it was a different value after moving
yeah ScreentoWorldPoint is a Vector3 in world space
ah so I can't use that with Vector2?
you can but you need to also define the z axis , maybe manually
apparently input.mousePosition is already a Vector3
it is but only with 2 values
yeah this
I want that though right?
am I misunderstanding this then?
its stored as a vector3 but only the x and y have anything afaik
yeah z is unassigned
is that a problem? I'm not rly messing with the z axis
do I need to set it to 0 or something to fix it?
scroll up and see what i said
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane // or some hardcoded value as you wish;
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
Debug.Log(worldPosition);```
this will give you proper values, first you assign the mousePos than you feed that into the ScreenToWorldPoint
thank you 🫡
I imported the first person and third person starter assets, how can I make it such that I keep the armature but have an fps cam and third person cam?
I have a script that switches between the cameras, but everytime I try making an fps camera a child of the armature head bone, the movement and looking around gets very wonky
Or is there a way I can duplicate the third person camera put it in front of the head and have it look and move like a fps?
create an empty gameobject at very top of the player hierarchy and attach the cam to this gameobject
Attach the thirdperson cam to it?
yes
So duplicate it yeah?
you can duplicate camera there is no problem, at runtime you can just disbale and enable them
Which ones would I duplicate?
i have no clue which one you want to duplicate, it is your game
This is from the Third Person starter assets
looks like you are using cinemachine
Yes
i´d suggest you ask your question there instead #🎥┃cinemachine
Hi! I'm coding an UI bar for entities that looks at the camera. Currently I did everything but I can't get it perfectly horizontal in respect to the camera
That's a screen. Full health bar, correctly facing the camera, but not horizontal
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
void Update()
{
if (showCooldown > 0)
{
healthBar.SetAmount((entity.health / entity.maxHealth) * 100);
healthBarObject.transform.position = healthBarPosition.position;
healthBarObject.transform.LookAt(
healthBarObject.transform.position +
(healthBarObject.transform.position - playerCamera.transform.position)
);
showCooldown -= Time.deltaTime;
if (showCooldown <= 0)
{
healthBarObject.SetActive(false);
}
}
}
That's the code I'm using to rotate it towards the camera.
(only the LookAt row actually).. How can I fix that?
Quick question how you make a boss fight in 2d side scroll game like blasphemous or somthing like in cuphead
Is the health bar in 3d or 2d? LookAt uses all three axes to look at the camera. Usually, you'd use UI for the health bar as it will always face the camera correctly, and track the object position to update the health bar . . .
The same way you'd make a normal bad guy that isn't a boss. Decide what you want it to do, and then implement the behavior.
3d
the health bar is an object spawned in the world. I used this approach because using an UI element would require instantiating the health bar in the main player canvas, which is not easy to reference
Anything is easy to reference, you might just be missing some knowledge in your toolkit 😄
why not use world space canvases
Why do you have to instantiate it in the player canvas? You can choose which canvas it belongs to . . .
so you get ui in the world
I'm using it in the prefab
Ideally they might actually want 2d for this, no?
hold on i think im missing context
I spawn all my enemy health bars in their own canvas so I can hide them, if necessary . . .
yeah, it's not in the game manager, and it's also a pain to handle when the enemy dies (I'd have to delete it) and for other behaviours. Most of the tutorials I found use what I'm using.
The main difference between a Player's Health Bar in the HUD vs an Enemy's is creating the Health Bar in WORLD SPACE.
In stead of overlaying UI on the Camera, the Enemy or Game Object itself has a Canvas attached to it as a child object, and the UI is a part of the Enemy GameObject.
The benefit of this is the Health Bar follows the Enemy aroun...
like this
clicked that embed and got ai keanu reeves ad im gonna kill myself
You can use more than one canvas
as I said, the bar has its canvas in the prefab
You should be using 2d instead. When an enemy is spawned, instantiate a UI health bar and pass it the enemy information . . .
LookAt a position means it's rotated to that position, the center of the camera
you need it to look at the plane of the camera, ie its own position projected onto the camera plane
this tutorial is for a 2d game where there's no rotational depth, its not directly applicable to 3d games
well another one (https://www.youtube.com/watch?v=cUQVLgohAjY) does the same, and it doesn't align the health bars
Learn how to make Health Bars that stay above the heads of units in World Space!
A common need in games is to show Health Bars over some enemy or unit. In this tutorial we'll take a look at one way to achieve that in a way that enables us to retain the benefits of sliced and filled Sprites.
I also discuss some of the "gotchas" that you may enc...
as you can see from the thumbnails
yeah?
im confused what you mean by this, could you elaborate what change you're proposing
They're just saying using 2d for the health bars would be easier since they already face the screen correctly . . .
that doesn't tell me anything new
yeah what do you mean by "using 2d"
this is all in a 3d world, no?
how am I supposed to just "use 2d" in a 3d world
i mean it was a response to you suggesting a world space camera
using 2d would not make them face the camera, they would face the XY plane
the object has a canvas, it doesn't seem like it's doing anythig. As far as I understand, it's because the object with the canvas is still in 3D
it's making me render image components, but definitely not fixing the problem
ah, you mean a screenspace/overlay canvas? yeah that makes sense
though it'd also mean all health bars would be the same size regardless of distance
its not a great idea perf wise to have many world space canvases for some health bars btw
...isn't there a way to just rotate the already existing bar correctly?
hm, why not? isn't the cost of a canvas from dirtying/rerendering them?
so having it all in a single canvas would make any health change/position change dirty the whole thing, no?
everything works flawless but a single rotation
yes, i told you
yea but I have no clue how to do it ahaha
yes and we cannot benefit from things like gpu instancing as they are all difference meshes
batching can't be applied to multiple canvases
then ask instead of ignoring it lol
better if they are all the same mesh + shader doing the health bar for batching benefits
sorry, was focussed on all other comments too
If it was done in one screen overlay canvas instead that would be a better option too (ideally its own canvas/sub canvas to not dirty other parts of the ui too)
tl;dr many canvases for a health bar in world bad
no batches?
@naive pawn by using 2d, we mean, using the UI canvas, not a 3d object . . .
so, the player's UI where there's all the other stuff? As I said, this makes every other aspect harder, from instantiating to removing the health bar
If its done in screen space UI it means you have to update their positions yourself (world > screen) but its cheaper perf wise
@naive pawn how do I do what you said? It seems like nothing I do is working
Ideally ideally theres like shader shit you can do for tailor made situations right?
Like instead of talking to unity ui just drawing to screen yourself
im not sure if there's a more direct way to do this, but here's one way (should work afaik, but untested)
do WorldToViewportPoint on the transform position
set depth to 0 on the result
do ViewportToWorldPoint on that
look at the result point
well yea you can just draw them via code with something like DrawMeshIndirect() if you want. works well with batching too
The bar is tilted as before (I forgot to invert the camera position so it's actually backwards, that's why it's grey)
ehhh I'm just gonna go with the boring and problematic UI solution if I can't tilt that bar, at this point it's easier to do that..
hmm, am i understanding this correctly?
- updating a canvas element dirties the entire canvas, can be modularized with canvas groups
- dirtying a canvas is expensive
- multiple canvases updating is worse than the same elements on the same canvas?
a canvas component can be used inside a root canvas to have smaller groups that can cause redraws
canvas graphic drawing uses batching so many health bars using the same textures/material should get batched together
this is why many single world space canvases in scene is shit
ah, i wasn't really familiar with batching
Unity themselves recommend not having 1 canvas with everything in it and using canvases within to split up things
so separate canvases are much worse if they have the same assets, because that means batching doesn't happen?
does that also apply with 2 canvases that don't use the same assets?
I thought it was normal to use multiple canvases and keep the ones that constantly update in their own to separate from static UI . . .
Yea that is right:
Main canvas:
- text
- text
- sub canvas
-
- health bar
-
- health bar
My understanding of how canvases draw makes me think its not possible to ever batch them because it should be assumed that each canvas has unique content
frame debugger will answer these questions anyway, i know it will batch within a canvas (e.g. 20 images using the same spritesheet/sprite with similar draw order)
ah i think i misphrased my question
i mean between these 4 scenarios:
A1: 2 canvases both using asset X
A2: a single canvas having 2 instances of asset X
B1: 2 canvases, one using asset X, the other using asset Y
B2: a single canvas with asset X and Y
if both X and Y dirty the canvas, batching makes a difference between A1 and A2, but not between B1 and B2, right?
or i guess, batching will apply to A2 but not B2?
I think only A2 will batch
well, that was a lot of words for a simple answer
i really need to get better at phrasing my questions lmao
its a bit confusing. I just checked something in what im working on rn and 3 world space canvases with the same content are not batched but is in a "render sub batch" group
doesnt behave like when multiple graphics are batched in 1 draw call
using Mono.Cecil;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float AnimBlendSpeed = 8.9f;
private Rigidbody _playerRigidbody;
private InputManager _inputManager;
private Animator _animator;
private bool _hasAnimator;
private int _xVelHash;
private int _yVelHash;
private const float _walkSpeed = 2f;
private const float _runSpeed = 6f;
private Vector2 _currentVelocity;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
_hasAnimator = TryGetComponent<Animator>(out _animator);
_playerRigidbody = GetComponent<Rigidbody>();
_inputManager = GetComponent<InputManager>();
_xVelHash = Animator.StringToHash("X_Velocity");
_yVelHash = Animator.StringToHash("Y_Velocity");
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
if(!_hasAnimator) return;
float targetSpeed = _inputManager.Run ? _runSpeed : _walkSpeed;
if(_inputManager.Move ==Vector2.zero) targetSpeed = 0;
_currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
_currentVelocity.y = Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
var xVelDifference = _currentVelocity.x - _playerRigidbody.linearVelocity.x;
var zVelDifference = _currentVelocity.y - _playerRigidbody.linearVelocity.z;
_playerRigidbody.AddForce(transform.TransformVector(new Vector3(xVelDifference, 0 , zVelDifference)), ForceMode.VelocityChange);
_animator.SetFloat(_xVelHash , _currentVelocity.x);
_animator.SetFloat(_yVelHash, _currentVelocity.y);
}
}
Does anyone know why when my character moves he slides around and the proper animations don't play?
The sliding is because you're using Lerp to change the velocity over time
As for the animation - I would check the console to make sure there are no errors. Aside from that i'd run the game with the animator window open to see if the parameters are being set properly.
Thank u man ily
How would you go about using the console to check if animations are working?
As I said you would use the console to check that there are no errors
that's step one
Wonder why people love lerp :?
it's all they know and every hare-brained youtube tutorial uses it as a quick bandaid
I followed a tut, my 2nd day on Unity 💔
What's the superior alternative?
Nah fair not hating just curious cause I've never seen it work for character movement here
If you want direct analog control without extra "acceleration", you shouldn't be using anything - just feed the input directly into the velocity (with some scaling factor)
lerps and slerps are still solid
but you learn other things like SmoothDamp, MoveTowards, etc
all kinda have their own use-cases
and then theres Tweening Libraries (DoTween, LeanTween, PrimeTween etc)
may want to look into those at some point
Thank u, very insightful
tweens can use "curves" and they have built-in functions for almost everything related to unity
positioning, rotations, scaling, UI positioning, single values, colors, rigidbodies, and the list goes on
i used to animate everything.. like a door that opened -> animation, a ui panel that faded in and out -> animation.. it wasn't until i was told to be cautious about animating my UI that i discovered it.. and for simple animations theres no better alternative imo
How/where can I store changing data?
Context: I am creating a game involving autobattle heroes. Each hero will have items equipped. Each item will have mods that can be changed through crafting. I am thinking of storing mod information as scriptableobjects, as mod information shouldn't change. I am a bit stumped on how to store the item information, as the mods on an item can change through crafting (e.g., rerolling a mod value within a mod-defined range).
I am hesitant to use monobehaviour because the items aren't really interacting with things in the game - they're more like data containers that are themselves stored in the hero they're equipped to or the master inventory.
But i am also hesitant to use scriptableobjects, which according to what i've seen online, are static, so shouldn't be able to store changing data.
plain C# class
a json file or xml would do it too
Will the plain c# class need to be instantiated on a gameobject each time I generate a new item? or can i simply generate a new Item and store it like a variable in a hero/inventory?
you can just store it in a list in your inventory class yes
or hero class
I feel this would be inefficient especially because of crafting during runtime - i envision changing the item multiple times a second during crafting, wouldnt it be inefficient to store it as a file? i would probably store it as json at the end of session
in short
First time I visited ECS
namespace Game.Player {
unsafe partial struct PlayerMoveSystem : ISystem {
void OnUpdate(ref SystemState state) {
foreach ((RefRW<LocalTransform> transform, RefRO<PlayerData> data, RefRO<PhysicsCollider> collider) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<PlayerData>, RefRO<PhysicsCollider>>()) {
float3 moveDirection = new float3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection *= Input.GetKey(KeyCode.LeftShift) ? data.ValueRO.RunSpeed : data.ValueRO.Speed;
moveDirection *= SystemAPI.Time.DeltaTime;
if (math.lengthsq(moveDirection) < 0.0001f) {
continue;
}
//moveDirection = transform.ValueRO.TransformDirection(moveDirection);
PhysicsWorld physics = SystemAPI.GetSingleton<PhysicsWorldSingleton>().PhysicsWorld;
ColliderCastInput input = new ColliderCastInput {
Collider = collider.ValueRO.ColliderPtr,
Orientation = transform.ValueRO.Rotation,
Start = transform.ValueRO.Position,
End = transform.ValueRO.Position + moveDirection
};
if (physics.CastCollider(input, out ColliderCastHit hit)) {
float3 normal = hit.SurfaceNormal;
float3 remainingMove = moveDirection;
float3 slide = math.normalize(math.projectsafe(remainingMove, math.cross(normal, math.up())));
transform.ValueRW = transform.ValueRO.Translate(slide * math.length(remainingMove) * (1f - hit.Fraction));
Debug.Log($"collision");
} else {
transform.ValueRW = transform.ValueRO.Translate(moveDirection);
}
}
}
}
}```
Why the hell does the player yeet into the void when pressing A or D?
#1062393052863414313 for ECS related issues
Thx)
I am making checkpoint system where the player enters the checkpoint trigger it should save the players position to the spawn point and the kill player collider should teleport the player to the spawn point. I have 2 scripts one will handle saving the players position to the spawn point and the other will teleport the player to the spawnpoint
I was wondering how I can save the players position to the spawn point. here is what I got so far https://paste.ofcode.org/36Es8rH7jccPk5pmKDgFvb5
right now if I enter the checkpoint trigger it will teleport the player to the spawn point which I want but I only want it to teleport when I hit kill player collider
You immediately assign the player position to the spawn point (that's why it moves right away). You should store the current checkpoint (if it's a MonoBehaviour component) or the spawn point Transform as a separate variable, like currentCheckpoint or currentSpawnPoint.
When the player dies, assign the player position to the currentXXX variable . . .
Basically, you only want to store the spawn point position when you reach the checkpoint, then use that position to set the player there when they respawn . . .
what like currentCheckPoint = spawnPoint;
Yep . . .
so in the other script thats attached to the kill player collider should I do
_player.positon = currentCheckPoint.position
this is what I have for saving the checkpoint https://paste.ofcode.org/GMJiDbkCg85FXy4XMgVj6B
when I try to reference the currentCheckPoint.position it doesn't recognise it.
If you have many Checkpoints this wont really do anything useful
It should be that the checkpoint script updates something on Player so it knows what the latest checkpoint is
then on death it can check if its not null and move position to the checkpoint pos
how should I do it? Imm gonna be having more checkpoints later on
yea i said the same thing?
the checkpoint script should do something like:
[SerializeField]
int order;
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out var player))
{
if (player.checkpoint == null || player.checkpoint.order < order)
{
player.checkpoint = this;
}
}
}
then in your player script on death you can do transform.position = checkpoint.transform.position; (if not null)
like this?
yea. Ideally it would be done via a function on TeleportPlayer but looks good
I just tried it and it doesn't work
er actually your second picture shows a logic problem
the "checkpoint reference" should be stored on the player object
the death area trigger can tell the player to move to the last checkpoint
what like create a separate script that has the reference and attach it to the player?
up to you. If you have a main "Player" script to handle stuff like this it can go in there:
void UpdateCheckpoint(Checkpoint newCheckpoint);
void RespawnAtCheckpoint();
should I put this in the update method?
no its just an example of the functions you could make 😐
This is soo confusing if I were to put the functions in my script what would I say in them? im just getting random errors
checkpoint script > https://paste.ofcode.org/3aZficUCFqXQ9j8tTeTzWFZ
Teleportplayer > https://paste.ofcode.org/QfakNcNR5UJ893nBiRmqyB
I feel like you are way over complicating this
public class Checkpoint : MonoBehaviour
{
public int order;
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out var player))
{
player.UpdateCheckpoint(this);
}
}
}
public class Player : MonoBehaviour
{
private Checkpoint checkpoint;
public void UpdateCheckpoint(Checkpoint newCheckpoint)
{
if (checkpoint == null || checkpoint.order < newCheckpoint.order)
{
checkpoint = newCheckpoint;
}
}
public void Respawn()
{
if (checkpoint != null)
{
transform.position = checkpoint.transform.position;
}
}
}
public class RespawnArea : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out var player))
{
player.Respawn();
}
}
}
have a complete example
plz try to understand the flow of logic as you seem to have a hard time understanding
This is still over complicated
its really not
Right but you could do this same thing is less
Meaning it's over complicated
This is what I deem to be good design so you do you
Also your player class doesn't have a variable for order
how is TBOI's random generative rooms work? because it's not fully random so it's not picking from a pool of enemies but it's random enough to not be the same every time
yes there is a mistake in there, fixed
Does anyone know how to get past a hidden code system
konami code
sudo rm -rf *
What?
Ask a stupid question get stupid answers
there is literally nothing over complicated about this. this is about as basic as c# gets.
I was just wondering how to get past a software that is blocking me from seeing how there code works
Yeah, as I said, stupid questions get stupid answers
But it wasn’t really an answer
you'd want to maybe ask in a place related to this game. this isnt really unity related. sometimes games have docs that describe how their features work
It also wasn't really a question
How was that not a question?
Provides zero information and is fundamentally unanswerable
You could have just asked for further explanation.
Nah this way's more fun
hey im trying to make a top down rpg game and im pretty new to coding so ive mostly been following tutorials and stuff but im having issues on how to make enemys attack where the player is like for example playing the attack down or up animation depending on where the player is. is there any tutorials or information about this?
Ok so it was all rage bait 👆nice 😏
if you're new, your first project should not be rpg
there isn't going to always be a video for how to do this and that, it takes years of experience
which part do you struggle with? which part exactly of the attack are you trying to implement
Try starting with coding movement if you have not already or coding item mechanics
yea ik but im keeping it pretty simple just to learn the basics
well for example flipping the hitbox and playing different animations depending if the player is up or down and just figuring out what the most efficent way to code it is with out running in to problems later
I am decently new and I was wondering what coding software I should use
i dont know what you mean with "depending if the player is up or down". up or down relative to what?
also you dont need to manually flip the hitbox. have it as a child of some object in your character and itll move around along with the animations.
Before you worry about doing this efficiently, first worry about doing it once. there isn't really a way to do animations more efficiently, at the end you're going to be interacting with the animator component anyways. You would typically just want to be interacting with it through one central script and thats fine enough
you mean which !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
• :question: Other/None
You can still use visual studio no? The first option when you click on the manual install for visual studio is for mac
It says visual studio code not just visual studio
What?
https://learn.microsoft.com/en-us/visualstudio/releases/2022/what-happened-to-vs-for-mac
For the most secure, up-to-date experience, we recommend either Visual Studio (Windows) or moving to Visual Studio Code on the Mac.
Those are the available coding software. You'd pick one from the selected where the first two are the same but simply different installations.
They can still install visual studio just it wont get updates https://learn.microsoft.com/en-gb/answers/questions/2236094/visual-studio-for-mac
Thanks
When my rigidbody player steps on uneven terrain, say a slope, or jumps on a box, he starts rotating jitterely on his own in turn causing my camera to rotate. Anyone have any ideas? Does this sound familiar?
It doesn't sound like a beginner coding question
It's my first person camera/movement script
sending the !code might help
but also yeah i'd reccomend making a post #1390346827005431951
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
why not?
Did you fix it?
How do I properly parent items to a player joint without a weird rotation and pivot point , so they tem can look proper with my animation
What is it exactly youre trying to achieve?
because if it's specifically this box, I'd say you need a box carrying animation.
No, I'm about to post in code-general 💔
Anyway If you do get that specific Box Carry animation I'd go for a dedicated carryslot.
So basically an empty gameobject where you place the box instead of setparent, you get some control over where the box spawns 🙂
also I would cache your meshcollider component.
I posted it
We need some more information on your movement.
how are you doing movement? Character controller? do you have animations that do physics.
I posted the script here
i have the animation. What I mean is when I parent it, I want it in a specific position, but I don't understand Unity transforms properly to position it the way I want. In the code, I'm setting the parent to my rig prop joint transformation, but the crate is under the floor when parented and with rotations.
its because you dont change the transform, you just set the parent.
so the box is being dragged through the ground
you can do SetParent(transform, false)
(you can overload the method, if you do not the worldPositionStays param is set to true)
asset store
does it cover all the movement of a car ?
I bet you can find insane assets on the asset store that do that.
ok thanks for the info i have never searched in the asset store
Any idea for VS ide resizing this area? it automatically went wide
Oh not every feature could be re coded in Unity?
im not sure how you got that from what I said. I meant that you're asking a unity server about how a very specific game writes its logic. It's incredibly unlikely that anyone here knows, and even if they do, this would be better in a forum/server dedicated to that game
I bet it can be recreated, but I also think not a lot of people know what game you are talking about , thus dont know how it would work.
ooooo you mean the binding of isaac.
bawsi is correct but here's a few general pointers on that kind of thing,
re: floor design i'd take a look at this https://youtu.be/Uqk5Zf0tw3o?t=97
for items, consumables, enemies etc. i'd assume they use spawn pools that consist of a list of weighted rarities
weighted rarity is a lottery esque random system where a given option has a amount of lottery tickets and the random selection is done by randomly picking one of those options
eg. lets say a given floor type had a enemy spawn pool of
CoolGuy1 | 4
CoolGuy27 | 4
MomsHand | 1
RarerCoolGuy4 | 1
the total spawn pool has 10 choices it could randomly pick from. Weighted rarity pools are used a lot in these kind of games because you don't neccarily need to adjust all the options values whenever you add or remove something, you just need to give whatever your adding a value thats relative to all the other values
Can i update .assets files from previous game versions to current by myself?
sounds like modding stuff which we dont help with
once a project is built thats it
opening an old project in a new version will prompt to upgrade so its all done for you
idk if this counts as coding but how would I actually make this show the texture?
I've tried it in both 2d and 3d
I'm trying to follow a tutorial (this is just an example they gave to start out with) but they don't explain this
you need to hook the output of your multiply node into the Base Color node in the Fragment Stage
(in the top left)
thank you so much that took way too long
I spent hours trying to figure it out before I remembered this server 😭
(I might be stupid)
Yes haha
Well it doesn’t have to be specific to that game I’m just asking about the logic in general in terms of Unity functionalities because I only learned the Unity game engine
Unity doesn't really offer any specific ways to help do that stuff
This is exactly what I wanted thank you so much❤️ super interesting!
It’s logic you’d have to create yourself then I assume?
Well as long as it’s possible haha
Anything is possible 😄
if you're asking about the generative rooms specifically then yea you'd ideally want to look at resources online. it seemed you were asking more so about that game and the part about "it's not fully random ... but it's random enough" which isn't possible for us to answer
I did a prototype with spawn handling but it was a mess and got too laggy, not sure how games manage to have 100s of entities without lag, are there special mod tools for Unity you’d have to install for it?
your using the term mod in a way that probably gives that message a different meaning btw
short answer is kind of skill issue respectfully aha, there's many ways you can improve that kind of thing
if you get back into that "mess" feel free to ask about it when you have specifics to show
I see so it’s a very specific case for that game, I’ll look further into the specifics thank you❤️
I meant like maybe a Unity package that is downloaded into the project kinda thing
It’s a very simple spawner objects that pastes prefab instances into the scene
yeah package/asset/template more applicable term there, only nitpicking because you'll have an easier time finding them with those keywords
And it gets very laggy, I basically re created one of those fake ad games where you shoot hoards of enemies
Well in that example is it the spawning of the enemies that is laggy or what the enemies are doing once they are spawned? Both can be problems
They are just walking forward but I assume because each has a movement script to find the player and move towards him maybe that causes the lag(?)
Because it runs hundreds of scripts
game obejcts wasnt meant to really handle 100s of characters with their own logic. there are optimizations you can try to make, possibly using jobs, though this isn't beginner territory at all
especially if this is mobile
Ohh I see, so it’s more complicated Unity functionalities
Yeah so overall the problem is when you do things at scale, the cost of doing certain things is going to matter a lot more right. So there are many, many ways to improve this kind of thing that usually fall under
- Doing things less
1.a. - Doing things less by caching values in order to avoid "expensive" code when you can
1.b. - Doing things less in a literal sense, eg. if your enemies are constantly checking something (maybe a path to the player) don't do that every frame, do that every x frames or something - Doing things faster - Just Unity/C# ways of doing the same thing in a more optimised way
- Doing more at the same time. - By default a majority of Unity code runs on a single cpu thread. You can kinda compare this to someone with 1 arm working a busy kitchen, at some point the bottleneck is just how much the chef can do. Using pretty advanced programming knowledge you can mess with stuff like burst, jobs and ecs in order to multithread your code in order to utilise many threads, but there's a lot of considerations on how to do that
Ooo I see! Thank you both for all the information super useful!❤️
I’ll look into all the suggestions
I didn’t know it runs on only one thread, is there a way to utilize more?
with scary code like jobs as bawsi suggested, it's probably not going to be the first tool you bring out
Ohh that’s what jobs do!
you're pretty limited to what you can do on other threads iirc
like i dont think you can access most of the unity api on another thread
hordes of enemies moving towards the player is something jobs can mess with pretty well though right?
How do companies make AAA games on Unity with only one thread?😅
i dont use anything advanced like this so i dont really know. I just remember seeing guides out there that did do this
some use #1062393052863414313 which are quite advanced. some dont start off by designing their game around having 100s of enemies
you'll see a lot of games really dont have that many enemies at once, for a reason
Ohh right offloading
Yeah I haven't touched any of it directly yet but I read up a tiny bit last month and it's actually way less intimidating than i thought
Does it kill game objects when you offload areas?
And if so are you able to save their state so when you load them again they remain in that state?
I have a UnityEvent esque class named ExtendedEvent that wraps an action and I want to make a kind of middleman class that allows strangers to listen and unlisten but not invoke, any suggestions on what to name this kinda class?
use a interface
expose only the interface that can sub to it
and only invoke on the concreate type
a kind of middleman class that allows strangers to listen and unlisten but not invoke
This is how regular C# events work
or just use C# events
Can't they choose to cast into the full thing though? I did see thats how ireadonlylist works though so i might be missing something
Yeah but i like my wrapper
sure if they have access to the type
What goal are you trying to solve? Absolute security or just a convenient API?
it could be internal or private
also they prolly wont
so its fine
also C# events literally do this
just use them
convenience more than anything but I wouldn't mind just a little bit extra security
if interfaces are the objective answer here i can live with that
you can't toss around words like security with no context
(they brought up that term)
no matter how you do it, people can still blow past any guard rails you put up
I'm very aware
but you can expose something via interface even if its own protection level is lower
which would stop casting to it
still not going to stop meta programming stuff like reflection
Yeah
if you use an interface though, something will have to implement this interface along with the event. I don't really see the point of it. unless im misunderstanding they just want a class with a private unityevent inside, with an add and remove listener class. Though I dont see the point of this either
public ITriggerable<Transform> OnTargetChanged => _onTargetChanged;
private readonly Triggerable<Transform> _onTargetChanged = new();
is how most would do it via interfaces
like mentioned depending on your needs the concrete type could be internal or private
but it only really effects ergonomics and intent of how its used, can smash through that with reflection easily
truthfully this just seems like a waste to do. you have to use this custom interface/class/whatever everytime instead of a unityevent just to protect yourself against calling Invoke on another object. If you were working with someone, you'd also have to convince them to remember this as well. Nothings stopping you from using a unityevent directly 3 months in the future because you forget about this class, and making this whole thing pointless
theres really no need to protect yourself from this, in the same way you dont need to protect yourself from the fact any code right now could call Application.Quit or Destroy every single object in your scene for fun
Forsure, I just wouldn't have minded a lil' bit extra. If it doesn't work out that's life 😄
I hear you on concerns about it being a waste of time but i've used my one personally quite abit and im happy with it
we chilling
am just confused by you saying security
but yeah for custom implementations like what i showed a few nice things can be added in, like the one at work we have instead of unsubcribe methods you just returns a IDisposable on subscribe
which can be nice for only being subbed for a certain scope, or nice simple by just putting them all in a collection on sub, then disposing them all in this objects dispose method
dawg
the downside to not using event is other people will likely not clue into there being a other implementation to use
what does it mean when you say security in a context like this
that you want to be sure what can and cant be called or changed externally?
the only non interface way i can think of is a little awkward as well since its just abusing closures and would involve making a method that returns both the thing to sub to and a method that invokes through it
it doesn't really mean anything. Just compiler-enforced prevention of something
but anything like that is easy to get around if someone really wants to
I was basically wondering why the person cared if someone could cast the interface to a concrete type.
a class with a unity event and a public AddListener/RemoveListener method is what i imagined they have
rather than a class inheriting from UnityEvent
yeah i almost never use actual unity event
same, I got lost once really badly when my main menu was connected entirely via unity events and decided it was better to just do it through code
to me its just overhead and they really only have benefits if you are using mb's or so's everywhere which is often not that case
idk
yea wtf
cant enter my project
lucky im already in mine 😎
ima be honest 15gb isn't much for a unity project
dont give a fuck if its big or not
lmaoo
ok buddy go take a chill pill if your gonna be pissy
pissy?
🗣️
instead of giving proper info youre here having a dick contest
yzaka u funny bro but people around here are very serious just dont get yourself kicked or nothing
not like you've given any context as to why you can't enter your game, plus this is the code channel not the unity project not working go to #💻┃unity-talk or something not here
@sour fulcrum context i think idk
your just getting the wrong vibe i think ngl
idk some people are just eh
im getting this error when trying to sign in in unity hub
yes
nah they just agree that youre getting the error
yes
Unity Services's status page provides information on the current status and incident history of Unity Services.
for anyone who helped me re: event stuff i went interface pilled eg.
[System.Serializable]
public class SelectableCollection<T> : ISelectableCollection<T>
{
private ExtendedEvent<T> onSelected = new ExtendedEvent<T>();
private ExtendedEvent<T> onUnselected = new ExtendedEvent<T>();
private ExtendedEvent<T,T> onSelectionChange = new ExtendedEvent<T,T>();
public IListenOnlyEvent<T, T> OnSelectionChange => onSelectionChange;
public IListenOnlyEvent<T> OnSelected => onSelected;
public IListenOnlyEvent<T> OnUnselected => onUnselected;
im happy enough with this
hmm weird stuff
tried restarting pc but still the same
tbf, that site can be a little inaccurate sometimes. issues can take a few minutes or a few hours to be reported
im trying to do mp stuff on the cloud, i am getting the same error.
well if youre also getting it then its probably on their side
that's why im here, looking to see if i was alone.
The fact you are also getting it reassures me.. although i wonder if i caused it.
engineers screaming your name
..i mean i blame them, they gave me the free 'credit' to spend
guess it wasnt free after all
C# thing, not a unity problem, but I REALLY REALLY REALLY REALLY wish there was a way to say "All declarations between HERE and HERE have THIS set of attributes"
I just felt the need to complain about that
real
i might be remembering wrong, but I think it works when you declare variables together of the same type.
like int a,b,c;
though yea that doesnt seem to apply much in your case
You are remembering correctly, I use that all the time.
Is it possible to make my game object to only sense collision on the frame it was made?
on the frame the object was made or the frame the collision happened?
the frame it was made
i wanna use the collider when its made and then use it for other purposes on other frames
just to specify
If it's not possible I can find another way, but it would be easier for a built in way
Might be better to use a physics query, no?
If you really need to, you could store the frame number in awake, and then disable the collider in update on the next frame.
surely you are in the wrong server
@humble rain There's no off topic here. Thanks.
where do i ask that kind of question ?
Not in this server, that's for sure, being that it has nothing to do with Unity development.
oh, i see
Hi
Anione can explain me how I can make move control for the player 2 in my scene with the new input system
I am creating a simple pong and I need to move the player 2 with your specific 2nd console gamepad
when I move the player 1 the player 2 is moving too
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/PlayerInput.html
#🖱️┃input-system can help with further questions
I am looking at the screen for a while trying to make a not shitty solution to this. So I have all those stats that can be added as stats from the gear and I want the UI to go over all of them and display a text showing those that are not 0, but I am not sure how to do that iteration/loop to check them all. Should I just manually go 1 by 1?
Or should I try to make them into a list somehow, even tho they are diferent data types?
You could make a Stat class that contains a string for the stat name and a float/int for value. Then create a list of these stats.
I kinda have that already, but I'd have to refactor all of the above???
One could also use reflection, but I wouldn't generally suggest that for runtime code
Yeah, also thought of that, fast to code, but rather slow to run
yep
This is gonna be update whenever a the selected inventory changes
well you basically wrote it in 2 different ways. You have this defined StatAttribute and then did not use it to define the stats in the class above
might be a good task for AI
Kinda the same, yeah
I was not intending to iterate over those when I was making the stats tbh
Just to each value add the extra value from the modifiers
id consider even just having a Dictionary then of <Stats enum, float>
anything that wants to access a stat is forced to do so by its enum
all of those could be floats realistically
Pretty much any number I am using could be a float I guess
But I just went for the "this value can NEVER have decimals" route
i guess depending on the game design it could get awkward. id still try to keep it as a float and round it when its used, if thats required.
Realistically I should kinda just use this for everything, but it would take some significant changes now considering how many stuff is referencing that and how different it would be
the main thing I wonder is how you're using that StatAttribute in the first place
is there somewhere that uses a switch statement from enum and manually affects that class.health?
And it's not like a 1 to 1 conversion, some attributes don't even show on the "Stats" enum; since I need to use some "in-between values" on the stats to do the final calculations and all that do not show there cause they were intended mainly just to use for stats that are displayed
The use they were made for is to basically show in here when making gear, so I can add stats 1 by 1, instead of having a whole list of all the stats when they are gonna just use like 1-4
The GearManager takes that on a switch and converts it into the appropiate stat and adds it to the total
But the GearManager is indeed just having all stats on it straigh up
Having some stats locked into ints make it so even if I wanted to pass a float I could not, so it's kinda of a remainder here
yea thats what I was wondering. unfortunately the best thing here would be to refactor but tbh it shouldn't require other systems to massively change code. Are you by chance directly referencing gearManager.health and other values in other scripts?
Well, basically the final stats of the unit is going over each stat, adding the base, modifiers and gear and get the final result with that, so yeah, they are being referenced
the refactor would be easy if you had methods exposed to handle the logic you want. A TakeDamage method where GearManager handles subtracting from its own health would mean your entire change would be
// in gear manager
public void TakeDamage(float dmg)
{
// health -= dmg;
statsDictionary[Stats.Health] -= dmg;
}
but now if you move this health variable to a dictionary, a lot of other scripts are going to have errors
or even like a GetStat(Stats myStat) method would save from all other scripts referencing the actual floats
Well, the thing is like, health is not even a thing?? Like, health on the stats enum is basically refering to maxhealth, since health on itself is not a stat, really
The stats on the unit calls that "currenthealth" instead, and is not modified by any stat
then make it a value in the stats enum
So it's kinda convoluted to change
either way that doesnt really affect the concept here, refactoring would be easier if you dont directly reference the public variables. now that you consider putting them in a dictionary, everything breaks
if you really cant refactor it due to an absurd amount of changes, in your initial problem, id suggest write the code one by one because this wasn't designed to be iterated over
Yeah, like I think I would get more issues than solutions refactoring tbh
I am not even sure if it be technically better, maybe easier to code, but, would also make it kinda more complex and messy?
Like basically I think I would get like genuinely hundreds of errors changing how stats are referenced now lol
I feel like you could get away with some slight insanity here if you really wanted to refactor this. Like in GearManager (is this your stats class?), create the dictionary, then change currentHealth to be a property.
currentHealth => myDict[Stats.CurrentHealth];
then rename it using IDE to follow proper convention
Ah, well, no, GearManager just stores the stats comming from the gear rn
Then the class Stats, should handle them comming over to calculate the finals
nah it would definitely be better. right now it feels like you're inbetween both worlds where you reference a stat by this enum, but they're also referenced directly in the Stats class
i mean, what you're doing can work, but you already see that its not possible to iterate through
I also have a separate class that is basically a copy paste from stats that is BonusStats, that is basically any modifiers from stats that do not come from gear, I placed these appart so I could reset any bonus directly if needed
i think i have pretty similar code to what you're doing here, though it is a bit odd that you handle the death logic there. I can show how the dictionary works here
Yeah, but cause honestly, when I was placing stats, I was not thinking at all about the iteration, it only came to mind when I had to start making the UI and displaying them
Honestly, the only real reason why I would prefer an iteration here is cause I want 1, to not show stats that are not being modified by gear (aka = 0), and 2, I want stats that are going into the negative to display after the ones in possitive, so just going 1 by 1 is kinda more messy than anything I was doing with those prior
void OnTakeDamage(DamageDealt damageDealt)
{
float newHealth = damageDealt.postDamageHealth;
float maxHealth = playerStats.GetCurrentStat(StatDefinition.MaxHealth);
float percent = newHealth / maxHealth;
ChangeImageFill(percent);
}
the only thing that changes is that I call a method to get the stat I want, rather than directly referencing it. you could've also implemented it this way from the beginning where it goes through that switch statement you mentioned. So your code would be some stats.GetStat(enum). The refactor from a bunch of fields -> dictionary would only change the implementation of GetStat
you still could do what I said above to make refactoring easier by changing what currentHealth is, making it into a property. You wouldnt need to go into other classes to change it
So, I would add that into the stats enum?
Feels kinda weird, considering that should not actually show in many of the things that are using it
Like what, can I now add "current health" as a gear attribute?
well for currentHealth specifically thats up to you, idk what you intend to do there. I actually do have currentHealth in my dictionary of stats
for other variables like maxHealth, the same concept still applies
i get what you mean where nothing is stopping you from doing this, but really this is something you would just avoid because you know it doesnt make sense. The same way that nothings stopping you from inserting 1000000 for your movement speed.
Gear as in.... items that are wearable /affect the player, right?
there are benefits though, like if we think of a "health potion" vs "mana potion". you wouldnt want separate code where both do the same logic, but are different methods because one needs to reference stats.currentHealth or stats.currentMana.
this could just be an enum exposed to the inspector and consolidated into one method
idk how i forgot to mention this. the main purpose for the dictionary is that you can "choose" a stat via the inspector, since enums are serialized. So if you had an object which buffed a stat, you just choose the enum in inspector, then pass that enum when interacting with the stats class
Makes sense but... I don't think it works on how I am doing things actually
Like for modifyig the stats, it would be useful to just select the stat as enum and add a value, but the managers need more data from that in most cases
Like for example, if it's a buff, it needs to know stuff like it's stackeable or how does it stacks, so it kinda needs to be of spefic class for that???
I think I could maybe refactor that too, if I try hard enough
Maybe I should???
Not sure
It's possible using scriptableobjects as kinda enums here might be a nice solution
depends on if that additional data is per gear type (enum option) or per usage of the enum
Currently not intend into making anything "usable" or "consumable"
Like at all
Could be cool, but no, I am trying to avoid that
you misunderstood what i meant by that
im not sure how this is affected from what im saying. the change im suggesting is that this Stats class should just use a dictionary<enum, float> and thats all. nothing else would need this dictionary
your buffs could stay exactly as they are
No, no, it would not affect that, I mean it would not really make me in this case make less classes, I think
it shouldnt affect anything at all
I still don't really get what you mean actually
infact if you do the cursed suggestion i said above of making all the current floats into properties, all the other code could stay the exact same
if you need more data in the enum options (eg. if a given enum option needs some int that says how much it could be stackable), you could use scriptableobjects in place of the enum
tbh i dont think scriptable objects solve anything here compared to enums
if there was some additional logic you needed to attach to this, then maybe, but that is also fine to just throw in a switch statement in the stats class.
A property like, an enum + value as you were saying?
I, could yeah, would kinda be in the same place tho? Maybe I am getting this wrong
i really dont like that im even suggesting this, but its purely to not break every other class. it would just be something like this
public class Stats
{
Dictionary<SomeEnum, float> myStats = new(); // plus logic to populate this dictionary
public float currentHealth => myStats[SomeEnum.CurrentHealth]; // or => GetStat(SomeEnum.CurrentHealth)
public float GetStat(SomeEnum myEnum)
{
return myStats[myEnum];
}
}
also typed it on discord incase theres some error i dont see
then you could right click in IDE, rename currentHealth to CurrentHealth to follow convention for properties and itll update everything for you
So basically whenever I reference current health, it just gets me the value on the dictionary that is asocaited to the same enum and I can basically just get a stat with the method to do the same with any
I see, I see
I see what you meant now
Yeah, that sounds reasonable
tbh it's not even bad to do with properties here, but its just not what i'd do. you will have a lot of extra properties
because its not just currentHealth. it is everything that you showed in the initial screenshot
Yeah, there are a lot of little things than I am likely gonna miss and break everything lol
well with what im suggesting, you dont need to touch any other class yourself
everything is purely within this Stats class
currentHealth gets changed to a property so everything referencing it still works. Then IDE renames it for you
I am right now just considering how much better it would be going forward if I just do it that way, to see if it's worth the hassle
Mmmmm... not sure
how can i change material properties from script
i want to change offset on unlit texture
actually, one thing i just realized is it will break if anything tries to set currentHealth from outside. you shouldnt be doing this anyways, but still thats something i didnt consider
you can get the material through the renderer, then look at the docs for Material and search for "offset"
https://docs.unity3d.com/ScriptReference/Renderer-material.html
why i need to find it? cant i just serializefield it
The renderer has and uses the material
Also to clarify on my last message, it would work if you had a setter for the property instead of only the getter as i wrote. Then youd also want a SetStat method
Player is falling forward like a mannequin when I try to move it forward by pressing W but instead of moving in that direction player just falls in that direction? Is this due to I am using 3D box collider?:
Codes:
private Rigidbody player;
private void FixedUpdate()
{
Vector2 moveInputs = mobileInputs.Player.Move.ReadValue<Vector2>();
float speed = 5f;
player.AddForce(new Vector3(moveInputs.x, 0, moveInputs.y) * speed, ForceMode.Force);
}
make sure you've frozen rotation appropriately
Put Rotation constraints on the rigidbody
x and z, usually
hey guys was messing with tilemaps and was wondering if it was a bad practice to put 2 tilemaps on the same "tile" or not?
was also trying to understand what this does, searched online but i still dont fully understand it
- question doesn't really make sense
- not a code question
oops
ask in #🖼️┃2d-tools, and could you clarify what you mean
tiles go in tilemaps/tilesets/grids, not the other way around
alright thanks
i'll answer the composite thing there too
Can anyone look at this?
I want the loop in AnimMain() to run forever, and after thats done, the next command is executed in AnimRoot() which called AnimMain(). both IEnumerators.
But currently, AnimMain() only runs once and nothing after that.
I pasted the script twice to put it in a window like this
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
so you cannot look at it that way at all...
let me correct it :3
using UnityEngine;
using System.Collections;
using JimmysUnityUtilities;
namespace NSMB.UI.MainMenu {
public class MainMenuTitleAnim : MonoBehaviour {
[SerializeField] private RectTransform titleMain, titleSub;
[SerializeField] private UI.Elements.GIF titleGif;
[SerializeField] private float latency = 0.00008f;
private float temp = 0.0f;
IEnumerator AnimMain() {
while (true/*temp < 0.5f*/) {
titleMain.SetPivotX(temp);
float prevTemp = temp;
temp += (latency* Time.deltaTime);
Debug.Log($"VAL: {prevTemp}=>{temp}, {titleMain.pivot}");
yield return null;
}
Debug.Log("Anim End?");
}
IEnumerator AnimSub() {
titleSub.SetPivotY(-2f);
yield return null;
}
IEnumerator AnimRoot() {
temp = -3.0f;
yield return StartCoroutine(AnimMain());
yield return new WaitForSeconds(0.2f);
yield return StartCoroutine(AnimSub());
yield return null;
}
void Awake() {
StartCoroutine(AnimRoot());
}
}
}
we can (on desktop), but it'd be better with the ideal method as given above
(the pastebin sites would be better for large blocks like this though fyi)
to run forever, and after thats done
how do you expect this to work, exactly?
if it runs forever, it's not gonna be done
which... isn't being used
ok so right now it should run forever, but it's only running once?
yep
so you're only getting the VAL: log once? or are you also seeing the Anim End? log?
what's telling you that it's running once, exactly
unity is compiling scripts
it was so much better when that happened in the background in 5.x...
(used that ver once)
VAL: -3=>-2,999998, (-3.00, 1.00)
That didn’t change
you still haven't answered this
are you getting the Anim End log
again, nope
bruh i asked you 2 questions before and you said "nope" once LMAO
make sure you don't have collapse enabled in console
any errors or anything else? have you tried putting logs at the start/end of the loop?
A tool for sharing your source code with the world!
imma run this
right i had to go
imma run it..
For some reason i am only getting the VAL thing and none of the other prints, which makes no sense
you're not getting "Alive" or "Done"?
nope
and unity also flags the yield return null in the loop as unreachable now
why would a debug log stop that iteration
well, either you're not running the code you sent or you're filtering the debug logs somehow
AH YEAH ive been upating the wrong file the entire time, gotta test around
having issues with player collision, when i get close to other objects and tap a movement key the player character bounces off the other objects
but holding it down just has the player "phase through"
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public Transform cameraRig;
public float dashForce = 8f;
public float dashDuration = 0.1f;
public float dashCooldown = 3f;
private Vector3 currentDirection;
private bool isDashing = false;
private float dashTimer = 0f;
private float dashCooldownTimer = 0f;
private Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
HandleDash();
}
void FixedUpdate()
{
HandleMovement();
}
void HandleMovement()
{
if (isDashing) return;
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 inputDir = new Vector3(h, 0f, v).normalized;
if (inputDir.sqrMagnitude > 0f)
{
Vector3 forward = cameraRig.forward;
Vector3 right = cameraRig.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
currentDirection = (forward * v + right * h).normalized;
Vector3 targetPosition = rb.position + currentDirection * speed * Time.fixedDeltaTime;
rb.MovePosition(targetPosition);
}
else
{
currentDirection = Vector3.zero;
}
}
void HandleDash()
{
if (dashCooldownTimer > 0f)
}
}
this is my player gameobject set up
i have an additional gameobject for rendering a sprite and a camera as a child of this
the actual sprite is being billboarded so i assumed that might have something to do with it but apparently it does not
If anyone wants to do my question:
Alive
AnimRoot Start.
Anim Start.
ANIM VALUE: -3=>-2,999998, (-3.00, 1.00)
Done
is my output
(scroll up)
Change continuous to discrete
same thing
in fact i changed it initially from discrete to continous thinking it would solve it
the fact that you can sort of bounce off of the wall makes me think some kind of collission is happening
but for whatever reason continous movement seems to just disregard it allowing you to walk through
tried it on different kind of colliders as well and you can walk through pretty much anything no matter how big or small
Oh wait dont use Time.DeltaTime for rigidbody especially if it's in fixed update
hmmmm for some reason
changing interpolate from interpolate to none
makes it work 🤔
Odd cause I've been told when watching videos that it just makes the movement visually smoother
but im using fixeddeltatime
not just deltatime
well without it the collission works but uh yeah its less than smooth now
Idk it's what the others here say :/
This works properly and loops if i remo remove the yields in AnimRoot(), but its not running in the background, and rather stopping the main thread......
But yeah, i want it to work separately
what no, this advice is for AddForce specifically
also deltaTime is the same as fixedDeltaTime within FixedUpdate
MovePosition doesn't respect collision and isn't suitable for player movement.
So whats the better alternative
set velocity or add a force
The easiest to work with will be setting the velocity
Does c# have a dictionary that behaves like the one in c++?
C# has a dictionary yes
Not sure how the C++ one behaves exactly but they're pretty much the same in all languages
If you have some specific difference in mind, please specify it, not all of us use c++
map in c++ is a sorted map/dict, c# has OrderedDictionary iirc
Dictionary in c# is a hashmap/dict/table, what unordered_map is in c++
structures in different languages will be implemented differently and will not act exactly the same
consider what functionality you actually need and go from there, instead of trying to find a direct equivalent from a structure in a different language
OrderedDictionary is .net 9+ though so not available in unity
very few structures in c# will behave like c++ analogues because c# doesn't have copy constructors 😛
I feel like we're getting ahead of ourselves
The basic contract here is key/value mapping presumably
its a little different, in c# you need to initialise the values before being able to use it.
in c#, you must call Add first before being able to use the values
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages.Add("Bob", 24);
but in c++ you can just use it directly
map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 24;
Ah makes sense
(yeah im just trying to say - actually ask that instead of trying to get an equivalent)
you can do that in c# too
You mean you need to create the Dictionary, yes.
this just.. isn't true?
You can use the [] syntax in C# as well
My use case is a bit niche in that I want to
Dictionary<string, Action> actions = new();
actions["money"] += moneyAction;
But calling actions["money"] += moneyAction; calls NRE
does it? i would assume it says the entry doesn't exist instead of an NRE
Oop yep I meant the entry doesnt exist
but yes keying into a dict does not default-create the element like c++ does
I was thinking that in c++, it would instead treat actions["money"] as an empty Action that would just allow me to add to it
yea i wanted that default creation method
yeah c# just doesn't have that concept in general
I mean, that's a pretty minor difference
(not really, it means upsert is given for free in c++)
I see, I'll find another way
If statements exist.
TryGetValue exists
The difference here is really in the fact that Action is an object that needs to be created
If it was a struct it would be equally free
generally for [non-c++ language] you would check for existance and then choose to add or update, or default-create the entry and update
it's only c++ that has the default-init behavior afaik
no? you'd still get an entry doesn't exist error because the issue is with the key, not the value
Yes if you blindly try to access it instead of using TryGetValue
Im working on implement a save file system to my game, and i want each save file to be accompanied with a little screenshot of the game, for better readability. How can i take a screenshot & save it to file? Additionaly, i'd love for the screenshot to be in a different aspect ratio from the game itself (4:3, instead of the game's 16:9)
the save files themselves are .json
Render a camera to a RenderTexture. Googling it should give examples
...which is the exact situation we're talking about? value and ref types just don't make a difference here at all, no? you can still do += on a null delegate
i've used render textures before, but how would i save it to file?
what's the current issue?
so it's not ending the loop, it's just... not continuing
which kinda sounds like it not being passed to StartCoroutine, but it is...
this
so yield just stops all coroutines smh
funnily i have a GIF script using ienums and they somehow work
well yes, but it's supposed to continue in the next frame in the case of yield return null
i made that before this tho
yield wait not stop, otherwise it would break
and it loops if yields are removed from animroot
but it currently works with the update function either way
Should I use a Pool to reuse my bullets or should I just instantiate them when needed?
always good idea to use pooling for bullets , they are always instantiated and destroyed and can save you lots of GC operations
Hey yall, so I’m new to unity, and am making a project for digital twins, I wanted to ask are there any good tutorials or materials I can refer to? I do use chatGPT, but after a point I’m not able to make it work
How can I get the value of the angle between a Raycast and the normal of whatever it hits ?
Unity documentation is pretty useful, they also have a bunch of tutorials on their site, as for videos you oculd check out Brackeys, he's pretty good
Oh cool thanks
some like this maybe ?
var incomingDir = ray.direction;
var hitNormal = hit.normal;
float angle = Vector3.Angle(incomingDir, hitNormal);```
thanks i'll try that, just gota figure some stuff out beforehand
ok. depends also what u want to do there might be a few more alts
Yeah just gotta get the angle that's all, so I can check for slopes since I want to add sliding
Works well, thanks a lot
I just had to quickly research how raycasts work cuz I couldnt get the "hit" variable to work
Ya learn somehting every day
whats the easier simplest way of making an on value changed for a bool? and getting the old value and the new value
Another question, the blue box is the Ground Check, and I set it to turn off the gravity on the rigidbody if it's grounded, only problem is, when I jump on the cube's edge for example, the rigidbody still kinda bumps off and slides down. I want it to stay at the exact same height it's at when the gorund check first collides with the cube, I tried manually setting the downward velocity to zero if it's grounded and it didnt work, any ideas ?
probably with properties
no reason to provide the old value for a bool though lol
did you like, also remove gravity? also you have an error in console, that may be related
That error has nothing to do with it dw, and yes I do turn off gravity as soon as the capsule is grounded but in this case it still slides down a bit before settling like in the image i sent
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
why are you resetting the angular y velocity
that's how fast you're yawing
motion is linear velocity
oh bruh, that was a typo, lemme change it to linear and see if it works
changed it but the problem persists
if i jump further on the cube and walk backwards until the Ground Check barely makes contact there's no problem, the capsule only slides down If jump on the cube's edge directly
let me take a screenshot to make it clearer
-# a literal edge case
how do you make your text small or big
we love some edging
you mean in discord or in unity lol
Discord 🤣
As you can see the capsule still says at the same height if I jump correctly on the cube then slowly walk backwards, but if I jumped now from the position shown in the images, the capsule just bumps off the edge of the cube and falls , that's what I want to remove
Forgot to specify
it's extended markdown
# h1
## h2
### h3
normal
-# small
```the small version is a discord specific thing, and generic markdown goes to h6
you can google all this though
not sure what i'm looking at in either of these images tbh
which one is the scenario with the issue, and what exactly is the issue? (i'm not seeing it)
Try turning off gravity lol
Already did that
the issue is this image, I basically want the bottom of the capsule to stay on the same height as the surface of the cube, when I jump on the edege of the cube, despite it making contact with the Ground Check, the capsule still slides down or even bumps off of it even though gravity is turned off
the capsule is frictionless, I removed the frictionless component from it and it seemed to kinda reduce the problem, the capsule wasn't bumping off the cube as hard
have you tried debugging and going frame-by-frame to see if the ground check and velocity reset are perhaps happening after it slides down or something like that?
i don't think friction would matter too much here, what about bounce
Can you turn off ground check? (I don’t use unity often I have only opened it once and understood nothing and was overwhelmed)
Why would I turn off the gorund check ?
I'll try recording it and sending it here
Maybe it is pulling it to the ground because it thinks it is hovering over the ground
And doesn’t like it and jerks it to the ground
Managed to record it
Look at when i'm already standing on the edge of the cube and try to jump
you should probably stop suggesting random stuff if you don't understand anything about it lol
Uh it was worth a try
snapping happens with depenetration
what's depenetration ?
When you slide off the edge is when you try to jump
this moment, right? where it's falling and the ground check kinda falls through the block a bit before the gravity disable kicks in
Yup how can I prevent that from happening ?
i'd guess that's just gravity being faster than the physics tick rate, rather than any issue with your code
you could make it snap up to the surface, but that might be jarring
or i guess gradually move back up to the surface
but if you want that behavior, why not just use a boxcollider
Couldn’t you also just make a hit box for the player
there's already a hitbox, it's the green wireframe
Try making the hit box bigger than the little oval
bruh thanks, box collider fixed it, ig it's my bad for making a cubic ground check for a capsule collider
if it's still a capsule collider it wouldn't really change the behavior
it'd just make the effect less
i get that you're trying to help, but if you have no idea how anything works, you just aren't really going to be able to help
if the normal boxcollider collision works for you, you should be able to remove the antigravity/velocity reset stuff too
Idk I was just thinking that like Minecraft has a bigger hit box than the actual player model and it stays on platforms
no, it doesn't
Huh
just, in case that ends up having accidental effects on stairs or moving platforms or something lol
the minecraft player's hitbox is a cuboid shape, that's why it doesn't slide. and minecraft doesn't have slopes.
the model protrudes out of the hitbox in some areas.
He doesn’t have slopes so I thought it would help I was not thinking in future
there's a slope check in the code
Oh i didn’t see that
nothing personal against you, but really - if you don't have the background knowledge to actually understand what's going on, your suggestions are just unnecessary noise
That was very personal against me
I have this issue where when the player "dies" and its trying to teleport the player to the spawn point this happens (watch the video)
Script : https://paste.ofcode.org/cXXV74g3pbWsB5kFhQDP6x
If you have to say that then it is going to be personal
the point they're trying to make is still true. you haven't shown any signs of having knowledge related to unity, just general game dev. if you want to actually help here than understanding the engine is an entry level requirement
I don’t know where to start learning
Ok so it removed the issue of the ground check slightly sinking into the cube, but the bounce is still there that's what bother me. Imagine jumping right on the edge of a crate in CSGO, and then jumping again while on it without moving a single step only to get knocked off of it the moment you land
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
That hasn’t helped me at all
it applies to any beginner trying to help even though they don't have the knowledge to actually present useful suggestions
right, so that would be the depenetration thing probably
Mind re-explaining what that is ?
I can still present ideas that may end up being helpful
is it basically the engine's physics acting before my code can disable gravity ?
you can, but are you? most of them won't be, as demonstrated in your attempt
so basically how physics works is it's gonna step work out where stuff will be after velocity has been applied, then figure out what stuff is inside each other, and then try to make them not be inside each other
so gravity might make the player and the box intersect like this for a brief moment, then physics will figure out - hey, those 2 things collide, they shouldn't be in each other, and then it'll push the player out of the box (or vice versa, dependant on dynamic vs static and mass and stuff)
i guess what is happening here, is that due to the player being on the edge, it ends up looking like this - the physics system looks at this and thinks the easiest way to depenetrate is to make the player move out instead of up, which is technically correct, just not what you want
Ah i see, is there a workaround for that or is my only solution switching from a rigidbody to a character controller ?
(or the physics system just pushes them directly apart and that ends up being out. idk the specifics)
well a CC would most likely give you more control over this, but im not sure if you can solve it with physics, it might be possible
Alright then, thank you so much man, I might have to switch to a CC then, it's annoying cuz i'll have to implement stuff like gravity myself but i guess it's worth giving it a shot, I appreciate the visual explanation
i'll just duplicate my movement script and make the copy work as a CC so I can still go back to rigidbody if i mess anything up
seems like this is... not a particularly easy problem to solve with physics
imo this isn't too egregious and would be a lot of effort to switch to CC just for this change, but power to you if you decide to fix this
an alternative would be to i guess extend the ground check to snap to the ground better, but that might also be a lot of effort for not much gain
You're right, especially since I at least fixed part of the problem, i think what i'll so is play some games where I can recreate this scenario and see if they have the same problem or if it even feels that weird in an actual game, then i'll decide if it's worth fixinf
there's this thread about physics if you're curious, though since it's about systems in general it might not be super applicable to your situation
https://discussions.unity.com/t/depenetrate-in-one-direction/892023/4
thanks and btw, i'm actually stupid, I extended the Y range of the ground check by 0.02 and it totally fixed the problem
with the antigravity/velocity reset?
well keep in mind that could have some unintended effects if you aren't mindful of it lol
Yeah thanks, i did some more testing and the problem wasnt actually fully solved, i guess i'll just do what I said earlier, either way I atleast know why its even happening so I can stop loosing my mind over it, thanks a lot for helping :D
Can you stop hating
buddy you are creating unnecessary noise that isn't helping
Ok and
Bro I get you were trying to help but it's better for you to just admit you're in the wrong here, you were drowning out actual helpful messages with your ideas
(which could probably be solved by reducing the x/z size of the ground check, but that probably just goes full circle to the box thing not being consistent lol)
spamming is against #📖┃code-of-conduct
yeah i'll just play some games with crates in them and see if this problem occurs in them too
not much of a difference when you just are not able to
There's a function to encode a texture as a PNG
You weren't really helpful tbh, throwing out random ideas doesn't really do much, @naive pawn could actually tell me what the problem is because he has enough knowledge on the matter, instead of arguing here you could've just followed along and learned something yourself
I have
oh actually just realized, this doesn't happen with unity i don't think? at least with the 3d physics engine
there's a depenetration velocity, whereas source iirc does snapping - it tries to find an open space and teleports you there
physics2d doesn't have "depenetration velocity" so it might be snapping
I think i found it, let me try