#💻┃code-beginner
1 messages · Page 762 of 1
I'm kind of confused cause I have this > transform.position = _portalRef.Exit.position; which already teleports the player to the exit portal so how would I teleport the player to the entrance portal when in the exit portal?
i verified my trigger is what's not working, not the code. I will get back to you guys on whether or not the code works once i fix the trigger!
i appreciate all the help
can you not just use _portalRef.Enter.position
hint: they are both exit portals
From the perspective of the exit portal the entrance portal IS the exit portal
Don't think of them in absolute terms. They are both exits and both entrances depending on where you start from
Each portal just considers itself the entrance and the other the exit
Got it! My polygon successfully switches sprites upon colliding with the powerup. My mistake was having trigger checked but I was using onCOLLIDERenter2d. but now my powerup is solid and i bounce off of it.
If I re-tick trigger to make it not be a solid object and switch it to onTRIGGERenter2d, I get a green squiggly under OnTriggerEnter2D stating it has an incorrect signature
bam. fully working. thanks for the help guys
When I change sprites, I can hit "reset" on the Polygon Collider component for it to reset the bounds to the new sprites shape. Can I do that in the exact same function that changes the sprite in the first place?
Alright thanks for the help! got it working.
nice
got that working! now the players collider is always accurate to the sprite currently used. Only issue now is that with the collider being removed and replaced, the sprite goes up a few times at once as opposed to the intended one time. But I imagine that will be fixed when I change the powerup to a prefab that disappears on contact
i might call it here for today, im happy with my progress
Can anyone tell me why my gravity is fluctuating? It goes from gravity (0.025f) to 0f and back repeatedly
// Gravity
if (m_CharacterController.isGrounded)
{
m_GravityPower = 0f;
m_MoveDirection.y = 0f;
}
else
{
if (m_UseGravity)
{
m_GravityPower -= m_Gravity;
}
m_MoveDirection.y = m_GravityPower;
}
For some reason the character controller is not grounded even when it is?
I'm using a run of the mill third person cam script on a free look cinemachine, this is my movement script for the player. When I rotate the camera the player jerks back and forth and speed is adjusted when that happens. Here is the code for my movement ```private void MovePlayer()
{
movementDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(movementDir.normalized * movementSpeed, ForceMode.Force);
if (movementDir != Vector3.zero)
{
player.forward = Vector3.Slerp(player.forward, movementDir.normalized, Time.deltaTime * 5f);
}
}```
I tried looking some stuff up but failed to find anything I understood. Could someone help me understand the way to do it?
Video reference
From what I understand it's because the players rigidbody movement and position is directly affected by the camera's direction, which is what I want for the movement but the double edged sword is that it affects the position as well. which I'm not sure how to differentiate that. But if my understanding is misguided let me know.
Yeah that's how CharacterController.isGrounded works. It only returns true when the last Move call pushed it into the ground.
I recommend not using it
Got it resolved
Just added a
CharacterController.Move(Vector3.up * -0.001f);
is this a legitimate way to populate Scriptable Objects w/ default values?
why can't you just give them default values?
couldn't think of how to do that..
since theres no Start() or Awake() that runs
maybe im just being stupid
there is awake and onenable but they are weird
you mean they'll work when Creating via the project window?
but also can't you just straight up give the fields default values? like
float myFloat = 15.0f;
ohhhhhhh!
thank you bud!
didn't even see that
personally i dont like default values in code for serialized values cuz they can be misleading when troubleshooting
yeah, fair
lol.. totally suppose i could have..
aye!! 💪
i like it
i've hesitated to use SO's for sooo long I actually forgot what little i knew about em 😆
i've just used simple Classes instead
SO’s are amazing
i just finished up my SaveData system... now im working on the Menu.. and im thinking they could be useful to store
like the current settings data
and have it saved to the json file when game is exited or whatever (if they differ from defaults)
always been told to only use them for non-changing data
the people who say that are cowards
only.. so i think that may have subconciously made me neglect them
not necessarily
lmfao!!
spit out my drink on that one
i use them for channelling events sometimes haha
i tend to overuse SO's so im probably a little bias
my last loading system had a SaveData class that i declared twice
once as the original (loaded into from the local save file)
and once as a run-time version..
and then i realized thats silly.. and i can use just (1) for both
public class ScriptableManifestManifest : ScriptableManifest<ScriptableManifest>
i love them
but yea... i figured it was 💯 true about that non-changing data..
b/c u could always read from em and do w/e u need to do
can also make them at runtime but gotta handle it correctly
or as ways to handle selectable functions in editor in some contexts
SOs make up for what little control you have over serialized classes
one day we'll get interface serialization out of the box with serialized references
i wish haha
eg. for a card game prototype i had a workflow where each ability a card had was a unique class inheriting from a scriptableobject, with 1 asset instance of that said class existing in the project so i could drag and drop it places. Then the functions on the scriptableobject run purely with the context being passed into them and static references so they don't need to store anything unique at runtime, eg.
public class Frontline : MoveData //MoveData is inheriting ScriptableObject
{
public override IEnumerator OnActivate(MoveInfo moveInfo)
{
Debug.Log("Frontlining!");
moveInfo.ally.player.MoveCardPosition(moveInfo.card, 0);
RoundManager.RefreshCurrentStack();
yield return new WaitForSeconds(1f);
EndMove(moveInfo);
}
public override void Initialize(Card card)
{
Debug.Log("Initiliazing Frontline");
card.onBeforeMove.AddListener(Activate);
base.Initialize(card);
}
}
thats dope
Same. If I don't attempt to use SOs for a system or idea I'm working on, then I'm doing smth wrong . . .
This would save countless headaches and attempts at creating custom editors. Currently, my problem . . .
is this a safe metric relative to someone like me? that's not beginner but also not advanced by any means..
using Classes for data storage and knowing I could use a new() instance to set my defaults was a game-changer for me..
been sleeping on SOs for quite a while (well, i'll change that.. from today on I'll try to use SOs atleast once per prototype scene)
since im trying to fill out my exposure to things in Unity i've embarked on a journey of putting myself out there outside my comfort zones.. using the New Input System, utilizing SOs, next up UIToolkit.. and so on
ohh and events... 🤫, I mean i've used events.. but not like i ought to be using them.. and as frequently
I actually thought you used them more. The applications are so broad: events; config data; enums (what I use most); modular behavior, as in, containers for methods (very granular approach), etc . . .
nah i've only ever used them for things like PlayerSettings and Projectile Settings, etc
like this
i've never actually tried to use them anywhere else besides to load up default values for a script w/ lots of variables
Yeah, they're great for any kind of settings . . .
ya, i guess the discussion is about whether u can or should rather, use em for runtime / or variables that'll change
and then having to read them prior
idk..
Like classes and other serialized types, it's great for exposing data to the inspector. The main difference compared to the other two would be where the data lives. With structs and classes, the data would likely be living on some component instance attached to a game object in the scene whereas with SOs the data would be attached to an SO instance (not associated with any specific scene object)
You could mutate the data but it'll not persist if no longer referenced so normally I'd just have a regular manager hold data using an MB component.
The more I can keep out of scenes the better and the more I can keep out of prefabs assets the better. (Imo)
Things that should just do things should not be reliant on knowing things in editor. ScriptableObjects are good at knowing things
Less points of failure
To use your first pic as an example; on a Jump component, you have an _action SO variable with a reference to an SO asset called Jump that has the variables needed to jump. If you get a powerup to double jump, you'd assign the SO asset called DoubleJump attached to the powerup to the _action variable. When you press the jump button, both SOs will display a different action because of their settings. This is easier than overriding many variables and doing so again to revert back . . .
As I mentioned before, I mainly use them for SO enums; much more versatility, because you can have fields and methods . . .
(And for modders they are a godsend in comparison)
Oh, didn't know that . . .
eg. if a game handles some form of content via enum and an outside modder wants to expand that content
Another example of cool SO use that some people might find problematic is that if you have a reliable source of serialized information (eg. a singleton) you can use static getters to make information easily and globally accessible that is actually sourced from scriptableobjects that could be swapped out, eg. I often handle colors with something like
static ColorLibrary _instance;
public static ColorLibrary Instance
{
get
{
if (_instance == null)
_instance = GlobalManager.Instance.colorLibrary;
return _instance;
}
}
public ColorWordsGroup damageColor;
public ColorWordsGroup healthColor;
public ColorWordsGroup currencyColor;
public static Color Damage => Instance.damageColor.associatedColor;
public static Color Health => Instance.healthColor.associatedColor;
public static Color Currency => Instance.currencyColor.associatedColor;
This lets code access relevant coloring easily (via ColorLibrary.Damage etc.) but lets me control that colour from a single source
Yes, these are great for default/global settings . . .
I usually have a debug class with colors for info, warning, error, etc . . .
I use an SO for all of the UnityEngine.Time class fields, so I'm pulling them only once and using those values instead of calling into the engine inside of multiple components . . .
ohhh... i feel like i might know why..
i dont think my projects have ever grown or matured enough for me use them enough
like now that i think about it, if the types of games i made were to be say.. a game w/ a big inventory or a game w/ a big skill tree or even a more simple game like mine, a shooter, had more powerups or weapon combinations or variations i feel like i'd use them out of design choice.. orr if my game was just getting really big.. or i was working on something like an rpg or some complicated ui/ux gameplay system i might be forced to use them more out of necessity
So imo:
-Managers for data that should persist between scenes (and possibly the entirety of the applications life)
-Scriptable Objects for non mutable data that should persist between scenes (and Editor play sessions)
i might just need to use em just to practice.. or expand faster 😄
i've gotten savy to using classes for almost all my persistent game stuff..
i just like the monobehaviour being attachd i guess 😊
but thats still not an excuse
ohh i think i could actually think of some use-cases i'd run into where i'd need data like that..
i just haven't really gotten to there yet.. most of my data lives in their own sub-system classes
and all hardcoded i guess u could say
ahhh.. eureka moment lol
what would be the best way to detect a click on a 2d sprite from camera that will be moving?
makes perfect sense considering its the same icon as other settings.. like the renderpipeline stuff and the postprocessin volumes n whatnot
figured it out.. my game isnt classy enough
raycast
You've got quite a few options but they all will likely use some form of ray casting (whether directly or indirectly)
just an IPointerClickHandler should work fine
if it were ui or something i'd say the IPointer interfaces
or i guess it can work there too.. idk never used it on sprites
you can use them on non-ui objects if you have a physics 2d raycaster on your camera
ahh thats right 🫰
I need your help
Don't cross post. #💻┃unity-talk
click anything in the scene and press F
there's a PhysicsRaycaster for 3d and a Physics2DRaycaster for 2d
since 2d and 3d physics are pretty much completely different systems
the more you know..
i know they're diff systems but i just had thought they shared the same component for Raycasting.. that doesn't make too much sense when i say it out loud
true. i bet your projects are bigger than mine. I just have an empty scene with cubes and components attached to try and create systems that work . . .
i feel called out because an empty scene with cubes (well, squares even) and components is exactly what i have rn
When I see what other people have, like Spawn's triangle shooter, that's when I flood with a bunch of ideas that I could implement . . .
prototyping my beloved
i have so many abandoned ideas
so hard to commit to things and push past getting stuff actually going
eg. i spent a day or two messing with an idea where you'd do some kinda town/city building thing as a way to teach basic computer networking but i got stuck on something and into the pit it goes
cubes and a skybox in one project, and another w/ nothing but a sprite
i've actually adopted that work-flow for alot of systems.. they "theorhetically work" b/c the values are there.. but nothing to represent them just as yet 😄
I like the first one. The colors really pop. I'd use that for a scene/testing . . .
I'm stubborn, so I'll stop working on it until I come across a solution. Sometimes that'll be days or weeks, or sadly, months . . .
I recently tested my stats system and modular damage system to ensure they work. It is satisfying to see the correct values appear. I just wish I could get the custom editor working for the stat system . . .
ya, thats my setup for now.. left one is scene objects and systems
the right is a bootstrapper at heart but ive been using it to test singletons, static utility/helper classes, and UI stuff
soo far this is like the optimo setup for me.. been much more organized and therfor productive by having 2 different projects one being more "back-end" unseen stuff
and the other being the visual and physics gamestuff
If I want a camera to follow a rigidbody, it's best to follow it with code in late update, rather than something like parenting it, correct?
yes thats right. making the camera a child would quickly fuck up as soon as the rigidbody rotated too
i haven't gotten anything done in the past 4 weeks because i've been going back and forth on this one issue and now i'm just going to give up and find an easier solution. is it possible to use aron granberg's a* solution in tandem with custom movement programming? the enemy i am trying to make is hopefully going to move around the player and shoot at them instead of just moving directly towards them
yes, that's what it was designed for. you use the pathfinding to just generate the path, then use that path literally however you want
oh
so if my enemy has line of sight with the player i can make it ignore the pathfinding and just start moving in its own way
Is there an easy way to implement a timer that resets a variable after it has elapsed? I have an int that I having change on player input, then return to the original value after half a second has passed. If the player presses a button in that half second, the timer should restart
i mean, you can still use the pathfinding there. but sure, if you want to instead do your own pathing for whatever reason when you have los then you absolutely can
use a coroutine
alright
ty
i guess i'm going back to aron granberg's then
remember, you don't have to set the target destination for a path to the player's position. you can use whatever valid position you'd like.
what do i do about this
well the last warning actually provides a suggestion for what you can do about it, and presumably the error is related
i don't know what webplayer or standalone is
do i just have to change the build settings?
what is your current build target
where do i find that
i have never made a build before so all i know about build settings is that you can use it with scene management
presumably you have selected "Web" as your build target . . . in the build settings.
i'm definitely being stupid and/or blind right now
i can find a build profiles window but not build settings
it's that
well there you go, you have windows selected, not web
the message said it wouldn't work with web
i never said to switch to web. i am simply pointing out that isn't the issue.
Is there any way i can integrate c++ into unity?
not directly, no. you can use c++ to write native plugins that your c# code can then access
if you want to use c++ why not choose an engine that actually supports it directly, like unreal?
so theres no way to code a unity game in c++
there is no point even trying
i dont want like those AAA game like high graphical type
then make your art style different?
you do know that the engine doesn't dictate your art style, right?
well i dont know how to make it in unreal so the lighting isnt like high quality
i want something like unitys
and unreal just confuses me
then learn c#
im trying but i also want to learn c++
but if unreal is confusing you, then unity will too
you either learn Unreal lighting or learn C# for Unity..
well ive made 2 games in unity
C# is fairly similar to C++ relatively speaking, so you might as well learn C#
without c#?
Then keep using it?
i want to learn c++
You can do that too
then use an engine that supports it
No one is stopping you from knowing multiple languages, in fact for overall developer skills it's probably a good idea
thats why im doing it
Ok
i want to keep using unity but also want to learn c++
Then learn C++ seperately to Unity and learn C# with respect to Unity
ok
I don't see how it's a problem
Damn
im just gonna learn c# then c++
Best of luck, hopefully you'll see that they are similar enough that the load is fairly light to learn both
basically this script gets the scriptable object assigned to the tile below and the above script is what i don't get. i'm lost at the process of dictionaries
📃 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.
Yeah, i've been told before. it takes my skull more then once to listen up appearently. will fix it right away
Dictionaries have <key, value> ... TileBase is your key. You pass in the key and get out the value (TileData)
Could someone help me explain how exactly dictionary work?
How does this connect TileBase with the TileData scriptable object script?
A tool for sharing your source code with the world!
When you add data to the Dictionary, you give it a key and value
the red squares are the obstacles, right? i don't know what happened with the scan but i think something went wrong
i'm just going through a tutorial right now and idk what caused this
Yeah, i was intially misslead to believe that dictionaries were tables when people told me to use dictionaries instead of tables for my variables
I dunno if Dictionaries are classed as tables or not
that helps alot to calrify
i was still thinking they might've been tables.
understanding what it is, is what's throwing me off. i was trying to add more then 2 arguments inside of a dictionary
which didn't go so well.
those I believe are just "nodes"
i disabled this and now everything is blue
no, traversable area is shaded in blue
it thinks that the whole area is unwalkable
oh alright. been a while since i used the A* pathfinding project
i disabled that but now everything's blue, including the area i don't want to be traversable
this isn't a code issue
it looks like Aron G's A* pathing finding asset? If so.. you go to the documentation for that asset, and then his support channels
So my game will be on steam but am also releasing it for sale on my website, I need a clean way to differentiate which version of the game the player is running.
I thought about either using #if STEAM and calling it a day but there are some problems with that. It messes up serialization, for example if you wrap a variable in an #if and assign it from the inspector then the condition of that isn''t met the variable resets to default value the next time it is met. Additionally I would have to build the game twice per platform each update.
I also thought about using launchParameters from steam and just having if() wrapping the calls but that is messy. Any other ideas?
using System.Runtime.CompilerServices;
using UnityEngine;
public class PlayerAnimation : MonoBehaviour
{
private Animator myAnimator;
private const string IS_WALKING = "IsWalking";
[SerializeField] private Player player;
private void Awake()
{
myAnimator = GetComponent<Animator>();
myAnimator.SetBool(IS_WALKING, player.ISWalking());
}
}
using System.Runtime.CompilerServices;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] float moveSpeed = 7f;
[SerializeField] float rotateSpeed = 10f;
private bool isWalking;
private void Update()
{
Vector2 inputVector = new Vector2(0, 0);
if (Input.GetKey(KeyCode.W)) inputVector.y += 1;
if (Input.GetKey(KeyCode.D)) inputVector.x += 1;
if (Input.GetKey(KeyCode.S)) inputVector.y += -1;
if (Input.GetKey(KeyCode.A)) inputVector.x += -1;
inputVector = inputVector.normalized;
Vector3 moveDir = new Vector3(inputVector.x, 0, inputVector.y);
transform.position += moveDir * moveSpeed * Time.deltaTime;
isWalking = moveDir != Vector3.zero;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}
public bool ISWalking() {
return isWalking; }
}
I’d really appreciate it if someone could help me find the error in this animation
the transitions between animation is not working
guys, help me. I tried use "Input.GetKeyUp" but when I start a game, It loses camera. What I have to do???
what object is that component attached to
can you explain what you mean by "it loses camera"?
You should also explain what you are trying to accomplish
Note that this code is almost certainly wrong:
My script attached to empty object
0 * 10f * Time.deltaTime is just going to be 0
So effectively all this code will do is move the object UP by one unit
from the 1 you have
I do it for y coordinate
And since the object is not the camera and it's just an empty object, it doesn't really matter if you move it
what are you trying to accomplish and what do you mean by "it loses camera"?
what's actually going wrong here?
the thing you have for Z is pointless
i'm betting this is also a 6.1+ issue and they are just ignoring the console
when I start a game I see "No camera selected"
that is not related to your code
Drag the game view window side by side with the scene view so you can see them both
and you don't have to rely on the camera preview thing
but when I didn't use Input.KeyUp the camera worked well
look at the console
a.. ok
can anyone help me with my problem i'd really appreciate it
there is
in the code you've shown, you set the animation parameter a single time in Awake, which only happens once on the first frame of an object's lifetime. where else are you setting the animation parameter?
!input 👇
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
thx
for future reference, don't ignore the console. it's typically best to have it visible while playing, and for extra points Error Pause is useful since it will pause execution on any error
SHOULD I TRY PUTTING IT ON ```cs
private void Update (){
}
that would execute eveery frame
youre my hero, thx
it works
thanks man
Hey, I am a bit new and I need some advice regarding the input and animation change.
I've connected the animation as it should and I thought I'd want to try out something new with the bool values to change my animation.
This is what I've currently got scripted, but doesnt work, anyone see the issue?
public Rigidbody2D rb;
public float moveSpeed = 5f;
private Vector2 _moveDirection;
public InputActionReference move;
public Animator animator;
private void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
_moveDirection = move.action.ReadValue<Vector2>();
if (_moveDirection.magnitude > 0.1f)
{
animator.SetBool("IsMoving", true);
}
else
{
animator.SetBool("IsMoving", false);
}
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + _moveDirection * moveSpeed * Time.fixedDeltaTime);
}
I did have
if (_moveDirection != Vector2.zero)
before but it didnt work either
You should debug this by opening the animator window while the game is running and see what's going on with the animator state machine and the parameters
"doesn't work" is a bit too vague
does anyone know have a tutorial for the physics2Draycaster? im trying to find information on it, but all of the tutorials im finding regards 2d raycast instead of physics2DRaycaster, and the documentation isn't very specific. trying to make a script that detects clicks on 2d sprites with colliders on them but cant figure it out
Physics2DRaycaster is for working with the event system
if you want to perform your own 2D raycasts you'd use Physics2D.Raycast and other related functions in your own code
wait sorry
if you want to detect clikcs on 2d objects yes you can and should use Physics2DRaycaster and the event system
What issues are you having with it specifically?
Do you have:
- An Event System in the scene
- A Physics2DRaycaster on your camera?
- A Collider2D on the sprite object?
- The appropriate code in your script attached to the object with the collider?
i havent really started coding yet, just trying to figure out where i should start. This list should help me get started though!
I haven't tried the debugger tool yet, how do I bring it up?
Hey can sombody help me, i actually dont understand why my Code somtimes Shoots and Walk at the saim time. I hope somone can help me there => https://paste.mod.gg/koplnovylfkx/0
A tool for sharing your source code with the world!
i know that this Script is a little bit so bad, i did one enemy Ai and now im working on it, it is a little bit hard to make a boss, but i learned that i need to start a little bit slower

The animator window I said
"debugging" is just the act of investigating and solving bugs
Can you clarify the issue? What's the desired behavior and what's happening instead?
i want that he only shoots, and not running, but he runns and shoots at the same time
what is "shooting"? Spitting?
yeah
I don't see anything in here that would prevent walking and spitting at once
I see basically two disjoint state machines in here
one for movement, one for attacking
Can you point to the code that is intended to prevent shooting while moving?
I think what you need to do here is merge your two state machines into one
spitting and moving should be separate, mutually exclusive states
ich laufe
ur german bro?
You can also just update a bool variable accordingly ... bool canShoot
If you wanted to keep the 2 disjoint/independent state machines setup
@wintry quarry Oh shit dude! I just saw you on a Unity Discussions lmfao. Thanks for the help 😂
https://discussions.unity.com/t/how-do-i-copy-a-terrain-to-another-project/813270
Ah right, in that case I just have a simple idle > walk and condition is just true or false with the "IsMoving" bool
the idle works fine ofc but it just doesn't wanna transition into walk when I am making a input (move around)
the only thing I think might be the problem is this though
(_moveDirection is the vector2 values)
and what'st the state of the parameter in the animator when that's happjneing?
You should be able to see right there if it's being set properly
do u mean me?
Also that code can be simplified without if/else: cs animator.SetBool("IsMoving", _moveDirection != Vector2.zero);
the "IsMoving" parameter is just always ticked off, so it must be on script side
oh thank you
Time for Debug.Log
what do u mean
I uhhh, may have made the casual rookie mistake haha
you said:
i want that he only shoots, and not running, but he runns and shoots at the same time
But I don't see any code that seems intended to cause that behavior. If it exists, point to it. If it doesn't exist, then that is the cause of your problem.
my animator parameter had a lowercase i but uppercase on the script hahsa
thank you for your help though!
oof but now you know for the future that its case sensitive!
i mean this should prevent that the Frog dont jump ands shoot at the same time
that will prevent you from spitting if you're already spitting.
It won't prevent you from spitting if you're walking or jumping or whatever
The crazy part I've been pulling my hair for over an hour trying different methods of the scripts hahah woops
i know how to fix it, i have a idea thanks
am I using this contact filter wrong?? Why is it getting things that aren't on the provided layer? It keeps listing the spawn area pictured in the third image as one of the first things in the buffer. The first image is the script this code is from, showing the inspector.
private void FixedUpdate()
{
var mousePos = _mousePosition.action.ReadValue<Vector2>();
Vector2 worldPoint = _camera.ScreenToWorldPoint(mousePos);
var hit = Physics2D.OverlapCircle(worldPoint, _radius, _filter, _colliderBuffer);
for (var i = 0; i < hit; i++)
Debug.Log(_colliderBuffer[i].gameObject.name);
}
[SerializeField] private LayerMask _layerMask = 1 << 8;
private ContactFilter2D _filter;
private void Awake()
{
_camera = Camera.main;
_colliderBuffer = new Collider2D[_bufferSize];
_filter = new ContactFilter2D
{
layerMask = _layerMask
};
}
yes you're using contact filter wrong
_filter = new();
_filter.SetLayerMask(_layerMask);``` this will do it properly
or:
_filter = new ContactFilter2D
{
layerMask = _layerMask
useLayerMask = true
};
}```
I would recommend just exposing the contact filter directly in the inspector though
oh i didnt even think of that
instaed of:
[SerializeField] private LayerMask _layerMask = 1 << 8;
private ContactFilter2D _filter;```
And using code in Awake. You should just do:
```cs
[SerializeField] private ContactFilter2D _filter;```
I ended up doing
[SerializeField] private ContactFilter2D _filter = new()
{
layerMask = 1 << 8,
useLayerMask = true
};
because it said I couldnt convert from int to ContactFilter2D.
correct, because it's not an int, it's a ContactFilter2D
Sorry I adjusted the example above
you don't need to set any default
but if you do want to set a default you can do it as you showed
how can i shoot somthing in the right directionn, like if the Enemy Shoots left the bullet also should go left? how can i detect the righ5t direction and how do i code that?
because i used a method the looks if the local scale.x is 1 shoot in that direction and the same code logic for the other, but i have the feelinng that this is not the normale way to do that.
transform.right or transform.up depending on how your sprite is laid out
thanks!
I'm getting a null reference exception on this
Startingtransform.position = gameObject.GetComponent<Transform>().position;
Startingtransform.rotation = gameObject.GetComponent<Transform>().rotation;
Startingtransform is null
also you never have to use GetComponent to get an object's transform, every gameObject and component has a transform property that already references it
Startingtransform.SetPositionAndRotation(transform.position, transform.rotation);
save yourself typing^
oh ty
does anyone here use cinemachine alot or have good experience with third person game creation
#🎥┃cinemachine and don't ask to ask, just ask
I'm slightly confused by your statement but thank you for providing the channel I wasn't aware of that 😄
what I mean is - just ask about your question - if someone knowledgeable is there they will answer it
"hello may i ask question about thing" ❌
"hello i have error x and i tried y" ✅
oh ok
Ah I understand. I asked earlier but I don't think anyone was available at the time.
Then again that was yesterday.
Hello, java developer here,
Is it also possible to create instances of an abstract class with objects? Basically I'm trying to make a tower defence game from scratch and wondered what would be a good architecture
abstract classes cannot have instances made but ofc if you inherit from that then thats fine
oki thanks
the point of abstract is to have abstract methods and properties which then must be implemented
does somone know why the Spit is not flying? better said moving?
Don't use inheritance for this IMO.
Use composition.
I.e. an archer tower would have components on it:
- Tower component
- ArcherBehavior component
a sword tower would have:
- Tower component
- SwordBehavior component
Unity is made for composition
you can declare by the abstract type assuming you do insert a more derived type in the editor, but new-ing an abstract class is ano
so you separate the object from it's behavior? I'll read about it thx
Debug.Log
Check what speed is, what dir is, whether there's an rb2d on it, etc
no you separate different components of the behavior on the object into smaller reusable parts
okay i will do that, its just a little bit strange because i coded this one time and it work befor
like Tower would have things common to all towers - the size, the collider, the cost, the experience curve, etc.
ArcherBehavior would actually "do" the archer tower stuff
but yess i will try it give me one second
u was right
now Rigidbody
but why?
can i say give the Object a Component? instead of saying get a Component?
you can add components with code yes
i will add it via editor for performance but i also want to know how to give one
can u teach me how?
Thanks
you are right to realise that its better to just add the component before hand in editor
hahah
So something like this? Where the tower base and the archer behavior defining what the archer does?
wait u mean i should Add a Component via Runtime or do u mean i should search the Component?
I'm not sure what the arrows represent in this diagram
Where the archer have all the attributes of tower and functions of archerbehavior
Add component at edit time, reference the prefab via that component instead of as a GameObject, then Instantiate will return the reference to the component you want so no GetComponent call on the instantiated object required
^ yea that
But what do the boxes represent?
okay thanks!!
After you change the prefab variable's type make sure to drag the object back into it even if it still appears assigned
classes are boxes
arrows represent the inheritance and in this case also the composition
Then no, this is not what I was talking about.
There wouldn't be an Archer class
there would be a GameObject named Archer or "Archer Tower" with two components attached to it - Tower and ArcherBehavior
(and probably others too but we're just focused on these)
I see
My way of doing this is have that single Tower class as the controller. This class would have basic information as Radius, Rotation to attack, and cost to build. Now, for the mode to attack I would accept some sort of ShotData class data that when radius and rotation is satisfied I would Shoot(ShotData shot, position, direction).
Some things to think about when doing this controller + projectile class is that you've two parts, the controller to spawn the objects, and the behaviour of the projectile itself.
It kinda depends how much variance there actually will be in the tower behavior, and how much of it you can shove down into the projectile prefab for example
The projectile itself doesn't need information about how many projectiles are spawned, only how it moves. So this data to say make a fan like shape of projectiles must be presented before that
Isn't it laggy to create lots of projectiles?
I just thought of doing a Attack() function that gets called when there's an enemy in range to not have any sort of delay
Ignore optimization and deal with it later if you need it
I don't understand the shotdata part
the tower class would have an enum with all possible projectiles?
Ok how about this. You have three types of data that define how this projectile(s) is instantiated, and data for how that projectile moves. First data component would define targeting like radius, firing like attack speed, and build costs. Second data type would provide how many projectiles are spawned and in what pattern as an example. Third data type would be how this projectile moves such as homing and perhaps variables like gravity.
Heck, can do a 4th data type for Hit data for when that projectile collides
TowerData, FiringSessionData, ProjectileData, HitData
Tower -> main driver
FiringSession -> Temporary class needed to a coroutine execution of a sequence of projectiles or anything a bit more complex you don't want to do inside of the towercontroller
Projectile -> projectile driver
HitData -> Only exists in data really so no instantiated really needed... similarly FiringSession could just be data too but if you want to run any sort of coroutine it needs to be on the scene instantiated
How to have an enemy detection range?
My goal : When an object type Enemy enters the range of my tower, it attacks
I'm looking at Enemy[] enemies = FindObjectsOfType<Enemy>(); but it is said to be deceprated
How can I detect an object when it enters a range x?
Projectile vs not projectile shouldn't be a decision to make based on performance. It's a game design question
Trigger colliders or using overlap queries
oki thanks
Its a bad looking diagram bro
The arrows are the wrong direction there.
Archer has ArcherBehavior, so the arrow should point from Archer to Behaviour
A depends on B
hey hey can anyone help me out here? i have no idea how to turn this off
the error says it exactly
you can either use the new input system (the recommended way) or change your player settings
yeah i want to know how to switch it off for just this practice project
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
ill definitly use the new one since ive heard great things but I need to learn the unt y fundermantals first
tyty
i would say the input system is part of the unity fundamentals
i will be learning that next then
but im just following this video, its just introducing some very basic things
pong game
and its using unitys old movement system
you should still try to do something yourself, try to modify it - just following it blindly won't teach you much
ill be completing this tutorial then im going to make a new project with one cube, and try adding basic controls to it using the new system.
thats my plan
i'm not really a fan of "completing" or following tutorials in general - i feel like trying to adapt the tutorial or expand on it somehow will teach you a lot more than just following it
but hey, you do you
maybe you can try learning about the input system, then coming back to the pong game and making it use the new input system
Anyone can see why my char can flip when I move to the left?
VS studio says .velocity is obsolete for rigidbody, is this true for any kind of project?
Atm im working on a 3D game with 2D view
yes. it should also be telling you what to use instead
Yeah it tells me to use linearVelocity instead
But github copilot really insists that linearVelocity doesnt exist
don't trust AI, trust the compiler
This is a relatively new change, so a lot of data the ai is trained on points otherwise.
If you're gonna use AI, make sure it does proper documentation search before answering.
its nice of the Unity team to make changes to their API to mess up the spambots output
I don't think that was the purpose...
To be fair, that change was as surprising to humans as it is to AI.
yeah, I'm only kidding 😅
it's funny to ask gpt about the property and it INSISTS .velocty is correct despite telling it otherwise
It's a very strange invention
Hi, i am trying to build a 3d rigidbody character controller and i am facing a problem. When i jump my character constrantly goes up and gravity doesn't show any effect. What could be problem?
private void Jump()
{
if (!_isGrounded)
return;
_isGrounded = false;
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
Show your full script
Is there not a way to get a more direct access to the values of an audio mixer than to search it with a string??
using System;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private Rigidbody rb;
[SerializeField] private Transform body;
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float jumpForce = 7f;
[SerializeField] private float groundCheckDistance = 7f;
[SerializeField] private LayerMask groundLayer;
private Vector2 _moveInput;
private bool _isGrounded;
private void OnEnable() {
InputManager.Instance.OnJumpPressed += Jump;
}
private void Awake()
{
rb.freezeRotation = true;
}
private void Update()
{
_moveInput = InputManager.Instance.GetMoveInput().normalized;
CheckGround();
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
Vector3 direction = (body.forward * _moveInput.y) + (body.right * _moveInput.x);
Vector3 targetVelocity = moveSpeed * Time.fixedDeltaTime * direction;
Vector3 velocityChange = targetVelocity - rb.linearVelocity;
velocityChange.y = rb.linearVelocity.y;
rb.AddForce(velocityChange, ForceMode.VelocityChange);
}
private void Jump()
{
if (!_isGrounded)
return;
_isGrounded = false;
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
private void CheckGround()
{
_isGrounded = Physics.Raycast(body.position, Vector3.down, groundCheckDistance, groundLayer);
Debug.DrawRay(transform.position, Vector3.down * groundCheckDistance, _isGrounded ? Color.green : Color.red);
}
}
First step is always check if the boolean you think is true/false is actually the value you think it is
Add a debugLog on the "_isGrounded" check on jump
i checked my jump method trigger once then i hit space
Well, if you set the y velocity to zero, of course the gravity is not gonna do anything
i also removed that line and tried again 🙁
is that could be a unity bug or something?
well if you're using ForceMode.VelocityChange you probably need to apply the gravity yourself
It's not a Unity bug
Yeah, aren't you reseting the Y velocity each frame on the move part?
Thanks man. i changed VelocityChange from my move method and jump fixed
But still should not be gaining heigh infinitely right?
if you wanna use velocitychange for more control you can just apply the gravity manually
it's just a simple acceleration
It wasn't that. It was because you're adding the y velocity to the force in your normal movement code
Velocity change mode itself was not the problem, but would certainly amplify it
You still have the issue
It's the second to last line in your move() function
Delete that
It looks like it was left over from some earlier movement code
so should i directly give direction?
I didn't say that no
but didn't i overrride Y when i move?
the problem is that you're applying your y velocity as the change in velocity (an acceleration)
so you're literally taking the y velocity and adding it (per second) to the velocity
Your move method should prob not be doing anything to the y velocity anyways
-# also you should normalize your move direction
i do that
oh yeah right, missed it
when I start the game and my mouse is off the game tab like in scene view it gives me an error but if i have it on the game tab then swap to scene it still works im tracking the mouse every frame im not sure if this is a problem or if its just an editor thing
what's the error?
Screen position out of view frustum (screen pos inf, -inf, 0.000000) (Camera rect 0 0 1920 1080)
UnityEngine.Camera:ScreenToWorldPoint (UnityEngine.Vector3)
MeleeRangeController:FollowMouse () (at Assets/Scripts/MeleeRangeController.cs:43)
MeleeRangeController:Update () (at Assets/Scripts/MeleeRangeController.cs:36)
inf, -inf is interesting
Unity bug for the screen position, no worries
oh okay thanks
Some one plz
hello! trying to use cinemachine, but it seems that cinemachine no longer uses priority to switch cameras? priority is now a checkmark that is set to default off. If priority is no longer the main way of changing virtual cameras, then how do transitions using code work?
For reasons I cannot ascertain, Visual Studio is not interfacing with its tools for Unity plugin. I’ve made sure I actually have it installed (quintuple-checked, at this point), I’ve made sure Unity has its own Visual Studio plugin installed, and I’ve made sure Visual Studio is set as the external editor in Unity. I’ve tried uninstalling then reinstalling both Visual Studio and the Unity tools plugin for it, I’ve tried restarting the programs themselves and my entire PC, and it just isn’t doing anything beyond what non-Unity Visual Studio would do. Visual Studio is 2022 (17.14.19), Unity is 6000.0.26f1.
Update: deleted the vs-related files in the root folder and regenerated the project files, that did the trick
Not sure why jumping through hoops to fix this was necessary but it's been fixed nonetheless
The sln/csproj files were likely generated when your ide wasn't configured properly.
There's the "regenerate project files" button in external tools that usually fixes such issues.
guys help. In my 3D Unity project, I can’t assign a PNG from my assets to a UI Image on the Canvas. Why isn’t it accepted as a Source Image?
what should I do?
I do it, don't pay attention
How is this a code question
can someone help me to import 3D model from blender into unity, i've add the fbx using import new assets to the project but the material and texture in blender doesnt work in unity. if you know some youtube tutorial or documentation that you can share to me or even better guide me via share screen i will appricate it. Thank youu
also not a code question
oops sorry, where should i ask this question
#🔀┃art-asset-workflow and don't ask for a private tutor, just show the problem there and if somebody knows they'll answer
okay thankyou
hey does somone know why this code better said debug.log never gets shoot
i mean i used it correctly and i dont see a problem?
did you mean to say it never executed the line where debug.log is at?
because waiting for callbacks from the animator may never happen
yeah i want to know why my debug.line never gets runned
but i debuged the "isHurt" bool and his values was to true every time after getting hit one time, even i said in the code to set it on false
personally I wouldn't yield against the animator. You should have your own statemachine that is calling the animator, you shouldn't need to rely on the animator to tell you the state
but if you do want extra logic to execute when an animation does play, I would suggest using animation events and injecting directly into the timeline
i use this way of animation plays bercausde i dont want to use events for every "Animation Ended"
Ah, yeah I see. Maybe duplicating the animations with different events but that does seem annoying. Could potentially modifiy a single clip at runtime and swap out what that event does.
but at that point you might as well just call the method if it's supposed to execute at frame 1
I added a flamethrower and enemies to burn, but now want a fire particle to appear when i actually burn them. Where do i start with this?
right click, create -> effects -> particle system and just mess around with some settings
is it normal that errors dont get shown in like a res underlining in visual studio?
There are all kinds of error. What issue are u facing?
!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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 1f;
private PlayerControls playerControls;
private Vector2 movement;
private Rigidbody2D rb;
private Animator myAnimator;
private SpriteRenderer mySpriteRender;
private void Awake() {
playerControls = new PlayerControls();
rb = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
mySpriteRender = GetComponent<SpriteRenderer>();
}
private void OnEnable() {
playerControls.Enable();
}
private void Update() {
PlayerInput();
}
private void FixedUpdate() {
AdjustPlayerFacingDirection();
Move();
}
private void PlayerInput() {
movement = playerControls.Movement.Move.ReadValue<Vector2>();
myAnimator.SetFloat("moveX", movement.x);
myAnimator.SetFloat("moveY", movement.y);
}
private void Move() {
rb.MovePosition(rb.position + movement * (moveSpeed * Time.fixedDeltaTime));
}
private void AdjustPlayerFacingDirection() {
Vector3 mousePos = Input.mousePosition;
Vector3 playerScreenPoint = Camera.main.WorldToScreenPoint(transform.position);
if (mousePos.x < playerScreenPoint.x) {
mySpriteRender.flipX = true;
} else {
mySpriteRender.flipX = false;
}
}
}
was following a tutorial on youtube but then i got this error. how do i fix this? its basically a movement script for my sprite
You didn't name your input actions asset correctly
In the tutorial they named it PlayerControls
You named yours something else
okay i fixed it. but now its not moving my position, the animation works but no change in position. is there something wrong with my settings?
Try disabling the animator for a minute
Also make sure your movement speed variable is set to something reasonable in the inspector
This is the beginner coding channel. If it's not related to coding and you're unsure where to ask, try #💻┃unity-talk
great
Hey knowledgeable people, is it possible to get persistent unique ids for game objects by default? Reason: we have about 3000 collectables and are working on a save system so we need to be able to spawn or despawn them in. Or is there an particular better way I am missing?
Our idea was to write in arras of object with some BSON and other data as a save file
When the joined player jumps , in the host's screen the joined player jumps and eveything works fastly . But in joined player screen its slow ( not so much ) . Does anyone know what is the problem ?
don't crosspost. keep it in #1390346492019212368
!code also 👇
📃 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.
hey, i want that the frog should play a "Hurt" Aimation if he gets Attacked by the Player, but i have the feeling that if the Player Attacks the Frog boss to much he will be in a Hurt Loop, i thought about this Game Design. If the Boss is currently dont Attacking he is allowed to play the Hurt Animation, but if he is Currently Attacking i wil not allow to play the Hurt Animation, only allowiungt o blink white for a short time, how can i code that.
public void Hurt()
{
if (isAttacking)
{
// blink
}
else
{
// hurt animation
}
}
i need to this guard on every state?
A tool for sharing your source code with the world!
uhh.........
i'd make a hurt method that gets called when you hurt the enemy
will do that
Should I choose layer or tags ?
I basically want to create a way to differentiate enemies from anything
component checking
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
I usually use layer for physics stuff like raycast, collision… What I would do is using a separate layer to apply on what can attack or be attacked, and tags to categorize them into different types of enemies if I want different interactions (traps, NPCs, other players .etc). It’s just my opinion
Personally I don't know of any reason why you would use tags over component checking period
layers are good for avoiding broad groups of interactions though yeah
Tags are fine for broad things that don't have any other functionality than checking what it is. For example for ground checks, much cleaner to just set a ground tag instead of making an empty component and attaching it to every ground element
I use physics cast to check ground and layer is required
but yeah if you're going to need the component anyway there's no point in first checking for an enemy tag and then doing getcomponent on it
Even then I have the fairly freaky opinion that using physics materials as kinda "scriptable tags" is preferable
Hey y'all, I'm wanting to add colored outlines to drops in my games so the player can tell it's level easier. I have an outline material and URP setup, but I can't seem to change it's color. Multiple materials seem to break the renderer, only rendering the last option. This "SHOULD" read the level from an applied scriptable object and set a color according to the level, but it keeps throwing errors... any ideas? Everything else is fine, just the outlines...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
also directly modifying fields on another script like that is 😬
curious is it really that bad to not use data encapsulation?
When you modify the internal state of another object, the other object must be implemented in a way to always expect these changes. The more fields you expose the more difficult this gets. So to contain this problem you expose data as readonly properties and generally only mutate internal state through methods on that object. This way the object can control its internal data consistency.
certainly.
Especially something like these stats which no doubt have far-ranging effects in the game including being displayed in UI somewhere (probably)
Also, what do you mean by "cache them"? Never heard of that before (only found out what a singleton was 2 days ago 😭 )
save them in a variable instead of using GetComponent every time
which line is this error on?
(line 13, what is that?)
of PowerUp.cs
Says line 13 of powerup (The PowerEffect.Material void), but opening the error goes to my loot script
PowerEffect.Material(gameObject);```
this is line 13
it's pretty clear that PowerEffect is null
you need to assign it
in the inspector
It's assigned from my loot script when an enemy is killed, that way it can randomly select one. Once it's spawned the powereffect sets itself
It's not assigned
or you wouldn't be getting that error
Are you talking about this?
GameObject lootObj = Instantiate(item, spawnPos, Quaternion.identity);
lootObj.GetComponent<PowerUp>().PowerEffect = dropped;```
Awake runs BEFORE you assign it here
When instantiated, it assigns itself
Nah you have the timing wrong
By the time Instantiate is finished running, Awake will have already run and thrown the error
I see thanks
What would be better than? Start or OnEnable or somethin?
neither
make a custoim initialize function
Instead of:
lootObj.GetComponent<PowerUp>().PowerEffect = dropped;```
You want to be doing:
```cs
lootObj.GetComponent<PowerUp>().Init(dropped);
And instead of:
private void Awake()
{
pickedUp = false;
PowerEffect.Material(gameObject);
}```
You'd do:
```cs
private void Awake()
{
pickedUp = false;
}
public void Init(PowerAbstract effect) {
PowerEffect = effect;
effect.Material(gameObject);
}```
I'll give that a shot
some of the naming is a bit confusing to me though
"lootObj.GetComponent<PowerUp>().Init(dropped)" Won't work since It won't change a ScriptableObject to a GameObject
Sorry I made a mistake
fixed it now
So no more error, but still no change to the color
what kind of color change are you expecting
Isn't Level always 0?
I have them both in my abstract class
private void OnTriggerEnter(Collider other)
{
print("Something entered");
if (other.CompareTag("CanBeAttacked"))
{
enemiesInRange.Add(other);
}
}
private void OnTriggerExit(Collider other)
{
print("Something exited");
if (other.CompareTag("CanBeAttacked"))
{
enemiesInRange.Remove(other);
}
}
But it doesn't produce anything in the console
same thing when I move the two
Do I have to call OntriggerEnter or is it called automatically like Update?
its a physics method.. runs every fixedupdate()
I see
it runs automatically when the trigger overlap happens
it does not run every FixedUpdate
but you need to have the correct configuration in the scene, which Box's link will help you check
hmm, didn't know that. so its an event sorta
well the engine must know when the overlap happens in order to trigger it automatically.. right?
of course
im actually confused now
the physics engine is running in a fixed timestep tho?
a tick
The timing for OnTriggerEnter can be found here:
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
Basically it's right after the physics simulation step, if a new trigger overlap occurs
i'll give it a read.. i've never actually read that page.. just referenced the diagram 😅
and yes the physics sim is on a cadence with FixedUpdate
okay.. that makes me feel a bit better lol thought i was fried
I only had issue with you saying "***every ***FixedUpdate"
also FixedUpdate is before the physics sim step, this is after, which is sometimes relevant
there's ya a solid answer.. see:☝️ context n all 😄
aye, honestly never seen/clicked into the contextual links
https://docs.unity3d.com/6000.0/Documentation/Manual/collider-interactions.html oh neat... here's a solid page ive never seen before either.. this one would be useful many-a-times i've been in
I think the problem is totally unity... And not me haha
I use some sphere collider to hold everything together
okay and which object has the rigidbody on it
I have never used Rigibodies
basically, I have a cube with an ArcherBehavior and a ball with a PeonBehavior
I have something like that
abstract class Tower : MonoBehaviour {
protected List<Collider> enemiesInRange;
protected SphereCollider rangeCollider;
protected SphereCollider initiateCollider()
{
if (range > 0)
{
SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
rangeCollider.isTrigger = true; // Can detect things
rangeCollider.radius = range; //size of range
return rangeCollider;
}
else return null;
}
private void OnTriggerEnter(Collider other)
{
print("Something entered");
if (other.CompareTag("CanBeAttacked"))
{
enemiesInRange.Add(other);
}
}
private void OnTriggerExit(Collider other)
{
print("Something exited");
if (other.CompareTag("CanBeAttacked"))
{
enemiesInRange.Remove(other);
}
}
}
Tower
public class ArcherBehavior : Tower {
public Awake() {
initiateCollider();
}
}
archer
and the enemies have the same collider initialization
I have never used Rigibodies
there's your problem.
if you would actually bother going through that link i sent before you'd see that a rigidbody is required to send collision and trigger messages
Aren't collider enough just for the function enter and exit?
there must be at least one rigidbody involved in the trigger overlap to send the trigger message
very well
Unity version control keeps nagging me about changes in files that are unchanged. When I diff them they are identical. Is this a known issue? Any workarounds?
is it your own files or is it stuff from unity like Text Mesh Pro related stuff? i ask because i recall a recent editor patch fixed an issue with version control noise related to some specific unity stuff
It's not files I touch, but I can imagine them being touched somehow in the background
what version of the editor are you using
6000.2.8f1, and version control 2.9.3
I'll try upgrading to latest-latest
could someone explain the difference between these two?
anyone reccomend any good videos to learn unitys new player movement system
Any idea why is the OnTriggerEnter and OnTriggerExit is triggered twice for two sphereCollider?
image 1 gets the actual sender's id from the rpc parameters while image 2 wrongly uses the local client id which would just be the server's own id instead of whoever sent the rpc
i think
send the 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.
that sounds correct, because on both host and client I was getting clientID = 0
man this whole multiplayer thing is so confusing, but definitely a lot simpler than I was worried about
Object n°1
private void OnTriggerEnter(Collider other)
{
print("Something entered");
if (other.CompareTag("CanBeAttacked"))
{
print("and it's an enemy");
enemiesInRange.Add(other);
}
}
private void OnTriggerExit(Collider other)
{
print("Something exited");
if (other.CompareTag("CanBeAttacked"))
{
enemiesInRange.Remove(other);
}
}
SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
Rigidbody rb = gameObject.GetComponent<Rigidbody>();
Object n°2
SphereCollider rangeCollider = gameObject.AddComponent<SphereCollider>();
they both have colliders (range set to 1)
I suspect it has to do with both edges being detected as entering and leaving
Hey everyone! ive been running into an issue with a scriptable object asset i created and cant figure out why, so thought id try some luck asking here.
My asset says that the assocaited script cannot be loaded and to fix compiler errors, but there are no compiler errors, and adding anything to the script and saving, even if its a comment or a blank space, makes the asset work again. But it breaks again during the next project open or whenever i switch scenes.
Any idea what it could be?
Ive tried reimporting all and the file name and class name are the same, all the classes are system serializable
Do you have more than 1 scriptable object class definition in a file?
nope
i have a different scriptable object by itself and that one never had any issues
If the class definition is in a file with the same name (MyCoolSO.cs -> public class MyCoolSO : ScriptableObject{) it should work fine
What you describe reflects what I had in the past when I had the class def share a file with another
yes, both colliders in a collision/trigger event will receive the collision/trigger message
yeah thats what i read online as well, but it has always been that way, the names always matched
How do you make the assets? CreateAssetMenu attribute?
Do newly made assets work correctly?
i tried making a new asset and it didnt work, same issues as before
📃 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.
yeah sure
A tool for sharing your source code with the world!
It doesnt need the Serializable attribute but I see no reason for this to break
are you doing anything strange with meta files or asm defs?
nah i havent touched any of that so far
i dont even need to edit the script itself, editing any script in the project also makes it work again
Hey knowledgeable people, is it possible to get persistent unique ids for game objects by default? Reason: we have about 3000 collectables and are working on a save system so we need to be able to spawn or despawn them in. Or is there an particular better way I am missing?
Our idea was to write in arras of object with some BSON and other data as a save file
Object.GetInstanceID should do the trick
though the ids do not persist between sessions!
Yeah that's not necessarily helpful as it doesn't persist hence no way of loading a save file 😭
i see
you'd probably have to generate them yourself then
I feel like I'm dumb this seems such a common use case for almost any game that I feel like Im missing something. Yeah maybe.
is it? i can't think of a scenario i ever needed a persistent unique id for objects
Well any RPG like game. Removed chests, boxes, non-respawning game placed game elements seems like common for those type of games
i mean just a simple sequential id should work fine for them
generally any implementation needs to be fairly specific to the game its built for so it's hard to make something general like that
Okay so I assume best way to go write a custom script which adds a unique id to any object when creating in the inspector is prob the best idea so they can be saved
that should work fine
I just generate GUIDs on everything even though Unity does have some utility I prefer to have the control
asset IDs are fine though and they wouldn't change between session. Not guarantee if you do patch the game though
Sounds good guys thanks!
the standard way is to serialize a per instance-GUID as a string in a field on a root-level component of a gameobject you want to identify. then store those GUIDs in your save. On restore find the objects with those GUIDs and inject the saved data into them. If you want your save-system to restore dynamic objects, you would need to make a asset-lookup and store a unique asset ID next to the instance IDs in your instanced objects that points to the prefab from which they can be restored (this works similarly to how netcode spawns/despawns objects in clients).
well, I spent all day learning the basics for C#, would the next best thing be to look at several hundred tutorials and disect how they go about making their games?
now that I can probably vaguely understand how anything works at all in this software?
if you feel confident in your c# abilities, then maybe take a look at unity !learn and start learning the engine. think of features that you'd want to implement and try creating them. Lookup tutorials to help you get there but most tutorials are horrible code quality
if this is your first language, a day in c# likely isnt going to be that much honestly
maybe make a calculator in unity 😄
well, i've had prior knowledge, so most of what I learned was more like- getting a bit deeper and learning how it actually works, but I think I might have some confidence in how to make some things
Time to make a highly complex leveling system that genuinely doesn't actually work
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
just realized the link didnt send before
the smaller the project the better and it's hard to accidentally overscope a calculator. also skill checks you on using unity to handle inputs (pressing buttons) variables (the current values of the calculator) and outputting to text
suppose that's true
well suppose I SHOULD ask, how decent of a teacher is W3Schools
buddy of mine sent it to me ealier and said it was decent
as a resource? extremely solid. as a teacher? pretty bad imo
I find it very helpful when im new to something and need a pretty isolated, working example snippet of how something works fundementally
so as a newbie it's probably pretty good because it showcases a fundemental process of using it?
but outside of that, it's better as just a resource?
Yeah, it happens to most people so don't take it personally but its very easy for new people to get choose paralysis on mix-maxxing the best possible resource they could be learning from
A lot are going to vary in different ways but anything relatively ok is better than nothing
heard
how do i fix this
A lot of non-interactive education kinda ends up being teaching how to follow given instructions which can help drill certain ideas in and get comfortable working with stuff but a lot of getting to the point where you can actually think of an idea and start making it comes down to learning how to learn, where you can dumb down your idea into micro steps and determine what you dont know how to do so you can then learn that isolated thing
kinda rambly i've been awake way too long 😄
well, Maybe it helps i've been straying a little bit to see how to combine a few of the things I learned, though it made me wish I knew more about User controls
it didn't much on ReadLine(), I tried to figure out how to use an If else with ReadLine and couldn't get it, it was one of the few that got me
as well as a lack of information on what exactly Type Casting is used for, other than that it's "rarely used"
it kinda lacked on If else and boolean, restricting it to numbers and never really interacting with anything else
for beginners it really do be rarely used, but casting tends to be when you know a little bit about something but you may need to know more about it (it's very related to the concept of inheritence so if you don't really know that you might not get it)
Inheritence, like, the idea of passing down something? A statement passing down information to another statement kind of deal?
I don't wanna get ahead of myself on guessing
kinda but more in the context of something as a whole
can i assume youve played minecraft
yeah
how do i fix pls
what've you tried? it just says installation failed
idk i just get that whenever i try to install android stuff
i closed the hub and ran administrator but that didnt do anything
so for example mobs, a lot of mobs share the same fundamentals (moving, being hit, doing stuff etc. etc.)
instead of making classes for each mob and redoing all that kinda stuff, you can make a "base" class for Mob and then "inherit" "from" Mob in order to use it as a foundation and build ontop of it
but yeah this is probably slightly abit ahead of where your at so no stress if it's abit much
ok.. have you looked online for any information on this specific quote?
yea
a method? I think that's what it is?
it's a base you can work off of right?
I think i get it, it's like an empty character you can apply a model, animation, and stats too, in the gamey kinda way of putting it
right?
methods and the class itself yeah. you probably don't need to know the specifics of how that works just yet but the broad idea is nice to be aware of
more or less yeah but the concept of this kinda layered functionality can be applied to anything really
A Microwave might inherit from Appliance which might inherit from Furniture etc.
so it's layed "what you can do, i can do" type of thing
that would explain why I didn't really get it
I think i still managed to use it at some point in my strange code
if it's the same thing were thinking of
more specifically "what you are, i am (and potentially more)
im trying to make an object that can show me tile coordinate that object's in while the game is not running,
tried if (Application.isEditor && !Application.isPlaying){ Debug.Log(convertWorldPosToGridPos(transform.position)) } in update but it doesnt work.
how do i do it, people in unity forum claim it worked, am i missing something ?
https://discussions.unity.com/t/how-would-i-get-a-script-to-execute-only-in-editor-but-not-at-runtime/645157/5
were talking about Convert.tosomething() right?
I think I get how that works a bit better
do you have the ExecuteAlways attribute on the class
Hi I'm beginner in shader, I'm trying to make a simple linear gradient in Unity in shader code that have controls with the start and end but when my _GradientEnd is 1, and my start is 0, my expected output should be all red as that's my end color, cause I assume 1 should be like 100% but why is my output still like a 50/50 gradient?
I'm confused at why you think it would be red? Your range is 0->1 between the two colors
yea google AI suggested that, it worked 🙂
Hi, i am trying to build a rigidbody charachter controller. I am not sure should i override linearVelocity or addForce. Which is better for movement?
setting velocity is for very specific scenarios. You wouldn't use it as the main driver to your controller
because every time you set the velocity you forgo any forces that were placed upon that body
Friction, dampening, elastic behaviours wouldn't even apply
But many tutorials and AI examples i generated doing the movement method like that
AI examples is a bad way to learn. They can help you if you know what the output means. tutorials are depending on what you are trying to achieve. Sometimes it makes sense to fully control the velocity, sometimes it does not.
It depends what kind of movement you want and what is moving (platformer character, car, etc.) Setting velocity directly gives precise control over the movement, but it won't look natural without a lot of extra work.
Thanks, can you suggest me any tutorial or resource to build a 3d rigidbody character controller?
character
Again, it depends on what you want to do. Did you look into the official unity tutorials about character controller (the unity one) and other movement scripts?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
my restart button isnt working no matter what i do
can i share the project to anyone to see if you are able to fix it
You can show your code (hence the channel name) and tell us, what the restart button is supposed to do and what is happening right now.
its supposed to respawn the player
this is the code public void Restart()
Debug.Log("Clicking restrt.......................");
Scene currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
} ```
it wont work no matter what
!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.
not work means, your log is not firing? or only the sceneload is not working?
its showing everything else is just fine
but when i click it wont respond
even the debug message isnt showing up
How did you attach the method to your button then?
And what is the "button". UI? 3D? give some info about the setup pls
Is that a standard UI button? Do you get any errors in console?
yes standard no errors
Does your button react to your mouse hover?
no
how do i tell theres nothing in the hierarchy
How do you know there is no cat in a room...
..im still learning
its fixed
1 more thing
when the game starts if i try going left(jumping off ) it wont let me and theres no colliders in the air on the left so i have no clue whats stopping me
📃 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.
A tool for sharing your source code with the world!
yep, thanks
Need some help with basic character movement. My player is moving and rotating sporadically when I'm not even touching the controls.
https://paste.mod.gg/vgixmfjfxtxi/0
A tool for sharing your source code with the world!
And when you move left, it will just stop at a certain position?
yes but only at that certain place otherwise i can move left just fine
I would start commenting out code blocks to figure out, where the system starts rbeaking
A certain place? Please clarify
i can go further left from the grass
are you sure, there is no small 2d collider stopping you at whatever point?
yea id figured the same but if i try to jump i acts like theres a wall of collider
in the image im moving left and somethings stopping me
Just for testing. Can you move your visual level to the left or right and see, if the invisible border goes with it?
!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.
Hi!!
so i got started with multiplayer, people around me suggested using Photon Fusion 2, but i am stuck as their documentation doesnt really explain things in details, can someone suggest some sources to get implementation practical guidelines for photon fusion 2?
(plus dont really know where to post this kind of discussion, if i am not allowed to do it here then do let me know.Thanks.)
My player is a rigidbody that has a collider that's horizontal to the ground.
It's comprised of two capsules that don't touch and they make a "T" shape.
Anyway, when I move push the player forward, it often catches on the side-to-side part of the collider and starts flipping towards the ground.
What should I do here? Increase angular drag (and maybe drag) and add more forces when moving/rotating?
I don't think switching the collider to a box would help with that. Maybe I'd need to remove the upper part of the T collider?
If it’s not supposed to rotate at all, you can just lock rotation straight on the rigidbody
freeze constraints
or use probuilder to merge them if you still want the rotation
I think there are some good docs from photon about how to do things, as far as I remember. What are you stuck on?
#1390346492019212368 could also be the better palce for general questions about networking if you dont have a specific code question
just the basics tbh, like how to initially set things up in unity(not the get photon app id etc etc, like the network runner and networkdatabase manager yk)
thanks!!
thats not covering a lot? https://doc.photonengine.com/fusion/current/tutorials/host-mode-basics/1-getting-started
Fusion Host Mode Basics explains the initial steps required to start a Fusion project. A general understanding of Unity and C# is expected.
its like direct to the implementation yk, i was looking for something like how different things are working but ig gotta really hit and trial through things to get my required things set up(cuz its a 2d kinda game so yep)
Yeh, you just gotta adapt to your needs. But there is no tutorial that could magically know what you need 😉 Just try and read on the docs when you need a function from photon that might already be covered.
The difference between 3d and 2d is not really relevant for photon afaik. If you need to clamp 2d positions, you basically sent a vector3 with z = 0 for example. So thats more up to general coding than networking with photon or netobjects or whatever multiplayer variant you chose
well the major part i am stuck at is mostly in docs/tutorials its like peer to peer, and even if its host mode, then it goes like a single host and a single client, i got like a single host and multiple clients so yep, but ig not everything is to be spoon fed🏃🏻
yeh, also that is covered in the tutorial I have sent you from photon docs. Host mode, shared mode and what not 🙂 youll get the hang of it, im sure
thanks thanks!!!
It is supposed to rotate when I'm moving the mouse.
What do you mean with this other comment
Can't freeze them
The rigidbody lock rotation for each axis locks physics rotation not code
perhaps reduce friction.
also not a code question
hello, i have this code, shot a ray from the player to the middle of the screen, that's working while the player is centered aswell but i have an offset on the player with cinemachine
private bool TryGetRaycastHit(out RaycastHit hit)
{
Ray screenRay = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
Vector3 rayOrigin = origin.position;
Vector3 targetPoint = (screenRay.origin + screenRay.direction * 100f);
Vector3 rayDirection = (targetPoint - rayOrigin).normalized;
//Debug.DrawRay(rayOrigin, rayDirection * distance, Color.red, 1f);
return Physics.Raycast(rayOrigin, rayDirection, out hit, distance, mask);
}
the ray should go from the player to the center of the screen, any solution?
tried transform.TransformVector() but it doesnt work as expected
Idk what this has to do with this. I'm just saying I don't want to lock rotation on any axes
That's actually a good idea. Physics material, right?
yes. consider moving to #💻┃unity-talk or #⚛️┃physics if you want to continue
Do you mean you have a 3rd person view like this and you want a ray from the player character like the arrow?
You can use probuilder to merge the two capsules together
Then they will act as one object
But if you want to seperate them then it wont work
Hi, I'm a beginner and I need some guidance.
I'm trying to make a system where a character launches projectiles randomly from a "deck" of cards. Each projectile has physics and the same set of stats but with different values like speed, power, etc.
Later on, I want to program a menu where the player can see their full deck with all the different projectiles and add new ones.
Right now the projectiles in the "deck" are prefabs in a list. Is there a better way to do this? I've heard scriptable objects being talked about but I'm not sure what that is.
I just want to know if I'm on the right track or if there's an even better way to accomplish this before I go down a rabbit hole. Thanks!
SOs are containers that hold data. If you're doing something like an inventory or item system (including cards), they're a good usecase because you can create an SO for each thing and define a bunch of the values of it.
Such as an Item SO that lets you give it a name, price, description, etc.
I hear you shouldn't use mutable data though
I see. Right now I have all the data in a single script.
But with an SO the object would have its script that controls all the physics, and then a separate Scriptable Object attached to it for all the stats?
SOs cant be attached to GameObjects like Monobehaviours can it'd be a reference in the code or serialized field
But you'd probably want a controller script that has a list of every SO card and a single prefab that can be instantiated with anyone of the SOs
Thank you! So I can keep the list with prefabs that I have now, and when I want to do the inventory screen, that's when I'd start using the scriptable objects?
The SO doesn't "control" anything, it's purely a data container.
A card in your case would be given the SO that contains its information (as a reference would be easiest). Then your game logic would use that to do whatever it needs to.
When the card "attacks" for example, you can pull out the damage values from the SO on that card to calculate the final outputs.
I guess where I'm confused is that what I'm drawing from the deck are random projectiles prefabs. So where could I use the SO? Like in the stats of the projectiles, or in the inventory showing all the projectiles?
If youre projectils are wildly different, then keeping them as separate prefabs and just putting all that information directly on them as properties or even hardcoded into their unique controller scripts, is fine. I don't think you necessarily need SOs here unless you want an easy to modify their individual design values without opening the prefab.
SOs really shine when you have a template prefab that you modify/dress up based on the SO its given.
Got it! Thank you
@keen dew yeah, i mean, its working, the problem is the camera offset applied to the player
Right. After the first raycast you need to do another from the player character to what the first raycast hit
Note that this is a problem that doesn't have a satisfactory solution, only a lot of tinkering to make it work somewhat satisfactorily
i was trying to add the offset directly to the target, or the origin so the ray goes straight, but after that it goes crazy
is taking the target from the world and not the 2d canvas space, like if the ray is long enough it will reach the center of the screen inside the world
There is no center of the screen inside the world. It's a continuous line from the camera to infinity
You have to pick a point from that line (which is what the original raycast is doing)
Hi im trying to make a function in a vr game where two flasks with different colour liquid can be mixed together howevr i cant get the script to work
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
!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.
how do i turn the playback rate of an audisource up when a bool is true?
so ive got a sprinting system and i want the speed of an audio clip to speed up when running, but there doesnt seem to be a playback rate var of anykind?
that can be done w/ really short footstep sound clips..
where u control when they play..
so ur code will play them quicker together when sprinting
[] [] [] [] [] vs
[] [] [] [] []
I don't think there's a playback speed variable, but you can raise the pitch to simulate it being faster?
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/AudioSource-pitch.html
i shall give it a try
[Header("Step Intervals")]
public float walkInterval = 0.6f;
public float runInterval = 0.3f;
void Update()
{
if (Input.GetKey(runKey))
{
currentInterval = runInterval;
}
else
{
currentInterval = walkInterval;
}
// then a timer
timer += Time.deltaTime;
if (timer >= currentInterval)
{
PlayFootstep();
timer = 0f;
}
}```
something like this is what i was referring to @bitter pine you can also use pitch as Digiholic mentioned to compliment it
so ur play short clips at different rates
good stuff good luck 🍀
though i changed up the way they split, mine wait till its done, play a coroutine with waitforseconds then play the next, is your way better in some way?
or?
no.. not necessarily.. i wouldn't ever say one way is better than another if they achieve ur desired outcome
kk
i just like simple timers in the update..
but for more refined control i do use coroutines just like u mentioned
if its anything more than "you hit the timer limits -> do the thing -> and reset the timer"
i'll use a coroutine
Not that it probably makes any difference in this case, but I generally prefer doing timer -= currentInterval. Just zeroing the interval essentially adds half a frame delay in average (so do coroutines I assume, unless specifically taken into account). If the game lags immensely the sounds could in theory get stacked for upcoming frames (if subtraction was used) so timer %= currentInterval would probably be fine too. I assume we don't want to have a loop either to play multiple sounds the same frame so the modulo should just discard the extra intervals that might be stacked up in the timer variable.
Again, doesn't make much difference usually, but just a small detail that is very easy to add
ya, we all have our timer preferences
some ppl like adding the next interval onto the limit
others like to reset timer completely..
some people like counting up and some people like counting down lol
In theory there is a small difference in framerate independence so it's not only about preference but it's mostly notable for things happening in very fast intervals.
It's bit similar to how velocity += acceleration * Time.deltaTime isn't fully framerate independent but most don't care taking that into account (even though it's not particularly hard) due to how little the difference is. Well that is framerate independent way to increase the velocity but if applied like that to a moving object, it will not be
has anyone have experience with "resistance" in joints? I have a configurable joint, which acts like a hinge joint, inherently a motor.
What I'd like to do, is, prevent the connected body to NOT rotate, until the motor is rotating it. The motor is just a very simple clockwise/anticlockwise input setup. But whatever the motor is controlling, sometimes changes its initial configuration, due to gravity. which makes sense. I'd rather not disable gravity on the controlled rigidbody, but resist it
I've tried zeroing out angular velocity, but it kinda just falls slowly. I don't want to actually apply a countering force, because when I tried this, this ends up creating forces of its own.
Playing with confiugrableJoint.targetRotation has yielded a nicer results, but I have no idea how to actually calculate it and set it. Just Quat.Angle(initial, current), seems to give the correct angle, but its not very accurately simulating
so what ur saying is if i wanted complete accuracy i shuldn't be resetting my timer to zero
This is not very code-related
Yes, setting it to 0 will overwrite what you had already cumulated in timer. Afaik that should add half a frame of delay in average to each time you are resetting the timer. Let's say your game would run 50fps (deltaTime = 0.02) and you wanted to reset the timer 10 times a second. You would end up resetting the timer every 0.011 seconds by average (0.1 + 0.02 / 2.0). Often not impactful but something to keep in mind to know where it is fine and where not.
sounds to me he's manipulating the joints via code.. so its 50% related.. but I posted a response in #⚛️┃physics cuz they probably have a better hang of joints in general and all the physics components
ah, i kinda knew this but never had anyone explain it to me 👍
thanks for the insight.. i'll look into this a little later..
i'm working on a new code-base luckily.. soo i wont have dozens of timers to refactor or atleast look at
even has a nice flow-chart Unity’s time logic definitely gonna add this to the bookmarks
timer drift lol
Usually my timers would look like this to also take care of the case where you need to do that whatever thing multiple times a frame (especially important if interval < expected deltaTime):
void Update()
{
timer += Time.deltaTime;
//while can be replaced by íf-statement if we won't have timer >= interval * 2
//due to high deltaTime or/and low interval
while (timer >= interval)
{
DoWhatever();
timer -= interval; //the important part
}
}```
ohh i think i had a eureka moment... soo its like if the timer passes the threshold.. but is not an exact divider you'll have some "remainder" that gets yeeted
Exactly
ahh i get it now 👍 thanks friend
if we're discussing on that level of delta, that means the second time around that remainder actually adds up to your timer, and hence its a little faster the second time around
yup, makes perfect sense to me now.. just never have used it for anything precise enough to notice
i've heard stories of when you run a game for hours on end you'd def notice a difference.. if ur timers have been running since bootup
void Update()
{
float dt = Time.deltaTime;
totalTime += dt;
minuteAccumulator += dt;
while (minuteAccumulator >= interval)
{
Debug.Log($"A minute passed! Total time: {totalTime:00}s");
minuteAccumulator -= interval; // the magic part
}
}```
yea that -= interval is smart 🧠
imma do my timers like this from now on
trying to think of any edge cases where this wouldn't work perfectly fine for me..
but can't think of any off-hand.. soo imma roll with it
instead of: resetting timer to 0
we're basically resetting only the part we used keeping the remainder to carry over on the next duration,
neat 👀
precicely
only took me 4 years and a handful of months to figure out something soo basic 😆
i think i've been cautioned before but was always too ankles-deep in work to consider figuring it all out.
im pretty sure they were like "it'll work for basic simple timers (only controlling (1) thing).
glad i stopped this time and looked into it
ohh.. and the while() instead of the if() makes more sense too
didn't think of that until just now.. it would correctly log (2) times if we had some stupid long lag spike or something
instead of the if() just jumping over one
Well, it will keep the extra time in the timer and take care of that in the next frame but the issue arises when the game is constantly running on deltaTime more than interval in which case the if will execute every frame but the timer will keep going up which is often not wanted. In this case however when what we want to do is play a sound effect, we probably don't want to fire the same sound effect multiple times on the same frame even though we would be behind the schedule. Also trying to catch up by playing the sound effect in consecutive frames after a lag spike would probably not sound very pleasent either. That's why I suggested using timer %= interval which would just remove all but the remainder. Depends on the case what we want to do, but in most cases I choose the while together with -=
good stuff.
yup, so it just depends on teh use-case of the timer 🙂
"all things are relative" - someone i bet
Something that can usually be taken into account in the code but the issue is essentially that single precision floating point values are only precise up to around 7 significant digits. If you need to present the current time since start using float you would be limited to millisecond precision once 10k seconds have passed (around 3 hours). In some math intensive calculations that might be enough to cause noticeable defects. For that reason there's also the Time.timeAsDouble and such methods in the Time class which use the double precision floats (double) with which you will never in million years run out of precision. Too bad most GPU's only support single precision floats so to avoid these issues on shader effects to which time is passed requires some tricks (like resetting the time passed by intervals that don't cause a flicker). note that the 10k seconds and millisecond calculation is only accurate to a magnitude level, the point was just that on thousands of seconds, you would start getting bit limited by precision
i did used to have a GameTick script that kept up with multiple frame-rates / tick-rates
and would just fire off events that all my other systems relied on..
i used it mainly for AI / Enemy Sensor Arrays..
like it could think x amount of times every second...
it gave a bit of "randomness" to the enemies movements
i think i'll redo that system using that while method just for exercise
is there anyone who wouldnt mind hopping in a call with me to help me out?
you'd need to use an external website to get support groups or..
edit: Unity Developer Community has VC channels.. but this is more of a community channel..
you ask out in the open publicly..
a. - to get help from everyone
b. - to help everyone that way someone can search thru the conversations and find useful information for themselves.. if they're having the same problem
There's no command called
colab.
⭐ Hello guys, what is your recommendation for Hands IK on 2-handed weapons? ⚔️
I've set up some "rotation & position" config so, any item can attach fine to the Player's right hand,
But with 2 handed weapons, well, now there has to be a real-time IK target indicating which spot on the weapon to hold (left hand)
And furthermore then aiming the weapon, totally breaks both hands IK, rotations etc, and looks terrible...
Thanks for your help guys... trying to avoid needing like 4-5 config rotations per weapon lol
itd be a bit rare to run into this case considering the max delta time is 0.33. a simple use case would be something like a gun that you'd expect could fire more than once per frame (like a minigun)
put a target gameobject on the weapon.. should be able to set the IK's target or hint to that
Fair enough... seems like the most obvious solution so I was avoiding that
yea, i just like to brainstorm a little deeper into things b4 i use them..
i know i probably wont run into edge-cases that wouldn't work with it..
but as a thought exercise i just like to make my rounds
👍 thanks for the headsup tho 🙏
lmao.. why u just trying to avoid common solutions?
Tbh just post the question. screenshots & code too. I'm sure we can solve it quickly
i can look for alternatives a bit later during lunch.. if its not cool enough for ya 🤪 lol
Idk i was tryna be fancy and just have a local position / rotation config per object 
but yeah the invisible game objects way is probably easier
u could use it just for target positioning..
Actually my "config per object" would then hold references to those invisible hint objects
and break out ur rotation and stuff in something different
you using Unity's Animation Rigging package?
heck yeah
ok so its probably a simple fix but heres my code which the error provided is refering to
or something like FABRIK
heck ya, its a solid package ngl
i love using it for procedural animations
think like a Kraken's tentacle
Object reference being Null. just means the script is trying to access a variable or something that isn't technically assigned
it's so great. like to make my sprint animation more dramatic, i just tilt the spine1 spine2 spine3 forward lol
so what should i do to fix it?
so it says thisThing.DoFunction()
but the code is like umm.. which thisThing? i can't locate it
The if in Awake is reversed
thats confused me even more ngl
What exactly are you trying to do?
Looks like Singleton stuff here
in ur error the last bit is the Script thats causing the error.. and the Line Number
Sharing data between different scripts?
sooo.. on that line.. what code is it accessing?
Your if(instance != null) instance = this; is wrong
ohh that could be it ^
ok what should it be?
And wouldn't it have to be created, if there is no instance?
If(instance == null) instance = this;
it was flippity flopped lol
Or technically, as a MonoBehaviour, the one object it's placed on, would be the instance
i tried this before and its still giving the same error
i also tried without the if statement completely and its just instance = this
What are you trying to accomplish exactly... are u following an outdated tutorial by chance 🧐
is the script in the scene?
yeah its like 5 years old but i cant find a better one
Send it bro i'm sure i have a better one
5 years isn't that old tbh but it could be a faulty tutorial
Are you ever creating the Attack_Script class?
https://www.youtube.com/watch?v=e2PRI19Igbo im following this tutorial
Ever wanted an Easy solution at coding a 2D Melee Combo System inside the Unity Game Engine?
Correctly coding it can be frustrating: the majority of solutions you'll think of or find on the internet will be either overly complicated or not even work.
No worries! WIth this tutorial you'll be able to code your own 2d melee combo system in unity ...
Does your Idlebehaviour class (the one with the null pointer error) have any reference to this Attack_Script instance?
what does this mean?
is it in your game?
Only case where this would actually be much of an issue is where the interval is very short (potentially much shorter than we expect deltaTime to be). Ended up in a bit of tangent from the way I personally like to do timers, in most cases I just figure it wouldn't hurt changing an if to a while. Depends on the actual use cases whether this would ever make any difference in practice, in most cases not. As I explained later, it also doesn't always even make sense to do the same thing multiple times a frame
i put this in which isnt in the tutorial but it removed the error in that code
it wont work if it stays in the Project Window.. and never actually added to the game.. or on a gameobject
so your saying make it into a prefab?
doesn't have to be a prefab.. but it must be in the Hiearchy
When you run the game the attackscript var is null do you have anything that references it, ie share the code for idlebehaviour
Usually things are created in Awake / Start, or static or something else whatever
Then you need references to those things
Here it seems like you are trying to get a particular instance of the AttackScript,
The question is, from where? @flint rover 🤔
heres idlebehaviour code
statemachinebehaviours are attached on animator states inside the animator window
if it helps im at 10 mins on the youtube vid i sent before
So no you have nothing that tells idleBehaviour what Attack_Script to use