Ehy guys, i was trying to replicate vampire survivors for those who knows the game and i've a question. As you can see there's a circle around me (the one who's opacity is less). That circle should deal 30 dmg to enemies colliding with it (using ontriggerstay2d) and enemies have 30 hp. What am asking is. Enemies should get oneshot from the circle but instead, when there are many, some of them go trough, do you know why?
#💻┃code-beginner
1 messages · Page 181 of 1
slowly rotate the game object with the line renderer/laser so the second point on the line renderer lines up with the player character, but with a delay. i can do it instantaneously but im trying to get the rotation to move slowly, lag behind the player
i am trying to make one script that handles all the collision for the player, however, when colliding with a fireball there are two outcomes, one is that the player takes damage and the fireball is destroyed, and the other is that the foreball is reflected off the player and continues on its way.
problem is, the condition that needs to be true to reflect the fireball, is to check if the fireball has collided with the child "shield normal" of the parent player (the player has the script for collision). Problem is, this requires a OnCollisionEnter2D inside a OnCollisionEnter2D... which seems to be not possible, instead i opted to check if the fireball has collided with the shiled in the fireball script attached to the fireball itself, then if thats true, set a "isReflected" bool to true, but since im running two OnCollisionEnter2D they run at the same time and the "isReflected" bool is nit set to true on time
just check if it has collided with the shield and reflect if it has, if it has not then you check if it has collided with the player
you are way overthinking how to set this up. a simple if/else if is all you need
Maybe just lerp or MoveTowards the transform.right vector?
yeah i tried those but ultimately went with something a bit different which now works as intended. thanks for the suggestion 🙂
i have the following code on the inventory gameobjects, dragging them works but the initial mouse position is wrong. attached is an image of the hierarchy, theyre all under the same canvas, have tried a few different things but nothing is working, what am i doing wrong? the Holder object is the one moving around
public void OnBeginDrag(PointerEventData eventData)
{
InventoryManager.Instance.draggedObjectImage.sprite = itemReferece.itemSprite;
InventoryManager.Instance.draggedObjectRect.anchoredPosition = Input.mousePosition;
Cursor.visible = false;
}
public void OnDrag(PointerEventData eventData)
{
InventoryManager.Instance.draggedObjectRect.anchoredPosition += eventData.delta / InventoryManager.Instance.inventoryCanvas.scaleFactor;
}
Could I please get help with this?
Are you sure you want to use the anchored position? It would be relative to the parent and anchors. While pointer position is in screen space.
Debug. See if your spherecast is hitting anything and if it does, what is it.
!code
Posting code
📃 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.
Anyone know why this code is randomly at times getting this message:
"MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still triyng to access it."
what should i use? ive tried local position, position, theyre all not following the cursor
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class WeaponScript : MonoBehaviour
{
[SerializeField] Camera FPCamera;
[SerializeField] float range = 100f;
[SerializeField] float damage = 30f;
[SerializeField] ParticleSystem muzzleFlash;
[SerializeField] GameObject hitEffect;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
private void Shoot()
{
PlayMuzzleFlash();
ProcessRayCast();
}
private void PlayMuzzleFlash()
{
muzzleFlash.Play();
}
private void ProcessRayCast()
{
RaycastHit hit;
if (Physics.Raycast(FPCamera.transform.position, FPCamera.transform.forward, out hit, range))
{
CreateHitImpact(hit);
EnemyHealth target = hit.transform.GetComponent<EnemyHealth>();
if (target == null) return;
target.TakeDamage(damage);
}
else
{
return;
}
}
private void CreateHitImpact(RaycastHit hit)
{
GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact, 1);
}
}
Looks like your code is trying to access a desttyoed particle system
the error message will contain a filename and line number. Start by looking there
yeah the particle system is my muzzle flash effect, but i dont know why its getting deleted randomly
the error message will contain a filename and line number. Start by looking there
MissingReferenceException: The object of type 'ParticleSystem' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.ParticleSystem.Play () (at <bed3c648adea411ea03fe29d57cdd527>:0)
WeaponScript.PlayMuzzleFlash () (at Assets/Scripts/WeaponScript.cs:31)
WeaponScript.Shoot () (at Assets/Scripts/WeaponScript.cs:25)
WeaponScript.Update () (at Assets/Scripts/WeaponScript.cs:19)
Position should follow it, assuming your canvas in in screen space.
but it doesnt set the isReflected bool to true in time
it gets to the else statement first, which destroys the object
Why do you need that bool?
its screen space - camera, its a UI camera, not the main cam
Likely some other code you have is destroying it.
its set to true if the fireball has collided with the shield
Again, why do you need that bool? Just check if it is colliding with the shield there
you mean in this method itself?
This is my enemy health script, but I don't have it on the muzzle flash particle effect is the weird part
public class EnemyHealth : MonoBehaviour
{
[SerializeField] float hitPoints = 100f;
public void TakeDamage(float damage)
{
hitPoints -= damage;
if (hitPoints <= 0)
{
Destroy(gameObject);
}
}
}
i only have that script on my enemies
What do you have it on instead then?
That script is on my enemies but for some reason my muzzle flash particle effect is randomly getting destroyed from it
Here's the steps to quickly figure out the issue:
- Look at the inspector of your WeaponScript instance in the scene
- Click on the particle system reference you have assigned there
- Observe which object Unity highlights/takes you to
- Observe that object while the game is running and make sure it's not destroyed.
Also note that you may have multiple copies of WeaponScript in the scene, and this problem could be happening on one copy but not others due to how they're set up differently and which Particle Systems they are referencing
The weapon script itself doesn't have the particle system assigned, just the item that the script is on
Wdym by this? Weapon Script has: [SerializeField] ParticleSystem muzzleFlash;. That means you must assign it to something in the inspector
yes that's what I meant when I said "Look at the inspector of your WeaponScript instance in the scene"
the instance
not the script itself
ahh
That could be the issue. If they have different resolutions, there would be weirdness.
ugh i cant even get it to trigger now
its very random when it happens vs when it doesnt
ok i triggered it, now it just says this as expected
did you watch the obejct that used to be referring to?
Is that object now destroyed?
yes it is
ok so
figure out why that's happening
the problem lies there
it has nothing to do with this script
how can i make the camera a FPS pov? as of now the camera can turn up and down, but not left and right. The player can turn, but the cameras Y rotation doesnt change
look up a tutorial for FPS controls, there are thousands of them
the ONLY place I have any destroy command is in the enemy health script
public void OnLook(InputAction.CallbackContext context)
{
// Reads movement input from the Mouse Input Action.
mouseInput = context.ReadValue<Vector2>();
Debug.Log(context);
// Sets the y-axis input from the Mouse inverted to the camera up/down rotation.
// Clamps up/down view to 45 degrees.
// Multiplies the x-axis input from the Mouse and sensitivity to the players left/right rotation.
// Rotates the first person camera local to its own rotation.
firstPersonCameraXRotation -= mouseInput.y;
firstPersonCameraXRotation = Mathf.Clamp(firstPersonCameraXRotation, -45f, 45f);
firstPersonCamera.transform.localEulerAngles = Vector3.right * firstPersonCameraXRotation;
// Rotates the player with the player left/right rotation every time the mouse is moved.
playerYRotation = mouseInput.x * mouseSensitivity * Time.deltaTime;
gameObject.transform.Rotate(0f, playerYRotation, 0f);
}
show the inspector for the M4 object
i know but alot of them arent working for some reason. I had this issue before but dont know how it got fixed
you should NOT be multiplying deltaTime into that
good to know lol, i still have trouble of when physics are at play idk
if this script is on an object with a Rigidbody you should not be rotating via the transform
it has a character controller with the new input system
gameObject.transform.Rotate(0f, playerYRotation, 0f);```
should instead be:
```cs
rb.rotation *= Quaternion.Euler(0, playerYRotation, 0);```
ok scratch that then
what trouble?
using time.deltatime
ah that fixed it, ty @wintry quarry
right, as mentioned you shouldn't be using it
at all? or just for the playerYRotation?
When handling mouse input
okay
mouse input is by its nature already framerate independent
because the values you are getting are movement since the last frame
one more question though, its also happening on my bullet impact object, but that has "Stop ACtion" set to none
i took it out, now the only thing im havin an issue with is how to rotate the camera on the Y axis of itself, normally you would parent the player over the camera, but its bad habit right?
start over looking at the error filename and line number
Likely something to do with
Assuming this impact object is what you're referring to
the code looks ok on the left there
I changed it
this is what its supposed to be
and the effect works for a while then gets destroyed
this is the code in question
!code
Posting code
📃 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.
// Your code here
private void CreateHitImpact(RaycastHit hit)
{
GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact, 1);
}
}
What's the error message?
same exact one as before
Can't be
it would have a different filename and line number
show the stack trace
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
WeaponScript.CreateHitImpact (UnityEngine.RaycastHit hit) (at Assets/Scripts/WeaponScript.cs:52)
WeaponScript.ProcessRayCast () (at Assets/Scripts/WeaponScript.cs:39)
WeaponScript.Shoot () (at Assets/Scripts/WeaponScript.cs:26)
WeaponScript.Update () (at Assets/Scripts/WeaponScript.cs:19)
So looks like you're destroying hitEffect somewhere
btw make sure you're referencing the prefab
and not some instance copy you have in the scene
because this screenshot seems to imply you have a copy in the scene for some reason
ok ill double check that
delete any copies from the scene, and then double check the prefab itself
oh hey! speak of the devil, i was literally about to ask someone if they could pickup the baton question 🙂
baton?
so the TLTR question was: how is this used / interpreted
InputAction action = playerInput.Actions["ActionName"]
baton, like a relay race (the metal rod passed along)
The prefab was what I had referenced
You insert the action name from one of the actions from the input actions asset inside of ["ActionName"]
ah ok
Jesus christ i said action alot
so Backpack in this case ofc
You couldn't have destroyed the prefab without acquiring other warnings about destroying assets so likely you changed the reference sometime after starting the play session.
so I think what you're stating as the next logic conclusion is that for example this code:
private void OnEnable()
{
_input = new InputActions();
_input.Humanoid.Backpack.performed += HandleBackpack;
_input.Humanoid.Enable();
}
private void OnDisable()
{
_input.Humanoid.Backpack.performed -= HandleBackpack;
_input.Humanoid.Disable();
}
public void HandleBackpack(InputAction.CallbackContext context)
{
if (context.performed)
{
Debug.Log("Attack performed");
}
}
Implies you've really referenced a prefab and not a scene object and it was destroyed
well i have the prefab still and i re-applied it and its still happening
you can use that one line instead of possibly subscribing to an the HandleBackpack event and then having a separate method called HandleBackpack?
using UnityEngine;
using UnityEngine.InputSystem;
public class InputSystemController : MonoBehaviour
{
private InputActions _input;
void Awake()
{
PlayerInput playerInput = GetComponent<PlayerInput>();
InputAction action = playerInput.Actions["ActionName"]
}
private void OnEnable()
{
_input = new InputActions();
_input.Humanoid.Backpack.performed += HandleBackpack;
_input.Humanoid.Enable();
}
private void OnDisable()
{
_input.Humanoid.Backpack.performed -= HandleBackpack;
_input.Humanoid.Disable();
}
public void HandleBackpack(InputAction.CallbackContext context)
{
if (context.performed)
{
Debug.Log("Attack performed");
}
}
}
Just for clarity, prefab refers to your asset not in the scene.
Does that code work?
Oh thats because i dont use InputActions like that
I didnt even know it could be that simple
Im confused by that code
well, i can't take credit but I'm thrilled I can pass along at least something 🙂
this is what winds up happening
the InputActions instance knows about the BackPack action?
let me cross-check...
notice how the impact disappears after like 10 shots
The console is printing Attack Perfomed?
Im not doubting you or anything im just shocked that works
Why do you have these HITFX_VFX instances in the scene?
ik 🙂
those are the particle systems
i just created an extra VFX_M4 item when troubleshooting before sending the vid
Thats pretty simple thx for sharing!!
not at the moment, ty! you gave me an alternative. FYI all you need for it to work is an empty game object with that script and ofc you know an inputsystem object that's called InputActions (btw not to be confused with Unity.InputSystems's InputAction (non-plural).
So, when i made my tilemap collider friction less (so i couldn't stick to the walls) this happened. I'm guessing it's cause the floor is so slippery, but I can't figure out how to fix it without making the walls grippy again. any ideas?
Wait, is it cause i use tranform.position to move the character instead of setting momentum?
Hopefully none of them were the hit effect object.. The hit effect object was supposed to be a prefab and not scene object
so it sets its position into the wall then gets ejected?
I think u have "Create a C# class" Selected for ur input action asset
if you don't mind shortcutting the test i can do, how would you execute your line of code?
InputAction action = playerInput.Actions["ActionName"]
aka how do you act upon the action
You have something else going on Spring
ahhhh
ok so im trying to get my enemy to dash to the players last position with this code private IEnumerator TreeDash() { moveBool = true; playerPos = player.transform; while(true) { gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, playerPos.position, 0.01f); yield return null; } }
ik theres no break in the while loop but for some reason when i run this it doesnt go the the location that i set at the top but it just follows the player constantly and i dont know why
no, just completing the thought/technique you shared was all
im a little slow tonight thank you all for the help
You can delete my code
but doesn't it work?
Its specifically for the player Input
No u have to do extra stuff for my code
I thought you were just trying to use the Player Input
oh ok, yours actually sounded VERY simple and was like, why do people do it the way I shared 🙂
You're moving towards the players current position and not their last position
again, can't take credit - at least a person Fen here helped and there's seems to be a pattern of the technique from Inventory Systems on youtube and/or Unity's new Input System to show this technique
im not tho im setting it once at the top and never again
Yeah Fen is way smarter than me when it comes to this stuff
have a good evenving vee, thanks for reaching to me again
Ofc man you 2!
If you're referring to the referencing of the transform component, it's a reference and not a value copy
If you want to move to a value, cache the last known position and move towards that - not the players transform component.
thats what im doing im caching the players position once as a variable then when i start moving it towards the player if i move the player while its moving it will move towards the new player position instead even though i never set that variable again
You're not caching the position. You're caching the transform component.
position = player.transform.position
Where position should be a vector 3 value rather than a reference to the player transform
Maybe show the error
wait no im dumb i got it
hey guys i need to add my text script but i cant seem to find a way to do that. i need to add the text to the score
Man I do not undertand a think of why this is working as it is working....
I want a proyectile to rotate towards the closest object with the tag enemy
If I use a separete script that just rotates a object towards another object and assing it there it works as intended, if I add that same code to this script, it doesn't
But in a really weird way
That cuve is tagged as an enemy
The botton left proyectiles seem to want to go DIRECTLY in the opposite direction
The rest just seem to straigh up ignoring
There are 2 types of texts in Unity by default, UnityEngine.Text which is the legacy built-in, and TMPro.TMP_Text which is the more updated text solution, it looks like you are using the latter but your type in your script is the former
can you help me fix my script
using UnityEngine;
using TMPro;
public class score : MonoBehaviour
{
public Transform player;
public TextMeshProUGUI scoreText;
// Update is called once per frame
void Update()
{
scoreText.text = player.position.z.ToString("0");
}
}
What am I doing wrong?
And that doesnt let you drag your text mesh pro component into the slot? Also as a side note, you can use a !code block to format your code with C# highlighting
Posting code
📃 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.
You should only set closestEnemyDistance if it is actually smaller than the previous one.
correct it does not'
In fact you don't set it at all
That should, do you have any errors in your console that may be preventing your script from compiling? Can you show what your inspector looks like with that updated code?
yup
Config your ide first
yo im so new im sorry how do i do this
Check console window where the errors are if any
!ide
💡 IDE Configuration
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
It is not what I am doing?
You don't set it at all. So the last object position satisfying the initial range, in the found objects array would be returned.
quick question, can anybody tell me how to make the players speed stay the same when holding down W & A/D because if i move diagonally it makes the player move faster
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(!isGrounded && velocity.y < 250)
{
velocity.y += gravity * Time.deltaTime;
}
controller.Move(velocity * Time.deltaTime);
}```
Use a normalized input vector in your movement calculation.
k thx
Is there any easy way to make the floor more solid? I'm using a tilemap collider and i keep clipping through the floor when I'm falling to fast
how can i have a button on the script in the enspector
Custom inspector
no like in code you write something and when you go back into unity you see a button on the script component
what is that called
Custom inspector
that is not it
Not really a coding question. If you're using a rigidbody for your controller, set it to continuous collision detection.
But what you probably want is an attribute [Button] from https://github.com/dbrizov/NaughtyAttributes
Oh okay
thanks
How’s it not
nvm i got it
it was this
[InspectorButton("OnButtonClicked")]
public bool Generate;
private void OnButtonClicked() {
}
Why is the Physics 2D not working? It seems to work fine for the line above?
What does the error say
Because I can see what's wrong, perhaps you can figure it out by reading it
it says ";" expected
and i just realised I forgto the curly brackets, but it still says it so
generally when you see an error like this you should look at the statement that preceeds it and think about whether it makes sense
Curly braces were not the issue
They are not required when inline
In this case, this is not how you write an else statement
how would i go about making it so my GameObject ignores colliders on other instantiated clones of that GameObject ive tried this but it doesnt work Physics2D.IgnoreCollision(wallCollider, wallCollider);
Put them on a layer and disable collisions on that layer
yeah, I've just stared at it for a bit longer and realised I did it completely wrong lol. It's cause i origanlaly had the code written at void start, not in an if statement, and just completely forgot how they worked when i put it in one lol. Sorry for bothering you guys
use the collision layer matrix to place that GameObject or prefab on a layer that doesn't collide with itself . . .
can i do it with tags so it ignores everything with a certain tag
Use layers
no, use layers . . .
But that’s a custom attribute no?
so would this work Physics2D.IgnoreLayerCollision(7, 7);
if all the objects i dont wanna collide with are on 7
Use the matrix in project settings, but otherwise it should work, yes
no, again, use the collision layer matrix to setup your layers and choose which should or shouldn't collide with each other . . .
Using named layers in code is terrible
Is anyone able to help me out with a duck problem?
Better than ints
If you change later the whole thing breaks
U can use constant for that tho
Magic numbers are not fixed by turing them into strings, you put them in a variable/constant
if i have two colliders on an object is their a way to ignore collision on just one of them
What are you trying to do with exactly
or use an SO with a LayerMask field and reference that. forget about strings or ints . . . 
LayerMask doesn’t work on gameobject int no? @cosmic dagger
Ok, yeah, it doesn't matter, it does the same
Since that’s one layer and not multiple like LayerMask
Like it was the only enemy tag in scene anyways
GameObject int? clarify . . .
oh, you mean the int that gameObject.layer represents?
nope. you have to convert it to a LayerMask. i use extension methods for that . . .
Yes I recall I couldn’t use LayerMask with that and had to use LayerMask.NameToLayer to get it working
Surprised we don’t have that, how would one convert that into LayerMask and vice versa?
Would something like 1 << gameObject.layer work?
For the one direction only of course
Interesing. haven’t dabbled into bitshift myself
the bitshift should work for it
transform.rotation = Quaternion.FromToRotation(transform.up, collision.contacts[0].normal);
I have this here which rotates an enemy along the normal of the wall it hits. How would I offset the rotation so it rotates 45 degrees away from the wall and not 90?
@summer stump yep, using 1 << gameObject.layer will convert it to a bitmask . . .
Nice! Thanks guys
typically, i use a CompareLayer or ContainsLayer extension method to check if two layer masks are the same or if a layer mask is contained within another . . .
once you do bitwise stuff enough you eventually remember what it all does
This doesn't seem to be working for some reason and I can't figure it out. What is the blaringly obvious error that I'm certain I've made?
(Also, any suggestions on how to find solutions through google? I keep trying to go to google for help, but I always end up not getting any helpful information)
What, specifically, is not working?
When i trigger OnCollisionEnter, the bool insideagain on the gate object stays the same instead of switching to false
you should explain what you're attempting to do and the result you want . . .
Are you sure the OnCollisionEnter meesage is sent?
your code uses OnTriggerEnter2D. that is completely different from OnCollisionEnter . . .
Yes, because the sorting layer switches fine
Also, I see- ah yeah, what Random said
Og yeah i meant to say trigger not collision sorry
one is a trigger, the other is a collision. one is 2d, the other is 3d . . .
details matter . . .
Do you get any runtime errors? Like a NullReferenceException on gate?
nope
place a log outside of the tag check and inside of the tag check to make sure the trigger method is called, and that the tag check is true . . .
Show the whole gate !code
I suspect honestly that the bool DOES change, it just flips back immediately because of something else
Posting code
📃 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.
That makes sense, lemme send the code
https://paste.ofcode.org/8bQfEtyDLURyRXUejTrfhQ
My code is really bad, just warning you
Is it bad practice to put multiple classes in one script? Like for an FSM?
would you guys recommend using a character controller or rigid body?
Both the debugs worked
you can only do that with c# classes, not classes derived from MonoBehaviour. i'd get used to separating them unless they concrete types created from a generic base class with just the class definition . . .
its fine, as long as you do not have multiple MonoBehaviours or ScriptableObjects in 1 file
to broad. it depends on the game and the type of movement you want . . .
Can I have one MonoBehavior and the rest non MonoBehaviors?
show us the code used for the debugs . . .
well its gonna be kind of realistic movement, basic walk run and jump
the problem is i dont know how to implement gravity into my character controller :/
yes that is fine
Yeah it’s for an fsm, so I feel like multiple scripts is pretty uneccessary since the classes are so closely intertwined
Sweet thx
is it possible to still use a rigidbody or is that bad practice?
yeah i often have a bunch of types defined in 1 file, if they are like data containers and stuff related to the main one
Neither is bad practice, it really depends on what you want from your movement.
im not picky lol, i just dont know how to get gravity to work
Rigidbody gives more freedom, while character controller is easier configurable
@thorn holly the ones to be weary of is anything that needs a guid, since to get that it needs a meta file. So everything that derives from UnityEngine.Object
yea ive noticed. but it feels like any coding with the controller is confusing bc idk how it uses .isGrounded in the characterController
multiple reasons.. also, i should probably learn rigidbodies in the longterm
Alr yeah, I’m just using an abstract class and then some states derived from it, so there shouldn’t be too much issue
yeah 100% fine
The only other issue is that you're doing lerp wrong.
What? Why?
Because t/time is supposed to increase from 0 to 1 over time. That's the whole point of lerping.
And both parameters need to stay constant.
It works literally perfect when used in stand alone
its not working how you think though
Like it smoothly interpolates between a and b based on the given speed
its working likly because you are also feeding current position into the first arg not start position
lerp is not meant to move things at a given speed
Isn’t there a look towards or look at method?
a few ways depend on if you want to apply it right away, or simply want the rotation that would make it look at something
THEN WHY THE HELL IS THIS WORKING?
I don't get it
lerp(a, b, t) returns a value between a and b base on where t is between 0 and 1
It's kind of working because you're doing TWO things wrong and they are kinda counteracting each other. But it's done wrong and you just havent hit the point that it fails yet
because you are feeding the current value into a every update you are moving towards it by what you passed to t
so if t was 0.5 it gives half way closer each update
but never reaches its final target because its always by half
normally people save there start pos pass it to a, pass destination to b, then start t at 0 and add deltaTime * a multiplier every frame
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
public class HighVelocityShot : MonoBehaviour, IAbility
{
public float AbilityForce { get; private set; } = 20f; // Example force value
public event Action<float, float> OnCooldownChanged;
[SerializeField] private GameObject abilityPrefab;
[SerializeField] private GameObject foregroundIcon;
[SerializeField] private GameObject backgroundIcon;
public GameObject AbilityPrefab => abilityPrefab;
public GameObject ForegroundIcon => foregroundIcon;
public GameObject BackgroundIcon => backgroundIcon;
public float Cooldown => 5f; // Example cooldown
public bool CanUse { get; set; } = true;
public string AbilityName { get; } = "PillStorm";
private Camera mainCamera;
public void Awake()
{
mainCamera = Camera.main; // Cache the main camera reference
}
public void Activate(Transform firePoint, GameObject prefab, float force)
{
if (!CanUse)
{
Debug.Log($"{AbilityName} cannot be used due to cooldown or other conditions.");
return;
}
Debug.Log($"Activating {AbilityName}");
// Calculate direction towards the mouse cursor
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
Vector2 direction = (mousePosition - (Vector2)firePoint.position).normalized;
// Create the explosive shot projectile
GameObject shot = Instantiate(prefab, firePoint.position, Quaternion.identity);
Rigidbody2D rb = shot.GetComponent<Rigidbody2D>();
// Apply force in the direction of the mouse cursor
rb.AddForce(direction * force, ForceMode2D.Impulse);
StartCoroutine(CooldownRoutine());
}
public IEnumerator CooldownRoutine()
{
CanUse = false;
float cooldownTimer = Cooldown;
while (cooldownTimer > 0f)
{
cooldownTimer -= Time.deltaTime;
OnCooldownChanged?.Invoke(cooldownTimer, Cooldown); // Update UI each frame during cooldown
yield return null;
}
CanUse = true;
}
}```
Hey I think I am running into an instantiation issue, I currently have a set of abilities that from within a list that can be interchagably swapped out on the fly. but none of the abilities can even instantiate or are returning null. Is this because of a parenting issue? Currently the script will is sitting on the parent of the child it's instantiating. I don't really know if this is a beginner or higher question
why is it called AbilityPrefab but you are passing in a refernce to the GOW Parent GO
Because the way I orignally had it set up, was to just pass in the entire prefab but wouldn't that cause circular instantiation and just not work or break the game?
code never shows what calls Activate, so can not see what prefab is being passed to Instantiate
One sec
also no parent is being set, so they will be created in root of your active scene, which could be fine depend on what you want
The system itself is a little complicated and out of my personal scope, but I was tasked with creating an system which will store player abilities that can be swapped out in between bosses once unlocked, which in turn has to be able to swap out all icons, prefabs etc.
Anything that you could be interested in is in the codeshare, if you need any further clarification let me know, I appreciate you checking it out
well it looks like the first issue i pointed out
where that code calls Activate, it passes in ability.AbilityPrefab, which does not point back to a prefab based on your inspector
but the GOW Parent object
So it was originally set up like this
But the problem that creates is circular instantiation no?
Because the script is attached to the object it's trying to instantiate
Is only one here, the other was not relevant whatsoever and is not even part of the standalone script
But honestly this is working so good that I cannot believe it is wrong
There are two things wrong with that one line of code.
You don't have to believe it, it objectively is wrong.
But if it's good enough for you in its flawed state, that is perfectly fine
Btw, instantiating an object means "creating an instance"
C# is an object-oriented programming langauge
Each time it fires the ability it creates a single instance of the bullet so that would be instantiation no?
I don't know the context of the issue here enough
I just got here
Can you explain the problem quickly again?
recursive you mean
TLDR: My abilities are not instantiating, here is the og post
here is the codeshare
yes that's the word thank you
Totally forgot to change the mic and disable the camera on obs my bad
I don't think it's an inspector issue
Are you sure you have the Action "AbilityThree"
Wait
Here
This is how that error message pops us
Ability is null
Check your inspector
Did you assign everything correctly?
Then how am I supposed to a Slerp that has to update each frame? Like if it is in the Update method, it would have to either wait to finish a slerp to start a new one or do various simultaneusly or start a new one each frame, none of those actually works
Hmm that's weird
should be
background story: this is a system , or an UI to display game result
im optimizing a 20 lines code inside that UI, quite a lot to do, let starts with step 1
foreach (object gameInfo in history.gameInfo)
{
gameResult.type = JsonConvert.DeserializeObject<Info>(JsonConvert.SerializeObject(gameInfo))
//something more
}```
the game result UI receive data from server and populate itself, the model class that receives data will be used by many other classes, im told to not modify it, or the whole system will collapse
ikr?
so, without modify the base model, is this good?
I'm unfamiliar with Activate()
I debugged and everything
It looks good to me but I'm too sleep deprived to thoroughly check everything 😭
Some people should be able to help here
Activate is just a method I created for the interface
using System;
using System.Collections;
using UnityEngine;
public interface IAbility
{
event Action<float, float> OnCooldownChanged;
string AbilityName { get; }
float Cooldown { get; }
bool CanUse { get; set; }
GameObject ForegroundIcon { get; }
GameObject BackgroundIcon { get; }
GameObject AbilityPrefab { get; } // Prefab for the ability
float AbilityForce { get; } // Force to be used with the ability
void Activate(Transform firePoint, GameObject prefab, float force);
IEnumerator CooldownRoutine();
}```
Why even use slerp in that situation? Seems like you should just use a different method
It's not a unity thing
How else do I calculate the positions in between 2 quaternions?
Like, vectors, I could do, quaternions, no idea
Should I maybe put this question in a higher channel? or would this still be considered a beginner question?
There's RotateTowards if you want to use quaternions, and there are other methods, like SmoothDamp and such in Mathf if you want to manipulate the angle I. Some other way.
Maybe start a thread, because for other people to help they'll need to scroll kilometers up the message history.
Provide all the details on the issue and your code.
Are you sure the problem is not with your “canUse” variable? The message you showed happens after you necessarily call get equipped ability which will give a specific message if it returns null, but this doesn’t happen. Either the manager returns null from its collection or you aren’t returning null and “canUse” is false.
Yeah I just figured it out
It totally was the canuse variable
Thank you all for your help
I really appreciate it
I'll hop on back if it's not the case
I'm trying to make a tank shell projectile that ricochets if it hits the object at too steep of an angle.
I had it figured out at first:
- Sphere collider at the tip and explodes on impact.
- and a Cylinder collider in the shape of a hockey puck right underneath. If the projectile touched the target with this first then, ricochet.
Problem is: it moves too fast so it sometimes phases through walls. I fixed this by making the sphere colliders height really large so it shoots ahead of the projectile reaching far.
But now how do implement the ricochet mechanic
try using the Vector3.Reflect method . . .
I'll have a look
is it more expensive to call the return method IsGrounded(); that includes raycasts every time it needs to be checked, or if I just put IsGrounded(); in update and change it to a void method?
because i wanted to only use it when i need to, I guess for better (clearly not noticable) optimization, but i realize if my movement method calls the IsGrounded method and my movement method is in the Update method, then Id just be calling it multiple times + the update function
From "speed" standpoint doesn't even matter, but I would argue doing it with return is better
You're creating a function who's single purpose is to check if it's grounded and can be reused anywhere else
yea i figured as well, then i thought if i just use IsGrounded in update and set it as a bool variable, maybe it would cost less?
Its really a point of do i want IsGrounded in the Update function lol, keeping things tidy
Depends on how often do you want to see if you're grounded or not
For most of my games
void Update()
{
If(isGrounded())
{
DoMovement();
}
}
Is pretty clean and tidy
Just make sure you're checking "isGrounded" only once per frame at Max
then id probably want it in update. thats wat i was gettin to, if i have to check 4 different times at once it could be an issue
4 different if statements in a single Update wont even make a dent in the most basic of cpu’s
ill just call the method in update once, and get the data from the variable
Yea but im trying to make a fps controller I can use in other games ill make, they have one on the asset store but i dont quite understand it, also it doesnt use the new input system
I want to make it look nice and be politically correct lol
He means 4 different is grounded check in single frame i think lol
Still
I was using the new input system and a character controller, then realized the controller isnt that flexable
so i had to switch to rigidbodies, ive been working on a system all day lol
Even if it doesn't make dent it's good coding practice
I mean what he is doing now is better in terms of code clarity and maintainability and even technically performance. Im just saying that modern cpus are truly insanely and disgustingly fast.
It helps to know that
I work at a pc shop during the day, and let me tell you pcs are becoming the value of a car
I did change it, it works exactly the same, is indistinguiseable
It is still resulting in the same issue
So I have all objects that reference the player do so by finding an boject with the tag "Player" at the start, and even though the player was technically not already in the scene and was being instantiated, it worked perfecty fin with no issues. But now it's just started not working. For some reason the object reference never works unless i put it in update or something. Is there way to fix this? Because it was working fine before. Technically teh new way (putting it in update) works fine but it just felels clunky and I'm sure theres a better way to do it.
do i still need to add .normalized to the moveDirection if i am using the new input system?
"never works"
wdym
do you get error ? show error
if you think they somehow were able to find the player before instantiation you remember wrong lol
You're saying player is instantiated later on? So I'm assuming either in a "start" method or later, so ofcourse it can't find a object with tag "player"
The player is instantiated in start
and line 23 in rope ladder is Start() ?
Then maybe share more details on the issue. Because it was not very clear and I don't see any obvious issues in the code. Perhaps it's the setup in the scene..?
if player is spawned in start ofc its not gonna find it
It's cuz you're assigning value of player on start, when it's not even instantiated yet
they both run start
Yeah but it was working perfectly fine before, with no issues
use awake
even though they were both on start
scripts order aren't guaranteed , between diff starts
For the player spawner or things referenceing the player
Because execution order of same rank is finicky, you can never rely on which start will be executed first
Sometimes player was instantiated first and assigned later, sometimes vice versa
Sheer luck that the Start spawning the player was running before the other start. Did you add more scripts in the meantime?
yeah
instantiation
Okay
why is player not in the scene already anyway lol
Well you adding more scripts shuffled the execution order
So either manually set execution order or certain scripts or redo when you spawn the player
cause they spawn in a different spot depending on where you enter from?
ever heard of teleport 😛
no
Basically all these proyectiles are aimed towards the cube (and they just move constantly forward), which is an object they should rotate towards when getting close, making it easier to hit; the expected in this case is literally nothing hgappens, cuase they are already looking towards the cube. The cube is the ONLY thing tagged as a valid autoaim target right now.
Instead this happens
I don't even know what they are trying to target
ohh , I mean the player can already be in the scene and just be assigned a new position..
how?
Is like they are snapping to one of the corners? Idk
use the position you plug into Instantiate , just do playerPos.transform = newPos
for example
ight, thanks
Why not debug it then?
Also a proper link to the shared code would be helpful.
!code
Posting code
📃 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.
my isGrounded is glitching out 
im just looking at a box flickering
how would i know
i had it in fixedupdate woops
dont worry i usually always send code after, unless i solved it like just now lol
Is what I am trying to, they are actually getting the position of the cube correctly, but they are not actually rotating towards it; I think
Share the updated code.
How? is !code rigth?
Posting code
📃 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.
Yes. Read the bot message.
Is not like that xd
` instead of '
Even if you formatted it correctly, that's not correct.
Read the Large Code Blocks section.
It pushed everything off-screen, it's large.
Everything over about 5 lines is large imo
It inherits form the generic proyectile, but should not be relevant, just hanldes basic collisions and movement
https://hatebin.com/bappghduwl
For somereason the animator.SetTrigger("stand") isn't doing anything. The debug goes off, but nothing happens. No errors, just nothing. Anyone know what the issue is?
Also, prewarning, my code is horrible
Is string name same as in animator?
Yeah, i've double checked
I have this script on my Camera to look around. For some reason the mouse movement is really blocky/jittery. I set it up differently than I used to, but i dont see why its acting like that. Also, is this the best way to set up mouse look for a player?
public class FirstPersonPOVBehavior : MonoBehaviour
{
public float sensX;
public float sensY;
public Vector2 view;
public Transform playerModel;
float xRotation;
float yRotation;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
ViewPort();
}
public void OnLook(InputAction.CallbackContext context)
{
view = context.ReadValue<Vector2>();
}
public void ViewPort()
{
yRotation += view.x;
xRotation -= view.y;
xRotation = Mathf.Clamp(xRotation, -45f, 45f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
playerModel.rotation = Quaternion.Euler(0, yRotation, 0);
}
!code
Posting code
📃 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.
Can you draw a debug ray at the position they're targeting?
Just read the mouse input in update instead of polling
- is trigger set to any clip in animator?
- is the length of the clip long enough to be noticed?
Otherwise you need to actually rotate in the event function or consume the input when you use it
I.e. set view to V2.zero at the end of Update
okay, how can i read the mouse input in update while still using the new input system?
Yes and, it's about a second and a half, with no loop (so hopefully it should stay on the last frame)
It will be simpler just to do the latter thing
view = Vector2.zero;``` at the end of Update
Mind showing animator window? 
course not
huh, for some reason the preview doesn't show th eanimation
BUt the animation window does
No clue then, maybe #🏃┃animation will be able to help better
Is just something like this un update right? Debug.DrawRay(transform.position, transform.forward, Color.red, 0.1f);
Cause it is not showing, should it?
Did you enable gizmos?
I did dissable a lot of them, but not sure which is the one that shows that
Cast a ray in your LookAtTarget method with the origin being the target position and an up direction, so that it makes more sense.
It's just the overall on/off toggle for gizmos that governs Debug.DrawRay
Also make the radius bigger, like 5f or something
Mmmmm, what?
the IsGrounded Raycast check is flickering on and off. if i stand still a certain way i can get it to turn off and on without jumping. what is causing this? https://paste.ofcode.org/aiSicvmiSYLM7AVYkwDMSC
lol thats multiplicaton then addition right?
i dont like it either, i jus followed a tutorial
So that's a ray FROM the target towards the position of the proeyctile?
How?
also where is transform .position
and how big is the player, show debug.drawray
Like why all of them aiming the right side???!!
player is a 2m capsule
Use Vector3.up for the second parameter...
wym transform.position?
when does it turn off and on
ohhhh you know what
it probably is because the center isnt at 1m, its at 0 bc i put the components on an empty parent over the model
let me try it out
okay, though personally I would use a bigger shape for like edges, I usually use ray for slope angles n stuff
what should i use? im still learnin, if theres a better method im down, im already not liking the setup i made. the camera controls the mouse and sensitivity, while the player controls movement, its a bit weird
Nope, that's not showing
Why?
if the player is a capsule I usually go with a sphere since that fits perfectly the bottom part
It does. It's just small. Which is why I told you to make it 5 units.
oh god there are many more parameters needed with a sphere hehe
private Collider[] groundedResults = new Collider[3];
private bool Grounded()
{
int hits = Physics.OverlapSphereNonAlloc(transform.position + groundedOffset, cc.radius, groundedResults, groundedLayers);
return hits > 0;
}``` not really lol
return hits > 0
true idk why when I recorded the video with that way !
Now there is line aiming upwards in the cube, that's.... expeceted, why sending the ray up?
yea that looks simple to understand, just alot of new information. I havent even gotten to making the game yet
Dont worry about making a whole game yet in the beginning tbh
just play around with the engine
get familiar with components and how they works, scripts etc
To make sure that the target position is correct.
Do you actually seem the rotating? Are they still rotating during the time of the screenshot?
They are rotating
Like in fact....
ive already made a couple platformers from start to finish, and dabbled with menus and stuff, I am getting the hang of alot of it without needing to copy code completely. So right now im trying to wrap my head around the correct way to do things, even if its not needed as a beginner. Id rather make sound games with not alot of content than a broken game from youtube tutorials
From their position TO the target the rayscast is this
That's what they are looking towards
But why though?
initially as long as it works, thats "the correct way"
Share the updated code(the debug line specifically)
you're in the beginning phases you're just meant to make stuff happen, there are hundreds of ways to do the same thing in dev
i feel like im learning wrong through half the tutorials i watch, theyre all sort of destructive
yeah tutorial hell. You kinda have to start researching stuff and paving your own ways
Oh, I know why, is cause I am using a Vector3 instead of a transform rigth?
Try debugging the object name of the returned position.
Unity doesn't like that
What? Why would that be related?
what is cc.radius in the code?
Where are you planning to use the transform anyway?
Cause the issue comes from when passing the target possition to the LookAtTarget, and I am pretty sure about that
cc would be the CharacterController
this is golden, ever since ive been reading docs first, trying, then watching a video ive noticed major improvements
@rich adder i dont have a character controller anymore :/ i gave it up for rigidbody
then use CapsuleCollider, they're both capsules
How would passing the transform change anything?
This method worked, woohooo
Dunno, but this makes 0 sense to me man
Is returning using the correct positions in the debug, like those are the exact coordinates of the cube, but then is trying to look at that angle which is clearly not rotatingTowards the target
try some top down
or 2.5d games
ive tried my hand at it, im not ready to get into tilemap optimization yet, and i want to freeroam, so im doin 3d for now
Ooof. Okay. I see the issue now. Please check the documentation of Quaternion.LookRotation. you're not using it correctly.
I have read it, I didn't understand shit
I curse the quaternions
Like why do we need them having Euler?
To avoid gimbal lock and other nasty issues.
If you don't like quaternions, why not just set the object transform.forward instead..?
Use what? Isn't that just the vector comming form the front of an object? How do I apply rotations with that?
You can set it and unity would rotate the object accordingly.
Set it to what?
To the direction you want it to face.
*To the desired forward direction.
how can i smoothdamp the camera movement?
im guessing using Addforce is causing the camera to stutter or update weird
What are the use cases for a singleton over a static class? Which should my save system be?
A static class is basically a freely read/writable global. Globals are generally bad, because they can be written from anywhere and therefore are easy to make mistakes with which are confusing to track down, and because they make it harder to test parts of your code in isolation.
A singleton is preferable because it's at least an instance, so in theory you could build another 'instance' of your game which includes its own version of that singleton, or you could make an instance of it for testing which isn't global. In practice though, most singleton implementations I've seen intentionally prevent these advantages and are globally accessible through a static reference, in which case I'm not sure there's much of an advantage.
Ideally you would compose your game out of non-global pieces which you can freely have multiple of in whatever context you need. If your game requires a single instance of a specific service you'll want to handle that properly, but that's different than how I see a singleton usually used where the code depends on there being a single instance of some global thing
well the things that would make sense to have a "global" for is my item database and save system
would it be preferrable to use a singleton instance or just a static class
You'd use rigidbody interpolation to avoid jitter
right now im using a static class and its working fine, but is that the best choice?
will I run into problems down the line
if it's working fine for you i woudln't worry about it
maybe, but you can't pre-empt every problem and you shouldn't try
one good reason to avoid statics is if you want to turn off domain reloading, which can help you iterate faster
but you could also use them and just handle that yourself
what do you mean?
it might help you make the game more quickly, which affects it in that it needs to be made to exist
lol true
not existing is the biggest problem most games have
I have it on interpolation already, i posted the issue in #🖱️┃input-system
so turning it off only effects static fields
everything else will reset properly
since it will technically leave scope
And how do I get the desired position and set an angle in between?
That just seems like the slerp I was doing at the beggining
right, so you have to reset your statics yourself if you want to use them with domain reloading turned off (if you avoid statics you never have to think about/remember that)
im only really using static methods
Man, this is literally just, looking at a specific target with a transition, it can be that difficult, like wtf, I am tired of this issue
oh, static methods are great and you should use them as much as you'd like
and one static hashset for my item database which doesnt need to be reset anyway
Danm you quaternions
pure* static methods i should say
yeah it sounds like you do have some static data
guys help pls i need help so bad
yes only the item database
but also it sounds like data which is reasonable enough to have be global, so have at it
aight thanks for the tips
yeah. I would instance that (maybe as an SO) so that if i wanted to, i could have multiple item databases and swap those in for testing or whatever but it's not a big deal
tf is "assets\pickle.cs(7,12): error CS0246: The type or namespace name 'Rigidbody2d' could not be found (are you missing a using directive or an assembly reference?)"
cause i was planning on doing that
but havent had the need to make multiple databases yet
sounds good to me, i'd keep it until you run into a real problem
show the code
are you missing the using statement? have your IDE fix the error for you
using statement for rb2d?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pickle : MonoBehaviour
{
public Rigidbody2D Rigidbody2D
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
you cannot name your variable
the same as the type name
yes, it's not a native type. but they have it so that's not the issue
it still persesting
i removed it
Rigidbody2D is a component that's coming from using UnityEngine
Assets\pickle.cs(7,35): error CS1002: ; expected
is your ide configured?
!ide
💡 IDE Configuration
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
yes, and if that was missing that could be the problem they had
yes but not using Rigidbody2d as you said
you cannot do such thing
...that's not what i said?
anyway you were missing a ; here
You'd rotate a direction vector from current to the target forward rotation. Almost same as now, but without quaternions involved.
And btw, your current issue is not caused by quaternions, but by not understand the difference between a direction vector and position vector.
No, I do, understand the difference, the issue comes when I want to tell it to basically just lerp its current rotation and a rotation at which is looking at something and decides that even though I give it a position to look at, the quaternions tell it that I was actually refering to a way different position in the distance
Also, they are both vectors, the position vector is basically a direction vector, which tells in which direction you should move from the origin to get to that position
so for my save system, i want it to loop through all things that implement the interface "ISavable." when the game starts. what would be the best way to do that? should I just make a public list and add them all manually?
or make the save system a singleton and use an event
That's the issue. You are not supposed to give it a position to look it, but a direction.
could i add a rigidbody to the camera 😮
You could
That's what LookAt is meant to do
Indeed. Any vector can be both. The question is in relation to what object or reference point.
Like isn't that literally its purpose?
idk why this pov is so jittery when i move, i never had this before
Rotation is relative to the object, not to the world origin.
If you use it properly, yes.
ISavable should provide some sort of method to register itself to the save service
It creates a quaternion rotation from a direction vector.
That's it's purpose.
ah so on awake it registers itself
Sure thats one way
is that what you would recommend
how do i go back to original text cursor?
Okey, now I just want to lerp the current quaternion rotation TO the quaternion ratation of lookAt, but it isn't working
press insert
thx m8
What doesn't work?
The lookAt is returning a random position in the distance
No it doesn't.
- It doesn't return a position at all. It returns quaternion representing rotation.
- You're not using it correctly as I said previously.
Check the documentation of what parameters it takes.
I would not implement ISaveable on a monobehaviour. A simple class that can ne easily serialized and just holds data will do. It can register itslef in its constructor that way it cant be missed.
I am using it on scriptable objects, not a mb
- I am refering to a random position at which they are looking at, it is actually a rotation, but they all are all aiming at the same Position in the distance, is not like each one is changing it rotation locally
- I am using it correctly, I have literally copied the documentation and replaced the values, it is still pointing there after the changes
Show your current code?
- This is because you're using the debug ray incorrectly as well. If you use Debug.Line instead you'll see that it is correct.
- What you have is totally not the same as the docs:
Your code:
Quaternion lookAt = Quaternion.LookRotation(targetPosition);
Notice that targetPosition is an actual position, not a direction.
Docs code:
Vector3 relativePos = target.position - transform.position;
// the second argument, upwards, defaults to Vector3.up
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
transform.rotation = rotation;
Notice how relativePos is a direction, not a position.
Maybe you should spend some time trying to understand what I'm saying and/or read through the docs and try to understand them, instead of blaming unity, quaternions and the rest of the world, trying to prove that your code is correct.
I know my code is wrong, I want to know WHY is wrong, just you are wrong is no help, I already know I am, that's why it is not working and why I am asking
I said like 3 times by now: position and direction are different things!
Does that make sense?
It does, I have done this, I have change it, it is STILL doing the exact same thing
As if I changed nothing
Show the updated code.
Hold up, I am afk rn, went to take a snack
why is it taking unity longer and longer to click play or load?
The bigger your project, the longer it takes unity to compile and reset everything. You can turn off domain reloading to speed things up if your code is properly architected
i just reloaded unity to free some ram, ive been working on this for about 10 hours straight lol
yeah it's good to restart unity every once in a while too
i cant seem to find out where the mouse jitter comes from. I even commented out the new input system and used the old input system to see if it fixes the laggy issue but its not goin away
You'd need to share some code.
so when i move the player, no jitter, when i jump and move the player, no jitter, when i move the mouse, no jitter, when i move the mouse and move the player, jitter
I think rb.rotation = Quaternion.Euler(0, yRotation, 0); breaks interpolation.
i thought so too, i changed it from gameObject.transform.rotation to rb.rotation , what can i do to fix that?
i used a character controller the first time setting this up, so i guess i never saw this issue, idk how to use torque or angular velocity,doesnt MoveRotation use character controller?
i wish i didnt have work today, i could sit here for hours learnin about this stuff
okay so Unity docs say "If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MoveRotation will resulting in a smooth transition between the two rotations in any intermediate frames rendered. This should be used if you want to continuously rotate a rigidbody in each FixedUpdate." and that rb.rotation teleports a rb from one rotation to another
I asked before here about some local saving data stuff, I'm now trying to look at a login. Everywhere I search is all using firebase but I'm wondering if there's any way I can do a local one at all so that I can personalise what will be used for the login details. Would this be done by just using methods through the local saving data that I mentioned or would it be done otherwise?
You can implement it however you want, but unless it's using a remote service like firebase, it's gonna be prone to hacking.
Whole thing should be on a local device, in the project I'm doing it would be for a fixed place not something commercially available
so when you say login, what you mean is like multiple save files? or multiple user profiles?
User profiles where their times to complete get saved
but no passwords or security or anything
anyone know why OnApplicationQuit is not calling when I exit play mode?
then yeah you can just do that locally, even just using the filesystem (make a folder for each profile and read those/let the user select one on game start)
I'll be using that I was just wondering if there's a way to do that locally
i think the editor has different quit events
is your filesystem not local? what do you mean locally?
oh sorry
what's the point of a local password?
It's like, a one place game which multiple people might be using the computer
and those people trust enough to share a computer, but not enough to play their correct profile or whatever?
🤷♂️
basically it depends how secure you want to be
is why i'm asking this
lke if you need real security, it's going to be some work
I can look at using firebase it's just I can't use library IDs on there
if you just want people to input a username and a password and you have those stored in text (or compiled into the game) somewhere and it's ok if people can find them if they try, that's different
That's what I was going to use for the login to begin with
if there's no reason for the game to connect to a server i wouldn't want to use firebase
unless you want to store your data in there anyway i guess
Ye that's why I was checking in the first place, seemed unnecessary
well it's your code so you can have it do anything
if you want to prompt them for a username and password then you can
Just wasn't sure if I'd be using the regular way to save data
If you want something which is semi-secure. Encrypt the user data using their username/password as the encryption key
and you'll have to decide how you want that to work and where those passwords come from and are stored and how secure they need to be
Ahh alr
probably, this would just be a layer on top of that
Ye I'll have a look at that
Ty
Quaternion deltaRotation = Quaternion.Euler(playerRotation * Time.fixedDeltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
if i remove rb.rotation, then the playermodel doesnt rotate, but if i leave rb.rotation in, then the player model rotates really slowly indefinetly until i move the mouse the other way.
i followed the Unity documentation, im trying to get the player model to follow the mouse input
can someone help me when i try put this on bones it says this
they are the same tho
What about compile errors?
show both the file name and the class name
That looks like you are using a lower case i in the filename but an upper case I in the class name
even though we cannot see the full fle name
anyone know why the Awake() on my singleton is being called between scenes even though it is dont destroy on load
Does it exist also in the scenes that you are loading
no they both have an uppercase i
no
its when i switch back to the scene it was initially in
So it does exist there
if you have your singleton code in Awake and it's done correctly, there is nothing to fix
if your singleton itself were an SO, it would persist between scenes naturally and you wouldn't need to worry about any of this
you could also have a wrapper scene which loads sub-scenes, and then you can put your singletons and any persistent stuff in there so that it's only loaded once
so just make a initilization scene that switches immediately?
yep, or with a little menu with a 'start' button or something, because eventually your game will probably have a menu
aight thx
anyone else know?
you have 2 errors there
duplicate script/class
Im trying to subscribe to an event in game manager, i realized singleton in it, so theres only one static instance of it, which i initialize in OnEnable, also i have bunch of listeners like background, timer etc. On those script i try to subscribe to an event in Awake method but i get null reference exception because instance is null
Here i set the instance of the session manager
private void OnEnable()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
Debug.Log("Instance set");
playerController.OnPlayerDied += EndSession;
}
and try to subscribe to it, but i get null reference exc
private void Awake()
{
SessionManager.Instance.OnGameOver += FinishTask;
}
I thought that unity calls OnEnable() first, so by the time code is in awake methods of the background class, instance was already set
Well, don't subscribe in awake.🤷♂️
Awake first.
Awake and OnEnabe of each object run in pair.
Destroy followed by subscribe to event, not a good idea
why do so many people think Destroy stops code execution?
well, it is on;y in case another sessoin manager already exist
omg thats you so much its working now
so you want to subscribe a method that you have just destroyed?
One tip: don't hide the errors. You might be able to escape from your problems in reality, but the compiler is relentless.
no, the logic was, if theres no game manager it would assign the first game object to the static insstance field and than subscribe that instance to playerDied event, if one game manager already exist, i dont need that game object and it should be destroyed
So if i make my start and awake methods public i would be able to manually call them,need to reinialize for multiplayer?
yes
Hi, how could I mimic a Mario-like jump ? What I mean is that when my character jumps, it can move it the air as if he was on ground, and so he moves to freely during the jump. In Mario, you can alter the jump direction, but slightly, so you don't get frustrated if you land right after an edge for example. It stored the jump direction of my character as a vector, and summed it with the character direction vector, but when I do that, it can't go back for example. If I lower the speed, the whole jump would be slower and the problem is not solved. I think I should maybe set all the others directions "slower" than the jump direction maybe, but that seems too complicated. Does anyone know how to achieve this please ?
Excellent will save me so much time thx
if you are object pooling don't forget you have OnEnable as well which you may need
Already using it,everything mosrly works its just hud elements not reinializing after respawn
then you are probably better using OnEnable & Start rather than Awake & Start
now im trying to put the circled bone into head and its saying that
yes, exatly what it says
also this is a code channel
You can't take it out of it's prefab. You'll need to unpack it.
Also, it's not a coding question.
Also also,I suggest learning the basics first:
!learn
not even sure why you would want to do that
Messages like that never lie 🙂
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh thank you
wait real quick what channel would i go to?
If it's a general question, #💻┃unity-talk
Otherwise, #🔎┃find-a-channel
oh thank you very much
Hello. I want to save the changed tags and load them when the scene is reloaded. I can't find a way to do this
https://hatebin.com/hmewqflkwr
Tags are changes inside the OnButtonClick method
not gonna work, you cannot update and save changes to GameObject/Transform data at runtime
not that I'm recommending this, but you could save/load the tags to PlayerPrefs
yes that's i want to do actually, but i couldn't do it the right way so far
use the gameobject name as the key and the tag as the value ?
In fact what i want to do is to save the color of the changed buttons and load them when the scene is reloaded. This is the only method i could come up with so far
may I suggest this, it's free and should make your lfe easier for saving Colors
https://assetstore.unity.com/packages/tools/utilities/player-prefs-lite-222004#description
color is just 4 floats
you can save the floats
then load the color based on these floats
r,g,b,a
it's not one or two objects, it's 30 buttons in an array, that complicates things
hmmm, my system handles arrays as well
what's the issue then
save each button's color
"Button1Color" "Button2Color" as a saved strings to player prefs
I cannot believe you are seriously suggesting that
for(int i=0; i < buttons.Count; i++)
{
var saveString = $"Buttons{i}Color";
Color buttonColor = buttons[i].GetColor();
//save to player prefs the color
}
or just JSON it
I want this gui popup box to be positioned so the top right corner is where the mouse is.
However, it also needs to be able to adjust for the size of the image inside it, which can change.
I thought i solved it but it changed based on screen size.... so if i fullscreen etc it displays differently
how can i do it properly 
current script is just this ```using UnityEngine;
public class CursorFollow : MonoBehaviour
{
public Vector2 offset;
private RectTransform rectTransform;
void Start()
{
rectTransform = GetComponent<RectTransform>();
}
void Update()
{
FollowCursor();
}
private void FollowCursor()
{
Vector2 canvasPosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)transform.parent, Input.mousePosition, null, out canvasPosition);
rectTransform.anchoredPosition = canvasPosition + offset;
}
}```
when i swap the colors of buttons i also swap some floats. But they are handled seperately. How can i use your tool? Do i have to create a seperate script for this?
Line 77 SwapButtonColors, Line 84 SwapStats
you use my asset exactly as you would use Unity PlayerPrefs, I have just extended the datatypes it works with considerably
ok, imported it. Are there any instructions on how to use it?
of course, there is full documentation available from the Tools menu or on my website https://stevesmith.software
is there a way to loop through all tiles of a tilemap (which are 3D game objects) and extract their position and name for example
i have a code that is working and is using raycast for that but is there a way to make it without raycast
this is not compatible with my script. I get errors. I think when i add the playerPrefsLite namespace, i can't use the default player prefs system of Unity. If that's the case i'll have to change the entire script
it should not be, my PlayerPrefs is 100% compatibile with code written for Unity PlayerPrefs
When i added the namespace i got errors for those lines
PlayerPrefs.DeleteKey("PlayerHealth");
PlayerPrefs.DeleteKey("PlayerDamage");
PlayerPrefs.DeleteKey("PlayerSpeed");
"Severity Code Description Project File Line Suppression State
Error CS0117 'PlayerPrefs' does not contain a definition for 'DeleteKey' Assembly-CSharp C:\Users\Ömer\Desktop\2d Samurai Game\Assets\Scripts\StatExchangeMenu.cs 160 Active
"
my bad, change DeleteKey to Delete
all other keywords are compatible with this tool right?
yes, at least I'm pretty sure they are, maybe Unity added some new ones since I wrote the asset
Thanks for spotting that, I will update the asset to handle DeleteKey
ok so where should i add the code to get the color of all buttons in all three arrays, inside the SwapButtonColors method?
show your code
i managed to save the stats, i don't understand why colors are too complicated to save. I think the array thing complicates things
public Transform[] healthButtonsParent;
public Transform[] speedButtonsParent;
public Transform[] damageButtonsParent;
why are you stroing them in array of transforms
why not Button[]?
i see you are doing GetComponent<Button>() everywhere
guys i could really use help regarding tilemap
any context? elaborate pls.. learn how to ask questions
how are we suppoesd to know what is wrong
and what is the expected behaviour
so, when i print bounds and local bounds i get numbers that dont correspond with tilemap size
it has 10 000 tiles all next to each other
yet bounds are like its single cell or no cells at all
reason for doing this is i want to itterete through all tiles in tilemap and get their cell positions and name
so i can pair them
Where’s “here” being printed?
tbh and not to be rude, but your code is awful but, you probably want something like this
void SwapButtonColors(Transform redButton, Transform whiteButton)
{
if (canSwap)
{
Image redImage = redButton.GetComponent<Image>();
Image whiteImage = whiteButton.GetComponent<Image>();
Color tempColor = redImage.color;
redImage.color = whiteImage.color;
whiteImage.color = tempColor;
PlayerPrefs.Set(redButton.name,redImage.color);
PlayerPrefs.Set(whiteButton.name,whiteImage.color);
}
}
You then need to see where you do the PlayerPrefs.Get to restore the state
it gets printed just before these bounds, i didnt screenshot it
i really dont understand why are bounds such...
Yesi know, i don't mind. I'm no coder. I can refactor it later. Right now i need something that works.
awake method?
Awake would be good
What're you trying to do exactly
I suspect you are looking at the wrong TileMap
i want to itterate through all tiles of a tilemap and store their position and name. I do have code that works using raycast but when using mesh collider, project gets incredibly laggy because of lot of mesh colliders on the scene, so i am trying to do it without it
i checked several times in inspector and i assigned correct one

How're you measuring them?
this
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.GetTilesBlock.html
works for me when I pass it tileMap.cellBounds
well unity offers cell bounds and then you itterate through them i guess
i will check now steve
well
i never had this line of code
Tilemap tilemap = GetComponent<Tilemap>();
actually i shouldnt need it because script is not attached on that tile
but on other one so i am passing tilemap as reference in inspector
Wait I think I'm being stupid but you're measuring a sprite based on tiles right?
all good
@sry how do i write the PlayerPrefs.Get line? I can't get it right. It's different than the regular playerPrefs. I checked the documentation but it shows an example for an int variable
what have you written?
Yo, im making a top down shooter.
Im trying to make a gun rotate so that its barrel points at the mouse, but didnt figure a way to di that, so im asking for help here
i copied exactly the playerPrefs lines to awake and change set with get. I got 9 errors
well that wont work even with Unity PlayerPrefs
ok, i'll give it another shot
the documentation is pretty clear use either
Color color = PlayerPrefs.Get<Color>("key");
or
Color color;
PlayerPrefs.Get("key", out color);
What have you tried searching for?
Tbh i didn't search for the problem, i tried a bunch of solutions i made up and they didnt work
Do you have any recommendations for places to search for solutions in?
I would try keywords in google, maybe something like "unity c# look at mouse" or something similar
Ight
ok that was embarrassing. I need to study more about the playerPrefs
you might also want to learn about using generics in C#
yeah i need to learn C# better period . That's the bottomline 😄
no time like the present
@cinder spruce tbh all of this would be much better in a script attached to each button so you can use OnEnable to Get and OnDisable to Set
purely from a design perspective
guys going on the unity profiler i noticed this https://gyazo.com/a8fa9841c1882619ab32e2c62974b224 . I'm getting spikes from spriteskin.OnEnable() [Invoke] what can i do to optimize that?
is redImage, whiteImage names of the keys? Why aren't them written as strings?
redImage and whiteImage are cached Image's. It's so you don't repeat GetComponent like you were doing
if you look at my code you will see I am using the button names as the keys
Is using Vector3.project a poor way of giving tight control when it comes to moving a character around? I found that using it and projecting the velocity vector around the players input gives some tight control
define "tight control"
as in, tight as in the time between dictating a direction and the character finally moving in that direction
i don't see how Vector3.Project has anything to do with that 🤔
Projecting a vector has no bearing on tight controls
I thought projecting the velocity vector, basically the forward velocity towards the directions of the players input would give tighter controls
The input is already giving you the direction
How fast you accelerate and turn is entirely based on your implementation
But protecting the input isn't going to do anything useful
that line has nothing to do with that error. you need to remove the UIElements using directive
I found that doing like
rb.velocity = Vector3.Project(rb.velocity,new Vector3(playerinput.x,0,playerinput.y));
gave me tighter control over my character
maybe its just my dodgy code lol
Like this is without the Vector3.project line
and this is the same thing with the project line in.
show the full !code
Posting code
📃 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.
okay, but im not responsible for any depression upon viewing my code
https://paste.ofcode.org/v4DTdyCnaVJYWXxSgvtdHP
you are using GetAxis instead of GetAxisRaw. the former applies input smoothing, the latter does not
you do not need the line to project the velocity, you just need to stop smoothing the input
hi guys, i have a character controller and when i setup the gravity my velocity.magnitude of the character controller is zero when i move and if i jump its not zero someone can help me pls ?
see #854851968446365696 for what to include when asking for help. you're not providing enough info/context which is why you didn't get an answer the first time you asked
Okay, the turning circle is not as loose as before. So yeah there was definitely a problem of input smoothing. Could afford to have the movement be tighter, but I could probably mess around with how I deccelerate my character to achieve the same effect.
@languid spire i added these in awake:
Color redImage = PlayerPrefs.Get<Color>("redButton");
Color whiteImage = PlayerPrefs.Get<Color>("whiteButton");
no errors but didn't work either
you also appear to be multiplying mouse input by deltaTIme which is also a no-no. mouse input is already framerate independent so multiplying it by deltaTime just makes it dependent on the framerate again and also leads to stuttery camera controls
Ah okay, I've just kind of assumed when moving something to always apply delta time to keep the movement the same speed regardless of frame rate.
anyway, thnak you @slender nymph ❤️
ok i will try this. The other way is not working for me
So my problem is when i ApplyGravity the variable currentSpeed return 0 and when i disable the ApplyGravity the variable return 7 the actual speed of my game
I have multiple enemies that I want them to use waypoints as coordinates to travel to.
As of now Im using this code https://hatebin.com/zmqmjolqiz
Im not sure if this is good way. I noticed enemies getting stuck on right side of the movement. And I think its doing too much calculations.
Is there better ways to deal with moving multiple objects at same time?
multiple calls to CharacterController.Move are probably what is fucking that up. you probably need to combine your gravity and actual movement into a single call. execution order of when Move is being called will also likely affect it
https://docs.unity3d.com/ScriptReference/CharacterController-velocity.html
Note: The velocity returned is simply the difference in distance for the current timestep before and after a call to CharacterController.Move or CharacterController.SimpleMove.
look at this
PlayerPrefs.Set(redButton.name,redImage.color);
PlayerPrefs.Set(whiteButton.name,whiteImage.color);
and then this
Color redImage = PlayerPrefs.Get<Color>("redButton");
Color whiteImage = PlayerPrefs.Get<Color>("whiteButton");
Spot the difference?
Hello, I am a beginner. Does someone now how I can make this fit? The wall should be the size, of the white wall on the right.
this is a code channel
Thx for help i get it
but there is no channel for art questions
really?
