#💻┃code-beginner
1 messages · Page 248 of 1
it'll matter if anything else moves your transform
but i would figure a coroutine is frame independent
if your transform is getting moved by anything else, then you'll get different behavior
i googled it
this is a good point
its fps dependent
if anything else is tweaking the transform.. its gonna throw off the smooth damp
unless u calculate it independently
It's just managed data that's updated every time you call it.
yes, they'll run every frame if you always do yield return null
consider doing what spawncamp did: instead of smooth damping from transform.position, store your position in a variable and use that
and then assign the result to trasnform.position
this person is expecting coroutines to run more than once per frame
of course that doesn't work
alright i’ll get home in 30 mins and i’ll try it
i concur with u.. when I isolated (as you did) zero issues.. but his code is involved to say the least
yield return new WaitForSeconds(...) tells Unity to resume this coroutine as soon as possible after that much time passes
i think that will solve ur issue 🤞 as minute as it sounds
Yes, it sounds very plausible to me
It just damps the value so that you don't overshoot with cameras and whatnot.
this guy see's in slow motion 😆
Where'd you get this? 
Does anyone remember how to turn on raycast/spherecast debugging in unity 2023?
youd have to ask Mniszeko
I definately remember it being a setting but cant remember where it is ahaha
from my experience you need custom scripts to do that
Nah in 2023, there is 100% an option for it ^^
you mean the physics debugger?
I used to use it a bunch
it's under Analysis
thats the one thank you
ohh yea i forgot that exists
window -> analysis -> physics debugger
go to Queries and uhhh
smash the "everything" button
I think they're referring to the setting in the settings somewhere
you owe me a keyboard
ya, i forgot about the physics debugger
thaanks
i was trying to throw my boy nomnom a bone too 😄
I have a page containing all the options lol
I should add Handles and Gizmos here perhaps...
don't you also have a physics visualizing asset too?
It's linked on that page with Nomnom's
ahh cool 👍
It does not, no. It's for visualizing 3D physics.
This does, though!
I dont see why it shouldnt work though since its the same render enging 😦 oh well thank you
enging
new word
they're completely different physics engines
PhysX for 3D, Box2D for 2D
they have nothing to do with each other
Does a raycast count as physics?
ofc
Yes. But it's 2D physics, not 3D physics.
Nothing is stopping you from just putting a 3D collider on a sprite
Handles are epic.. I'd let them bear my children if I could
Would it work with tilemaps though?
Im basically wanting to make a game with grappling and want the player to be kinematic when grounded, and rigidbody when not ^^
(I have no clue how I would manually program grappling hook physics otherwise
So what's the 3D element?
tilemaps are such a re-occuring issue/ question..
I dont know where you got 3d from?
You suggested to use a 3d collider, and I asked if that would work with tilemaps since they have rigidbodies
ur tilemaps use rigidbodies?
interesting..
i presume you have a player with a Rigidbody2D and a tilemap with a TilemapCollider
ohh okay, lol i was wondering
anyway, to visualize the raycasts, consider using this
Ah, I think I missed what the issue was, I thought you were asking about how to use a 3D Raycast in 2D, but you were instead asking how to use the Physics Debugger in 2D
i gotta show my boy some love and try out his asset.. im ashamed to say i havent even used it yet
Ignore me, I walked in on a conversation in progress and thought we were talking about a completely different thing
yup I just installed it ^^
it happens
npnp
Whjilst on the topic, is my idea to use kinematic for ground movement, and rigidbody for grappling and gravity a... good idea?
or is it horrible and going to set everything ablaze
like platforms?
It's not a terrible idea, but it's a bit complicated. Normally you'd either bite the bullet and either deal with the fiddliness of dynamic rigidbody movement or coding in your own kinematic grappling.
Coding in kinematic grappling sounds awful
🥲
either or sounds exhausting tbh
if I had to choose one of those two, I would probbaly do rigidbody movement
and just try to finetune the settings
Gonna try my idea first, see how well it goes.
as a side note.. I cant actually figure out how to install the package, I installed it via package manager, but it doesnt work as described haha.
Yeah, but if you want total control over the physics you'd need it at some point. I have no idea how good the physics engine will handle transitioning between the two states but if you don't run into any major issues you can probably get away with it
Open the Package Manager from Window/Package Manager
Click the '+' button in the top-left of the window
Click 'Add package from git URL'
Provide the URL of this git repository: https://github.com/nomnomab/RaycastVisualization.git
Click the 'add' button``` you used this method?
Because its definately installed
already done that part, yeah
Have you added the namespace?
it should be in ur project already.. then..
Do, I know 4 different programming languages, but I dont actually know what that means 🥲
ya u just need to use the namespace.. and VisualPhysics shuld be avail
Ive never really googled it. lemme google quickly and understand
Though, 0103 might indicate you're using it in a completely invalid place—won't know without seeing code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public float speed = 200;
Vector2 move;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.AddForce(move * speed * Time.deltaTime);
RaycastHit2D hit = VisualPhysics2D.Raycast(transform.position, -Vector2.up);
if (hit.collider)
{
rb.isKinematic = true;
}
}
// Update is called once per frame
void Update()
{
move = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
}
}
Thats the entire thing.
yeah, missing namespace looks like it
No need to presume
Not entirely sure where I would find the name of the package
Did you read the link vertx sent? It shows a quick way to do it
probably not
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
you'll be doing urself a favor.. trust
egh cant find my vscode install kek
Ill do it when I get back, need to walk dog. thanks for the help peeps
I’m a bit confused on trigger vs collision, if I have an object that:
Doesn’t pass through walls, but instead bounces off them
Activates a method and passes through the player
How would I do that? I can code the bouncing, I’m just not sure how to make it pass through some objects and make it collide with others
Also this is 2d top down and I don’t want physics to apply to anything, other than detecting wall collision, and I stuff to move only explicitly.
I believe someone told me how to do part of this, but I just don’t know how to do the different interaction types
trigger you can pass thru.. collision you cant
if u want it to pass thru objects. u can set layers.. and in the physics settings u can manually set what layers interact with what other layers
called the Layer Collision Matrix
you don't have to use Triggers.. just b/c u want something to pass thru it..
triggers are meant to be activated(do something in code).. like if u walk thru a metal detector.. it'd Alert.. and tell the code to do something
Ah
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("We collided");
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Triggered");
}
}```
How did you add Adding a Winner Zone trigger to finish the level? Like when creating a game
^ OnTriggerEnter
course you'd want to use something like a tag and CompareTag("PlayerForExample");
to know if it was the player colliding with it.. and not just the ground or something
Alright, Im tired of messing with this lol, who wants to make like 10 bucks, maybe more, doing some rigging and maybe programming
pfft, I wouldn't open my editor for less than 100
lol fair point
you the dump truck kid?
Tow truck
Hardly a kid though, left that title behind about 10 years ago
I could use people who are interested in my project
i like physics.. and mechanical things..
WELL I DO TaKe OfFeNsE nOoB lol
why does it work when they do it, but not when I do it?
Instantiate(f1, new Vector3(12, 12, 5));``` is it because I use a tilemap and they used a gameobject? Does that change anything?
before coding.. i was a mechanic and a carpenter
funny enough, I am a mechanic by day trade. run my own business
i figured
its why im willing to pay someone to get this part solved for me lol
or u wouldnt be doing something like ths
I fix this shit, I dont build this shit lol
a tilemap is 2D
ahh
thats a 3D coordinate
just got a cs1503 error
do you know how to export a .unitypackage
whats the error say
I do not @rocky canyon
i cant memorize 1000s of error codes
cannot convert from 'UnityEngine.Vector2' to 'UnityEngine.Transform'
Oh yeah? What is a P0304
was already writing it :)
how about the most common, CS1002?
P0304 is an automotive error code, I'm being a smart ass since Spawn was a mechanic at one point
ahh
mines just the semicolon error
shade tree mechanic.. never had an OBS reader
OB2*
pshhhh hack LOL
P0304, Cyl 4 Misfire
what would I do to turn it into a transform?
my cars were junk too.. all i had to do is short out the connector with a paper clip.. and count how many times the check engine light flashed
theres a line number w/ the code.. whats the line of code
P0301-P0308 (and more for those 10 and 12 cylinder engines of course) are all misfire codes for a specific cylinder. P0420 is catalyst efficience, usually clogged cat
Alright, got that package for you @rocky canyon i assume shoot it at you
the instantiate code
I thought that was clear
here it is again
speaking of.. my kia.. is misfiring atm, my valve cover gasket is busted.. and leaking oil on top of the 1 cyl spark plug 😈
You would not. That doesn't make sense
Instantiate(f1, new Vector2(12, 12));```
VCG on Kia is pretty easy, YMM?
Because they use the proper method signature - they also pass in a quaternion, and you don't.
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
The second parameter is the parent
we're getting off topic.. but i just got some red sealant.. gonna patch it.. a new gasket is 50 bux.. forget that
Im confused. my ide is definately configured now but I still dont get errors
ill hit you in dms with more info but do NOT use red sealer for gaskets
If you don't get errors, it is not configured
literally what I'm reading on the side... thx anyways
wdym?
Package is at your door @rocky canyon
Do you know what a parent is?
Do you see all the method signatures in the documentation? Which one fits your call according to parameter count?
There ya go. It is a reference to the transform component you want to be the parent
is there any other way to have the instantiated object go to the position I want without doing that in its own seperate script?
Look at overload 4 of that link
Note it takes a vector3, NOT vector2
And it requires a quaternion
You can do whatever you want
Why not just move it IN the instantiate though?
because it's a tilemap so I can't do 3d and it doesn't accept 2d for some reason
Well 2d is just 3d with a z of 0 (simplifying things)
So that is a non-issue
Just pass the vector2 you had as a vector3 🤷♂️
I run into that problem
Because you did it with the wrong overload
You have to use a vector3
Just pass the vector2 you had AS A vector3
As in new Vector3(2,2,0)
cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Transform'
then I get this
The problem is the param count...
You are doing it wrong
You must include the quaternion as I said above
Dear lord almighty
Just look at the docs and see for yourself that there is no Instantiate method which takes ONLY the prefab and position
this is code-beginner
I'm already in this channel
That is a link to a specific message...
Anyways, I'm sorry for my stupidity and, thanks for the help!
your profile picture is incredibly annoying (or bugged on my end)
transform.position = Vector3.SmoothDamp(transform.position, position, ref ladderPositionVelocity, ladderStartPositionDuration);```
so basically do that ^?
Sooo im lost as to what I missing regarding this... I have the correct external tool selected, I have the package installed (even have the unity extension in vs code installed)
Did you click regenerate project files in external tools?
or like this?
transform.position = position;```
THATD be a no.
thank you
It's not in the guide unfortunately
The button doesnt "seem" to do anything, at least not visually, though I do have this error now. So perhaps this is the issue?
Ah yeah, did you get the c# dev kit extension?
@swift crag @rocky canyon
it didnt work
was i summoned?!
indeed
Is this vs code? Or Visual Studio?
where might one find it, its not on the page vscode actually tells you to go to 😄
unless Im blind
(equally possible)
well shit
found it on an entirely different page.
idk, is there anything else modifying the transform?
nope
holy shit
yo
i think i figured it out
after 3 days
YESSSS
the transform had a rigidbody right
and its interpolate mode was set to interpolate
thats why
i set it to none
Pog, its working now. appreciate the help!
and its working perfectly
same for everyone else ^^
so i just gotta set the interpolate mode to none whenever im laddering
@ivory bobcat @teal viper cause i know u guys helped me over the past two days
if your curious why it didnt work
Yeah, that makes sense. That's why I said "isolate it entirely"
Well, glad that solves your issue
How do I figure out the layer of the raycasts return?
Currently its triggering on the players capsule which is of course not ideal 😛
Raycast doesn't return a layer.
I see
https://docs.unity3d.com/ScriptReference/RaycastHit.html
Assuming you mean a RacastHit, you can access it through the collider or gameobject
But different overloads return different things
Is there a way to make the raycast ignore the player?
Layermask
Pass in one that doesn't include the layer the player is on
Yeah the moment I typed that I thought "wait isnt there a layermask argument for raycast"
xD
I would put the number of the layer correct?
nvm I get it.
layermask is an array!
or something similar. Ill work it out
If I disable a collision on the LayerCollisionMatrix, will triggers still activate?
I mean, that is basically right yeah. Vertx's link explains it well.
But I just wanted to say that yeah, it can become confusing going from layer INDEX to a layermask.
It's best to just create a layermask variable and set it in the inspector
public LayerMask raycastMask;
No
Hmm. So I have a projectile, I need it to collide with the map in the sense that the projectile will not move through the map and activate OnCollisionEnter, but I need it so the projectile will pass through players, but still activate OnTriggerEnter on the player and projectile
If it has a trigger collider it will not cause OnCollisionEnter
Well, I need it to collide with the map but not with the player
Can you not just have it destroy itself if it does OnTriggerEnter on the terrain?
Or do a ricochet logic
Yeah, do I have to worry about it passing through the wall?
i havent tried this personally but maybe adding 2 colliders and setting up the physics layers would be possible.
I would really just have it check against some kind of map layer though in OnTriggerEnter then do your logic
like passing through a little bit before it activates the ricochet logic
no matter the solution, every wall, floor, or object you want this projectile to hit is gonna have to be a different layer from your player
You would have to handle that case, yes. It would have to have a rigidbody, and setting it to continuous collision mode would reduce the possibility of penetrating walls at any reasonable speed
Well, it wont be going too fast, so that should be fine then
do I make the rigidbody dynamic or what?
Yeah, for OnTriggerEnter
How would I stop all physics then?
I don't want my projectile to simulate physics, just do the OnTriggerEnter
Choose a different method.
Raycast in front of the bullet maybe
So raycast, make the length of the ray the velocity's magnitude (I don't actually have rigidbody velocity but just the amount im translating it by) id assume so it doesn't move farther than the raycast, then if it hits a wall, do ricoshet logic, and if it hits a player, do that logic?
Yeah exactly, that is a pretty robust method, you just need to control all the physics yourself obviously (which it sounds like you want)
You can then do a layermask to be like the collision matrix too
What would it mask?
Layers you don't want the raycast to care about
Well, sorry. To be clear, it would be the opposite. It would ONLY include the layers you DO want to hit
Only three layers, map, player, and projectiles
So now for the player, I want it to collide with other players and map objects (as in not go through them), but still not simulate physics and I dont need anything to happen on these collisions. Would I do the same raycast and trigger method, but just make it not move if it detects a collision?
Hey, I'm having trouble subscribing to an event. It's CrawlStateEnter in Test.cs https://pastebin.com/swbbDyRk
Oddly it throws null exception in only one of the two events and I can call CrawlStateEnter only once.
Everything is referenced in the editor.
The error has nothing to do with the event. crawlState in Test is probably null. Make sure you don't have other instances of that class in the scene with unassigned references.
According to this it's not
if (textboxController == null)
{
var _textboxController = FindObjectOfType(typeof(TextboxController));
textboxController = _textboxController.GetComponent<TextboxController>();
}
Is there a specific function that finds an object in the scene with a given component, and returns that specifc component, or is this up above the correct way to do that? I'm struggling to find out from what I've been investigating.
Seems to be the only game object with CrawlState.cs too
FindObjectOfType<TextboxController>() does just call the generic version
also the one you called does to, you just have to cast the result, but the generic version is the correct one to use
so FindObjectOfType<TextboxController>() would return the TextboxController of an object in the scene correctly?
Thank you very much for the help. I appriciate it.
try it, it will return the first TextboxController it finds that is in the scene and active, there is a bool to include inactive if you need
Ok, I solved the null error, but it keeps calling CrawlStateEnter only once
What was the issue?
That the event CrawlStateEnter is being called only once, after that it only calls CrawlStateExit
I mean what caused the null reference?
As for the current issue, add logs to where the event is supposed to be invoked and see if it prints.
How would I make a track for a moving platform? I want to be able to display where a moving platform will go, because right now it's really hard to know where you'll end up.
A line renderer maybe?🤔
What if I want to make it look nice, with a custom texture for instance?
Yes, that was it. I messed the _Start function and forgot to restart a variable causing the function to only run once
Still a line renderer maybe.
Thanks for the help
Line renderers do that? Cool... I didn't know...
yeah line renderers do that, it can tile a texture along the line on y axis
Sure. It just generates the mesh. You can apply whatever material you want to it.
also sprite shape might work for you
What if I want the line to be animated (eg., a moving lightning bolt)?
first is it just 1 straight line, or a bunch
Should be possible the same way as with a regular sprite/mesh renderer.
or a path that curves
No, the path is a straight line, so I think a line renderer will work.
Thank you!
if its always 1 straight line, even just 1 nice sliced sprite would work
I thought I might try using just rb for the 2d controller, but my character bounces over the tilemap
ive read that this is a limitation of box2d, but that post was from 2016. any ideas?
i'm not sure what "bounces over the tilemap" means
like, you're getting caught on the boundaries between tiles?
i'm just figuring out 2D physics right now myself, so I haven't had that issue yet
If I use a box collider for the player instead, the player randomly just stops
Maybe your sprites are slightly too small.
What if you switch the tiles from Sprite to Grid collision?
it's an option on the tiles, not the tilemap collider
I havent seen that. Ill give it a try in a sec
Am I using unity actions correctly?
using UnityEngine;
using UnityEngine.InputSystem;
using System;
public class PlayerInput : MonoBehaviour
{
GameActionMap S_GameActionMap;
public static event Action doSomething;
private void Awake()
{
S_GameActionMap = new GameActionMap();
}
private void OnEnable()
{
S_GameActionMap.Enable();
S_GameActionMap.Player.A.performed += ActivateButton;
}
private void OnDisable()
{
S_GameActionMap.Player.A.performed -= ActivateButton;
S_GameActionMap.Disable();
}
private void ActivateButton(InputAction.CallbackContext context)
{
doSomething?.Invoke();
}
}
It seems that if I invoke my actions in my input script, I'll have a ton of actions declared
Is there a way to declare my csharp public static event Action doSomething;
In the class where I use it?
I thought of using a static class instead, but It feels a little weird to make a seperate static class
you declare it in the place you invoke it
and sub to it else where, where you want to listen for it
In an Abstract Class, I want an if statement that checks if the component is of a specific type or not.
Is there a way I can check which specific inheritor of an Abstract Class is being used, or check if a specific inheritor is on the object in question?
if (obj is SomeType objOfSomeType) { ...
it feels pretty backwards for the base class to try doing logic based on the child classes, what are you exactly trying to do?
if you need to check for many types there is also a pattern match with switch you can use as well
but yeah it does feel strange for the base class logic to need to care what type extended it
normally this would be for something that consumes the abstract type, and need to work differernt based on what extends it for a edgecase
I'm using it to throw errors if variables aren't set, but some of the child classes don't use those variables, and I want to supress the Debug.LogError if the class doesn't use the variable in question
using UnityEngine;
using UnityEngine.InputSystem;
using System;
public class PlayerInput : MonoBehaviour
{
GameActionMap S_GameActionMap;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;
public static event Action doSomething;```
What happens if I want to invoke a ton of actions inside 1 script?
My input script will have like 50 action declarations
My script will start to look like this ^^^
well this is not valid code, but why would you need so many
like you can use Action<T> instead
then pass data into the Invoke when you call it
maybe make another child class which specifically handles which variables are needed. A layer between the base class and the actual child class. The base class shouldnt care about this at all, you'll never stop editing the base class everytime you need to make a new child class.
Or maybe just throw some extra logic into the base class like some protected bools so it knows what variables to not check for, and child classes can change those bools
I need a lot because It's my player input script, If I wanted to map every button to something, I would have a lot of actions
just use the new input system, itll do what you're trying to do already and better
Maybe I could just change the method in the child class using an override, then?
they are, but are trying to wrap it with static events for some reasons
🤨
like you can make as many instances of your GameActionMap to map with as you want
no need to do it all from 1 place
You could but itd be slightly annoying because you'll have repeated logic in each class that wants to override it. Ideally you could have some way for a child class to "toggle" what its checking for
Magic:
public static event Action<Key> KeyPressed
Then invoke that one event with whatever key as a parameter.
even if i was redirecting it through events, i would use only a small amount of events that have args that are passed
such as the enum value or a tiny struct
I tried doing this:
public class AnotherScript : MonoBehaviour
{
public static event Action doSomething;
private void Awake()
{
doSomething += SayHi;
}
void SayHi()
{
Debug.Log("HI");
}
}
But then I cannot do this:
public class PlayerInput : MonoBehaviour
{
private void ActivateButton(InputAction.CallbackContext context)
{
AnotherScript.doSomething?.Invoke();
}
}
I can only subscribe events with AnotherScript.doSomething
you cannot do that because you cannot invoke events from another class
hmm, yeah ;/
But some how I can subscribe events from another class
It would make sense to me if I could do this above
AnotherScript.doSomething += SomeMethod
if that wasnt an event, just an action, that should be fine to do. but this all seems very weird to even need to do
if the instance it is on matters its common to keep the event static and pass the instance as the first arg
Events are supposed to have one source and many subscribers. That's why you can subscribe to it from wherever, but can only invoke it from the owner.
but also makes no sense subbing to a event on the same type that defines it
hmm, what happens if I want to invoke the same event in different scripts?
hello! when i set up a camera to make it follow a cube and the cube colldies why does the camera fly all ove the place?
what you want to do feels more like a basic reference and function call
like the idea of events is you make it many things can sub to it from all over the code base
You would request the owner of the event to invoke it. But that sounds like a bad design idea(depends)
and they all see when its invoked
why when i have lower fps the firerate is slower?
do i multiply it by Time.deltaTime?
like this
To get around this would making the declaration for this event in a static class be a bad idea?
So, I can invoke the action from any script?
have it not be a event, but you want for this is strange
That wouldn't change where you can invoke the event from.
It feels like you're trying to solve a simple issue with a weird solution. What exactly are your rying to do?
I can just not use it right now, but I am curious now that I typed it, would something like this result on an endless loop?
correct
unconditional infinite recursion
it's worse than an endless loop, I guess
Unity just instantly dies when I do that (on macOS, at least)
I want to decouple my code,
So a trigger can invoke a function without knowing where the function is or what it does
I very commonly do this by writing
public float Foo => Foo;
What should I use instead?
What does that do?
it's a property called Foo that returns Foo
which is a property called Foo that returns Foo
you can see where that's going
to me it doesnt seem like your solution actually is dependent on fps. Maybe ive missed something. This might just be an issue that the fps is too low, and the game is running too slow.
imagine if you had 1 fps, your game is running Update ONCE per second. No matter what you set the nextFire time to be (lets say in 0.1 seconds from now), update wouldnt run within 0.1 seconds and you would at best shoot 1 second from now.
Similarly if you had a fire rate of 1 million bullets per second, your game would never actually run that fast to get 1 million shots out in 1 second
I have never seen the "=>" before so I am kinda confused by that XD
indeed -- and there's another problem
suppose your weapon fires once per second
and you're getting 1.1 frames per second
frame 0, t=0: fire. next fire at 1.0
frame 1, t=0.9: don't fire
frame 2, t=1.8: fire. next fire at 2.8
frame 3, t=2.7. don't fire
why crosspost this to all 3 channels, read the #📖┃code-of-conduct and delete it. This isnt a coding question.
wtf i just noticed you pasted it to literally every channel
you're losing a bunch of time
I prefer to do weapons like this
[SerializeField] float fireRate;
private float delay;
void Update() {
delay -= Time.deltaTime;
while (delay < 0) {
delay += 1 / fireRate;
Fire();
}
}
This avoids "losing" time caused by frames and the fire rate not perfectly aligning
It can also fire several times per frame, if necessary
Wdym by "trigger"? And, you can do that with one event with parameters, defined in the class that you originally shared.
Could you explain why this is a bad design choice please?
If you don't actually want events, just don't use events.
event is just a way to ensure that only the owner can invoke the method
There's nothing stopping you from slapping a System.Action field on something
so its fine?
Well, because that goes against the concept of an event. An event is something invoked in one place with one or many subscribers that could react to it.
yeah u got a point
What am I looking for?
where an event doesn't have an owner, I want to trigger a function from any class. But I want this to be decoupled.
feel you are thinking about the purpose of events backwards
basically yea, if you do what Fen said then you can ensure the firerate is accurate. Really though as a user, I wouldnt expect my game to fully function if it was running at 10 fps suddenly. A ton of games have bugs with lag
a event is just a message on a system that something happened, and many things can choose to listen to it
its invoked from 1 spot, but listned to by many
That would be just a delegate.
I'm more concerned about the subtler loss of fire rate you get if your frame rate aligns poorly with the fire rate
It can be really bad in certain situations
if you do not want this restriction just remove the event keyword
Thank you 🙂
how do i fix it?
by doing this
Oh,
of course, making the weapon sound right is another matter (:
if you just play a sound every time it fires, it'll sound a tiny bit choppy
...then again, I never really noticed that in the games where I've used this strategy
so it's probably fine
Anything where you fire multiple times per frame probably shouldn't be playing an audio clip for each shot
Why would you want to invoke your events from many places though? Assuming it's still for the input use case.
switching to Fuller Auto and crashing fmod
Just multiple triggers who want to invoke the same event? I'm just trying to think ahead on how to structure my code.
i feel multiple triggers just makes it harder to follow
when i think of my events they are owned by 1 system
but if thats what you want use the same code you have, just remove event keyword from those lines
Yeah. Just remember to set delay to 0 if you aren't firing and it goes below 0
Otherwise you'll bank up a ton of shots
achieving Fullest Auto
wait so where do i set it to 0
if you aren't firing
oh okay!
if you are firing, the code already raises delay back above 0 (by firing the weapon)
and only if delay is below zero
only if delay is below zero.
otherwies, letting go of the mouse will instantly end the cooldown
Mmm just a quick query, if I wanted to use 2d physics, can I use 3d models still;?
Sure.
the only important bit is if you use the URP 2D renderer
it may not play so nicely with 3D models
so like this?
Hmm I did choose urp mode but I supose I could just make a 3d project, and use 2d code
Right.
so before it wasnt really accurate?
the firerate
before what?
the way i was doing it
what i had before
There were two problems with that logic
One: You can't fire more than once per frame. This isn't very likely to come up unless you have a super-fast-firing burst weapon (or the game gets down to a low framerate)
there are ways to fake multiple shots per frame
The best approach is to have a hierarchy in you code. At the very top you'll have something like a game manager, that governs the overall game loop. It would hold the topmost events and you can request it to invoke a certain event for something, like game over or game start. Below it would come some specific systems or managers, like PlayerController or something, it might have events like OnPlayerDied or something. Each of these classes would hold ownership of these events and would be the only one invoking them. Since PlayerController would be the ultimate source of truth for the player live/dead state, it would be the only one that can and need to invoke the event. It wouldn't make sense to call the player died event from a random stone in the scene, even if it was involved in killing the player. Makes sense?
but its much more complicated
Two: You lose any excess cooldown time. So if the weapon is almost ready to fire on frame 1, it sits around for a long time before frame 2 comes around
That time gets lost.
egh nevermind, I want the pixelart style ahaha
like if its a projectile, you can calcualte how many shots should happen per frame, then adjust starting positions of projectiles to fake it
By subtracting the time per shot, you get to keep that excess time
@buoyant schooner similarly, no other script than GameManager should decide wether the game is over or started, thus it should be the only class invoking these events.
Yep, that makes a lot of sense!
So, would I be storing my most important actions in this Game Manager? Then I can access Game Manager to invoke the event?
If you find yourself having an event that many scripts need to invoke, then there's something wrong with assigning responsibilities to your classes
Again, you can't invoke events from outside. It needs to come from the logic inside the owner.
the game manager manages the game
it's not just a dumb bag of function pointers
If it's a game over event, for example, the game manager would be checking the win/lose conditions on update or on certain events and if they're satisfied, invoke the appropriate event that it owns.
It's fine for other things to tell the game manager about what's happening
like "The player just died"
or "This objective was completed"
also you mentioned some of this is your want to reduce coupling
events do not reduce coupling it just reverses where it is which can be rather helpful at times
But you shouldn't be grabbing it by the collar and forcing it to end the game
Hmm, ok!
I guess it would make sense to only trigger an event from 1 script.
I think I need to now look at some example player input script designs
Your player controller logic should be mostly in the PlayerController, so you wouldn't need to forward input events from it anyway. There might be some exceptions, but for most cases it will be like that. Thus what you're trying to do is confusing.
But, shouldn't the logic and the input be separate?
It is though.
The input is handled in the unity input system.
All you do is receive and handle the input, which is the responsibility of the game logic.
You're trying to add additional layer of abstraction for the sake of adding additional layer of abstraction.
Which doesn't make sense.
what am i doing wrong? I setup a list and fill it and when i come to a method inside the same class after the game starts the list is empty.
1
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
Added house: House (3)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
2
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
Added house: House (2)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
3
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
Added house: House (1)
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
4
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
Added house: House
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:101)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
5
UnityEngine.Debug:Log (object)
NPCBehavior:FindHouses () (at Assets/Scripts/AI/NPCBehavior.cs:102)
NPCBehavior:Start () (at Assets/Scripts/AI/NPCBehavior.cs:41)
code
void FindHouses()
{
GameObject[] houseGameObjects = GameObject.FindGameObjectsWithTag("House");
foreach (GameObject houseObject in houseGameObjects)
{
House house = houseObject.GetComponent<House>();
if (house != null)
{
houses.Add(house);
Debug.Log($"Added house: {houseObject.name}");
Debug.Log(houses.Count());
}
else
{
Debug.LogWarning($"GameObject with 'House' tag is missing the House component: {houseObject.name}");
}
}
}
public House FindClosestHouse(Transform npcPosition, Seeker npcSeeker)
{
if (houses == null)
{
Debug.LogError("houses list is null! Ensure it's initialized.");
return null;
}
// Filter for valid houses
var validHouses = houses.Where(house =>
house != null &&
house.transform != null)
.OrderBy(house => CalculateDistance(npcPosition, house.transform, npcSeeker));
if (!validHouses.Any())
{
Debug.LogWarning("No valid houses found.");
return null;
}
No valid houses found.
UnityEngine.Debug:LogWarning (object)
NPCBehavior:FindClosestHouse (UnityEngine.Transform,Pathfinding.Seeker) (at Assets/Scripts/AI/NPCBehavior.cs:63)
NPCBehavior:Determine (MYNPC/npcAction,MYNPC) (at Assets/Scripts/AI/NPCBehavior.cs:168)
MYNPC:DetermineNPCAction () (at Assets/Scripts/NPC.cs:340)
MYNPC:Update () (at Assets/Scripts/NPC.cs:168)
sorry update hit enter instead of shift enter
okay, I'll do that then
Thank you
no clue what im looking at but show how you're creating the list in code
updated. i hit enter early
Is there a reason you're using Find over serializing it on the editor
they way you are using the input system you are more or less handling the input logic off to it
so it is seperated you are just handling it in your player code
Wouldn't i have to find the ones that get instantiated after the game starts?
oh wait, i guess i could make the list static and add the in the house.cs start or awake method.
if you're instantiating them at runtime, then yeah you couldn't just serialize them directly, so what you can do is store them somewhere in a container which you can assign on the editor.
and then use the container reference to search through for houses
When i make the list public like the other variables which i can see in the inspector the list doesn't show up even with [serializefield] unless im missing something
static references / singletons is another good idea too
should be visable to populate, but you really just need the reference to the object that contains the list as you're probably not inserting anything into it at editor time anyway by the sound of it.
as well as making the list accessable
Also, please don't use Count() when Length or Count exists, Count() may iterate over the entirety of the collection to calculate the length
90% of cases it wont do that, but it prolly will box things while trying to check if its IList so yeah still would do the check directly
I wouldn't trust shit in Unity's ancient version of .NET, but yes, it's just bad practise and I hate to see it
still would be a cast you dont need
can dictionaries show up in inspector?
they do not
unity does not know how to Serialize them
ah
are a few work arounds
what are you wanted key and value types?
could have a list of structs, then in Awake loop it and make a proper Dictinary from it
I was using a dictionary before i moved to a list for the simplicity. I got the list to show up and i figured i'd ask if they would too.
unity has an example here, maybe you could just use this directly after making a few methods like add/remove.
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
there are implementations online
Ty bawsi
i have a UI that is made up by 3 parts, upperhalf , video canvas and bottom part
all 3 UIs have vertical layout group and layout element enabled
im now trying to make a resize algorithm for 3 of them using the min height and preferred height
basically upper half height : video canvas height : bottom part height will be 1 : 0.6 : 0.1 , something like this
but , as you see, it seems that the height i obtained with getrectheight() is not correct
like upper group is 1012, but the actual height is 1596
i think i gonna work on it more first
aight i think im good lol
is there a line of code that checks whether the gameobject attached to the script is a game object or not?
sorry,
a prefab or not
if talking runtime code there is not
Instantiate does not really care if something is a prefab or justa regular GO in the scene it can make a instance of either
for editor code its a different story there are a lot of methods for working with prefabs
ok,
what about a clone?
is there a way to see whether an object is a clone?
with a script attached to the clone?
Why?
Generally when you instantiate you would just hold on to the returned instance
I'm trying to create an endless runner and I have code I want to run only if the game object with the script is a clone
So keep track of the clones as you make them
Or set some data on the script
Or set a tag
yeah
but only if it's a clone and not the actually thing because I use the not cloned version as the start.
When you instantiate it returns a reference to the new clone
You can use that to set data on it or modify it
can you send me the documentation?
hello my intellisense in vscode isnt working any help
why is the center of the game object is off with the spirte? how to fix it
sprite editor when you import the sprite
!ide 👇 and don't crosspost
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
alright mb
game devlopment doesnt appear for me
that's probably due to that being the instructions for Visual Studio not vs code
so its not needed for vs code?
why not follow the instructions for vs code and find out?
icl i thought they were both the same thing
i followed everything still doesnt work
did you install the unity extension
yep
did you look for relevant error messages in the vs code console?
the only error
thank ya much
there it is. regenerate project files in unity. if the issue persists then restart your pc
alright imma restart rq
did you try regenerating project files first?
can i have a game object with a custom fuction like being hited and place it as a tile in tile map?
yea thats still occuring
How the heck do I access these variables, AS THEY ARE, in code? offsetMin and offsetMax do NOT return these values, and I don't know what function of RectTransform does.
Documentation doesn't seem to help, the doc for RectTransform doesn't seem to list any specific ways to get at these numbers.
Dialogue.cs(29,24): error CS1503: Argument 1: cannot convert from 'method group' to 'string' getting this error, anyone know why?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Yeah... I know okay thanks
this is more like a code design problem
have the code inside a function
when you spawn out new object, the clone, call that function as well
so the function can be called on clones only
So, this struct:
[System.Serializable]
public struct NamedRectTransform
{
public Vector2 offsetMin;
public Vector2 offsetMax;
}
is being used in this method:
void Start()
{
startLocation.offsetMin = rectTransform.offsetMin;
startLocation.offsetMax = rectTransform.offsetMax;
upDelta = (Mathf.Abs(endLocation.offsetMax.x - startLocation.offsetMax.x)) / transitionSpeed;
rightDelta = (Mathf.Abs(endLocation.offsetMax.y - startLocation.offsetMax.y)) / transitionSpeed;
}
But when the Start method is ran, startLocation.offsetMax is getting set to a negative number, (I.E, 10 in the editor window becomes -10 in the script)
Why on earth is this happening? Shouldn't offsetMax return the values for Top and Right, as seen in the below picture? The actual number it's spitting out is -349 and -251
Ehhh little confused, Im trying to make a rigidbody jump script, but it only "sometimes" runs. any ideas?
void Jump(){
if(Input.GetKeyDown(KeyCode.Space)){
rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
}
}
This function is being called within the FixedUpdate() method
Guess it should be in update then 😛
Does the actualy force script need to be in fixedupdate? or is it fine since it is * time.deltatime
can i have a game object that can be set indivitually and place it as a tile in tile map?
like a button that can activate certain target
Huh interesting. I thought you always used it on physics stuf
making dialoge and getting this error, trying to make the dialoge start when the UI is set to active, anyone have a function I could use or know how to fix this one?
you cannot yield inside a OnEnable , it's not an Iterator type
Okay, any other way I can delay the function for like .5 seconds, its starting just a bit too fast, also thank you so much
turn start into IEnumerator, put OnEnable code there instead
private IEnumerator Start(){
...
}```
Dude! Thank you so much!
Okay, soooo got my movementy decent, but for some reason my character can like "grip" onto the sides of walls 🥲
Otherwise, making good progress!
put no friction material on character collider might help
You actually do NOT use it in physics stuff, because physics stuff (like AddForce and velocity) already have it built in
What editor works best for editing the Ink Json Files?
Ahhh I gotcha!
Won't this affect mobility when walking?
can someone reccomend me a book for learning coding in unity , i already have the basics of c#. need somehelp with vector and unity engine module
should be fine if you're using velocity , add some drag too
hi is it possible to get structs to display in the inspector?
make it [Serializable]
nah it goes above you class/struct definition
[Serializable]
public struct IKNode{
...
}```
No matter what I do, my object is moving left and right on the screen, and not moving along its local y axis. My code will follow this message, followed by an image
// Slider Out
if (Input.GetKey(KeyCode.P))
{
float sliderMoveValue = sliderArm.transform.localPosition.y;
sliderMoveValue--;
Vector3 sliderNewPosition = new Vector3(sliderArm.transform.localPosition.x, sliderMoveValue, sliderArm.transform.localPosition.z);
sliderArm.transform.localPosition = sliderNewPosition;
//sliderArm.transform.localPosition -= Vector3.up;
}
// Slider In
if (Input.GetKey(KeyCode.O))
{
float sliderMoveValue = sliderArm.transform.localPosition.y;
sliderMoveValue++;
Vector3 sliderNewPosition = new Vector3(sliderArm.transform.localPosition.x, sliderMoveValue, sliderArm.transform.localPosition.z);
sliderArm.transform.localPosition = sliderNewPosition;
//sliderArm.transform.localPosition += Vector3.up;
}
The commented out part was a different attempt
start throwing in some logging
I dont even know what to log at this point, like, i see it going the wrong way when it shouldnt be lol
those are vector3 , start drawing some gizmos
Gizmos.DrawSphere(sliderNewPosition, 0.22f)
etc.
should Sphere be an option because I dont have that
oh sorry is Gizmos..
no worries, had me think there was more broken here than just my brain
nothing is broken, you may be offseting position without taking account of rotation
well, as far I can tell by the image
im telling it to move positive and negative on the local y, which should follow that green arrow perfectly
but yeah, gizmos a good idea
maybe just do transform.up * amount
Is that relative to global or local
so
sliderArm.transform.localPosition += transform.up * 1;
same thing
No matter what I do I tell it move and it moves, the wrong way
when I try telling it to move on the local y it moves towards the front and back of the truck only, versus up at the angle its supposed to, and even that the transform gizmo shows it should
you in local pivot mode ?
Im in pivot, and local yes
You making a Pokemon game?
ya
Dope af
just link the sprites in the inspector
does pivot change if you remove it out of the truck hierarchy
nope, doesnt seem so
so i cant do a pathing thing for it
hmm btw ur also missing Time.deltaTime to make sure ur moving consistent
It's hilarious how many people ask us the best way to link GameObjects without using GetComponent
unless i make an image for each individual sprite
Why does it have such a bad rep?
good to know
You can but you have to know how to grab the sprites within that texture
You can if you use it correctly. Did you read the Resources docs?
the image is called status
The basic jest is that you make a folder called Resources and place the sprite there
Depends on the path you chose
But everything has to be under Resources
no idea why people don't just use fields for basic tasks lol
I have to step out for a bit but if anyone has any other ideas on why this object refuses to move along its local y axis, tag me
Well to be fair, linking the 7th script in the inspector gets annoying when you have many objects
Especially if you're going for a heavy component based system where one object could have 20 or so scripts
If you do it right, you'll be able to implement systems easily in the future by just attaching scripts instead of having to hardcore every action
You'll actually end up with less duplicate code this way since you won't have to rewrite your health system on every single thing
not everything has to be a monobehavior
True, but a lot does
ok so ive put the sprites into the resources folder
and ive called them
but theyre still a white box
Pokemon?
Having a DamageOnCollision script instead of hardcoding it to enemies and players means you can easily make another GameObject damage the player on collision, so maybe you want to make a wall damage you in the future
Better yet, a SO to hold the sprites.
what
yeah but thats too complex in code beginner prob
like field as in
Public Variables
I think spliced sprites are accessed via the parent sprite name. It kinda acts as a directory. Might be wrong though.
how do i edit layers property to include or remove specific layer inside a script?
Hello, how to add libraries of sensors into unity? They arent in git. They are only downloadable from their web
just pass the layer?
[SerializeField]
LayerMask layers;
private void Method()
{
circleCol.excludeLayers = layers;
}```
can you override the fields of certain component and make them unchangable?
uh idk what you mean, maybe this?
https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
ah yes i know that. but i wonder i can just include layer or remove one from a property of a component.... i guess like this?
Doesn't work? Also try not appending the value, let the variable be the distance from the origin. Not exactly sure what way you're trying to extend, but try other directions.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no, doesnt work. its weird. It moves it along the global Z not the local y
now idk if its ACTUALLy moving it along the global z or not, but thats the axis its moving in the directions of, whether by coincidence or actually following it idk
I am trying to create a basketball game, and I am having an issue with the setting menu. It contains the option to change the sprinting keybind, however, the keybind text (seperated from the keybind selector) becomes empty as soon as the game starts. https://www.toptal.com/developers/hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
your paste is empty. Ah, you posted the wrong link
Hey Steve, maybe you have an answer to this weird one I got
Here it is
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sprintInputButton.text = PlayerPrefs.GetString("SprintKey");
you need to supply a default value to be used when the string does not exist
Sorry I should've clarified, the sprintInputText is what I'm talking about here
then why this?
if (sprintInputButton.text == "Awaiting Input")
So there's a button next to the sprintInputText
(sprintInputText is "Sprint:" btw)
And when that button is clicked
It is set to "Awaiting input"
Once you have clicked a key
It is set to that key
It's not currently working right now either, but that's a different issue
https://www.youtube.com/watch?v=3BOn2gs7z04 when I apply this on my character controller and when i touch rigidbody objects, I get launched upward with rigidbody, why 
In this Unity tutorial we're going to look at how we can push obstacles around using a Character Controller and Unity’s physics system.
We'll start by adding a box for the character to collide with. We'll add a Rigidbody component to it so that it reacts to physics,
Next, we'll create a script to apply a force to the box every time the charact...
I'm confused.
In start you do
sprintInputButton.text = PlayerPrefs.GetString("SprintKey");
in Update you do
sprintInputButton.text = keycode.ToString();
PlayerPrefs.SetString("CustomKey", keycode.ToString());
So how does the Pref SprintKey ever get set?
In this video I will be showing you how to create a simple custom keybind system for your unity game! If you have any questions, or need help comment down below and I'll get to you when I can.
Need a login system for your game/application?
Check out KeyAuth! https://keyauth.cc
Need help with code or just want to share your code?
Check out ...
I'm not going to watch a video on your behalf
No lol, that's the video I used, and if you skip to the end you can see the code I used
Besides, this isn't the issue I'm asking about
I've fixed the issue, thanks for your help anyways!
One point. TextMeshProUGUI is probably not what you should be using. TMP_Text is likely a better choice
Ah, yes I see now. Thank you!
when I use character controller, and followed the code, it pushes the rigidbody upwards at extreme speed :x why
https://www.youtube.com/watch?v=3BOn2gs7z04
In this Unity tutorial we're going to look at how we can push obstacles around using a Character Controller and Unity’s physics system.
We'll start by adding a box for the character to collide with. We'll add a Rigidbody component to it so that it reacts to physics,
Next, we'll create a script to apply a force to the box every time the charact...
sorry for repost, if ok 
I used her final script, it was different
it is ok now
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
looking at this again, it seems fine honestly. The only other thing I can think of is that the pivot is at the bottom perhaps but I think you mentioned it's not.
What the heck is this error ?
Does this error continue to appear?
If no, ignore it
Probably this https://issuetracker.unity3d.com/issues/error-messages-are-shown-when-using-a-list-of-serializereference-objects
So internal and can be ignored or fixed if you upgrade
Reproduction steps: 1. Open the attached project "SerializeReferenceBug" 2. Open "Scene" in the Assets folder 3. Enter Play Mode Exp...
a way to retrieve all objects without having to add "public float" in the script because it would be very complicated if you had to add them all one by one
Well when ever I run the game it happens
It's a Unity bug so you'll have to upgrade to have it fixed, apparently
Thank you
Is there a question here?
I apologize in advance, so what I mean is is there a way to retrieve all the objects in this game without adding "public float" to the script?
Mornin' all,
So, I have this ship controller (it's very basic atm, just trying to get the basics working), but I think I have order of operation or something wrong.
Idea being that when you hold a movement button, the rcs thrusters fire for that given direction of travel.
The issue I'm having is that for some reason the forward/backward thrusters don't fire unless I also hold down either the left/right key. It's very odd.
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.
If you're trying to store the number of objects that exist, then there are many ways.
You could just drag all the objects to some array/list and use the length of the collection.
Or have some script on each object notify another 1 script that it exists and then add to a counter.
do you know how to make a list in the script?
any idea why stuff with shader graph broke?
oof make a new shader graph and everything changed
Guys I have a quick question, I’m trying to make an open world game with different characters and every character has its own abilities. Basic movement is on the ground and there are abilities like “dash” or “sprint” etc, but also abilities like “fly” or “levitation”. I used a CharacterController to move until now but should I switch to a RigidBody addforce / velocity to better control the movement ?
Yes it's just a List<whateverType>. Google has many resources on it, though this will rely on you dragging all these in during editor time.
noob question:
[SerializeField]
[Range(1, 10)] [Min(1)] protected int targetCount = 5;
public int TargetCount { get => targetCount; protected set => targetCount = value; }
//pseudocode:
TargetCount = 3;
based on this pseudocode on top: what is targetCount now? 3 or 5?
I am not understanding the get set thing yet
In the pseudo code you're overriding everything that came before it, so 3.
None of this shows your actual movement logic, you should debug and find out why these values either arent what they should be, or why they arent being used properly in the movement logic.
you are doing
KillAllRCSThrusters();
unless keys from both sections are held
The movement code is lower down and works fine.
so it will change the initial value of that targetCount?
Okay... but is the TargetCount (if we would not set TargetCount to 3) will be passed to other class, other class won't be able to override that targetCount, right? or still?
Ah okay, I'll have another look at it, thanks. (been looking at it for a while so missed that obviously. lol.)
I cant seem to see it on mobile but seems someone else solved that
Oh the movement code isn't in what I posted (it's in FixedUpdate()) Wasn't relevant to the issue.
BTW just my Unity Editor or Unity Hub ?
Editor
how bro, im newbie sorry
The initial value is still gonna be 5 but when you change it through the property to 3, it will be 3. Since it's an int, if you pass it to another class, the other class wont be able to change it unless you use the ref keyword. Child classes can change it directly since it is protected
If you dont know how to use a list I suggest you do some c# basics first, or really just find an example on google. There isnt much more I can do other than write the code for you
oke bro thank u
daaang... I guess I have to watch some documentation about get sets and maybe some tutorials 😄 But thank you
I'm getting back into Unity and working on a simple player controller script: https://paste.mod.gg/hmctgecldcgq/0
I'm having a problem with the player "phasing" through objects and I believe I kno why.
Under my PlayerMove() method I'm translating the transform based on the movement direction and speed. If look straight forward I can go through objects pretty easy but if I look down it's just jittering. So I believe there is something going on there causing me to have this issue.
i will paypal anyone 10 pounds if they help me with my problem (My problem is that when i pull out my gun the gun doesnt want to shoot ive been following a tutorial from a guy called HawkesByte and when i am this part where i cant shoot when i take out my gun its quite useless please help lmao)
There isnt much to it, the get is public so anyone can read it. The set is protected meaning only the existing class and child classes can set it. It would be the same if you had a method
publuc int GetValue() and protected int SetValue()
okaay, now it's much more clear. Thank you
Just a very quick look, but your player move should ideally be in FixedUpdate()
Right yeah, JUST noticed that haha, but I don't think that'd be the reason for the issue
is there a way to make that initial variable not being able to be modified even by existing and child classes?
you shouldnt be using transform.translate either if you're using rb, no?
Dont mix Rigidbody and transform movement
You can explicitly teleport with transform though.
I can't remember, but would MovePosition be the one to use then?
yes, that will respect physics. rigidbody also has a position property
Hello this aint a code question but i cant find the "On click" section
the left side is a YT tutorial but i aint got it on my inspector
scroll down?
But I see an issue that because I'm setting these in PlayerMove
cameraZ.y = 0;
cameraX.y = 0;
Wouldn't I just be going to Y 0 all the time?
scroll down or hide the "Fart" panel
Ah crap, my bad, was looking at the image wrong.
I presume that the rigidbody is on the player not on the camera
Yeah, but I'm moving based on the camera direction
Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;
should be ok to replace transform.Translate with rb.MovePosition
yes, of course
cameraZ.y = 0;
cameraX.y = 0;
Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;
movementDirection.y will always be zero
but it was 0 before when you used Translate, nothing has changed there
It was working before since I wasn't using the Y in translate?
I see what you mean. So you need to put the current rb.position.y back into movementDirection
Sorry I'm really not the most experienced and I've forgotten most I knew, how would I do that 😅
seriously?
Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;
movementDirection.y = rb.position.y;
Ah, sorry misunderstood, thought you meant to the equation
But still seems to be doing it 😅
Ah, yes, you probably want transform.forward.y rather than rp.position.y as you are calculating a direction.
or
Vector3 movementDirection = cameraZ * verticalInput + cameraX * horizontalInput;
Vector3 pos = new Vector3(moveSpeed * Time.deltaTime * movementDirection);
pos.y = rb.position.y
rb.MovePosition(pos);
Ooookay, I think I'm monumentally stupid, but I can't see why this isn't working.
I've split my controller script up to make things a little easier to read and a little more 'direct' (I know it's not overly 'elegant' lol.).
Annoying thing is that I had this working a couple of minutes ago, but it suddenly stopped behaving.
The forward/back rcs thrusters no longer fire at all.
Any ideas anyone? 😕
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.
I know that the values are working correctly because the ship moves (the 1, -1, 0 values get passed to my movement section just fine.
Again, the thrusters will only work if both key sections are pressed
Yeah, was literally just about to type that I think that was the issue. Think I should take a break to clear my head a little. lol.
I think all you need is
if (flyMoveSpeed == 0 && turnMoveSpeed == 0)
{
foreach (VisualEffect rcsThruster in moveForward_Thrusters)
{
rcsThruster.SetFloat("EmissionRate", rcsThrusterMinEmission);
}
foreach (VisualEffect rcsThruster in moveBackward_Thrusters)
{
rcsThruster.SetFloat("EmissionRate", rcsThrusterMinEmission);
}
}
instead of testing each for zero seperately
Yeah I was just trying to 'split it up' to make it easier to read. But I'll give that a go, thank you 🙂
in interactor script when i try to access interactable script public Interactable interactable;when doing this itemDictionary[interactable.itemType] I get null exception, why?
i know it has a value, by why cant it find the value
difficult 
either itemDictionary or interactable is null. So debug them to see which one
Debug,Log(itemDictionary[interactable.itemType])?
no, that tells you nothing
how do i debug them?
if ok 
that is how I check if they have value, but they cant find the value
if (itemDictionary == null) Debug.Log "itemDictionary is null";
and the same for interactable
You can't make a new vector with only 1 argument
mb, should be, of course without the new Vector3
Vector3 pos = moveSpeed * Time.deltaTime * movementDirection;
But if you do this, the player only moves a tiny bit and goes back to 0 when let go
probably because you set the position elsewhere
The MovePosition parameter is a position, not a direction
so it should be Vector3 pos = transform.position + moveSpeed * Time.deltaTime * movementDirection;
interactable is null it said

I have public Interactable interactable; and has the interactable = hit.collider.GetComponent<Interactable>(); but only on the bottom/after this thingy itemDictionary[interactable.itemType], and not before, is that what is causing it?
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, itemDictionary[interactable.itemType], interactableLayermask)) //when raycast finds something
{
var selection = hit.transform;
selectionRenderer = selection.GetComponent<Renderer>(); // Assign selectionRenderer here
if (selectionRenderer != null)
{
selectionRenderer.material.SetInt("_enableFresnel", 1); //enable fresnel when in sight
///Debug.Log("logging");
}
_selection = selection;
if (hit.collider.GetComponent<Interactable>() != null)// if it find that interactable is in, used to be false instead of null
{
if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
{
interactable = hit.collider.GetComponent<Interactable>();
currentInteractTimerElapsed = 0f;
Debug.Log("New Interactable");``` it is kind of like this, but ``itemDictionary[interactable.itemType]`` is null
not sure why 
Well obviously there's not going to be anything in the variable before you put something in it
Why are you using it in the raycast anyway?
so that it can find an interactable item and it could be interacted, not sure if right, itemDictionary[interactable.itemType] is for itemtype, different items have different ranges to be interacted
like if it is broom (itemtype 1), it will have a range of 2, and if it is car (itemtype 2), the range is 6
You can't select the distance of the raycast based on the thing that the raycast might hit, that makes no sense
{
/*rotationDictionary.Add(1, (new Vector3(-30, 0, 0), new Vector3(30, 0, 0))); // Example values for item type 1
rotationDictionary.Add(2, (new Vector3(20, 0, 0), new Vector3(0, 0, 0))); // Example values for item type 2
rotationDictionary.Add(3, (new Vector3(0, -10, 0), new Vector3(0, 0, 0))); // Example values for item type 3*/
itemDictionary.Add(0, 12f);
itemDictionary.Add(1, 2f);
itemDictionary.Add(2, 6f);
}``` i made a dictionary for them
You have to make the raycast without the max distance, then after it has hit something check the distance
ah okok, I thought it would work simultaneously 
but i have to check the item type of interactable for the range, how would that work?
and how would no range work? leave it blank or no
if(hit.distance <= itemDictionary[interactable.itemType])
itemDictionary is a bad name for it btw and using a dictionary for this purpose is questionable
I want to add other elements for the item also, but not sure which to use
I only know dictionary and enum atm 
it is like, I want to make itemtype, but it will have their own characteristic, and it would only be called by their number
or maybe rename it to rangeDictionary?
Variables don't usually have their type in their names. I'd call it maxInteractionRange
i still get NullReferenceException: Object reference not set to an instance of an object
interactable is still null, but interactable not being null is dependent on the raycast
...show the code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I want to learn how to stop null exceptions
also,if there are other tips, if ok
I always have a difficult time when trying to use codes that arent declared yet, but needs to be put in an area before the declared code, maybe why it is null
I'm about to work on an inventory system for a shooter type game, so the npcs and player would have stuff liek grenades, guns, ammo and whatnot. For this inventory, what might the best approach be? I'd want said inventory to just be of one type, so would making a 'slot' class that just holds the name of the item and maybe some ID from an item database be a good approach? In that case, how could you track individual details like the ammo in a weapon etc? I'm not too sure what the general class structure for a system like that might look like
The check is too early
question can we make a shopping app on unity ?
Yes
but it wont work as intended if the check is later, or is it ok?, can i move interactable = hit.collider.GetComponent<Interactable>(); up?
But why would you use an entire game engine to make a shopping app is another thing
Hey does anyone know why this is grabbing both instead of just 1? https://gyazo.com/e14c4546372b20fc7d20be4d586a4bf5
if (hit.distance <= itemDictionary[interactable.itemType])
{
interactable.isHighlighted = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log("Toggled");
targetObject.SetActive(true);
}
if (Input.GetKey(KeyCode.E))
{
//Debug.Log("it works");
// Perform radial interaction here
PerformRadialInteraction();
if (Input.GetKeyDown(KeyCode.Mouse0))
{
currentInteractTimerElapsed = 0f;
}
UpdateInteractProgressImage();
}
else
{
currentInteractTimerElapsed = 0f;
}
}
this is the only place where you need to check it, if I read the intention correctly
Looks like its detecting the parent instead of the childs
How are you handling the mouse click?
the reason why i want it earlier is because of if (selectionRenderer != null) { selectionRenderer.material.SetInt("_enableFresnel", 1); //enable fresnel when in sight ///Debug.Log("logging"); } else, fresnel wouldnt follow the range, or would it cycle and be reachable by fresnel?
item type have different ranges for both fresnel and interaction
Do you want the fresnel shown on any object, interactable or not?
only on interactable
Then you need to move that code lower, where it checks if the object is interactable or not
okok
so it goes like main update code-> itemDictionary (or max range)-> fresnel code?
(cache your get components pls)
I dont know how yet, but I want to check 
I mainly see this code, at line 108
if (hit.collider.GetComponent<Interactable>() != null)// if it find that interactable is in, used to be false instead of null
{
if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
{
interactable = hit.collider.GetComponent<Interactable>();
currentInteractTimerElapsed = 0f;
Debug.Log("New Interactable"); //something
// Access the itemType property of the Interactable component
// Add your logic based on the itemType here
}
.
:
}
You'll have to learn to read what the code does. It runs one line at a time, from top to bottom. If you just read out loud what the code does you can see if it's sensible or not ("Enable fresnel. If the item is interactable, check keypresses..." oops)
hmm... mouseclick I will set later but for now its this "public void OnDoubleClick()
{
chestManager.Remove(itemWeapons);
Destroy(gameObject);
}"
that could be done to this
interactable = hit.collider.GetComponent<Interactable>();
if(interactable != null){
currentInteractTimerElapsed = 0f;
Debug.Log("New Interactable"); //something
//Do the other things from line 120 down
}
ah, it should be if item is interactable -> (put range here for fresnel) -> enable fresnel and check key presses, I think it would work like this better, hmm what do you think? 
i meant, how are you handling he drag, sorry
I think the drag is automatically part of Scrollview gameobject
is it?
Mmm, i don't think so, but i might be wrong, it was a long time since I worked with UI but normally I had to implement it myself the click, raycast, find object, move and snap to mouse position
because ive noticed when I have the button click logic in, it doesnt click the one I want,
Nope I did none of this, it goes for me Canvas>Scrollview>Viewport>Content
and I think its in there somwhere the drag component
weird...Icant find anything
it was just automatically applied when I created the button
So its a behavior the is part of scroll view.
so wtf is wrong with my thing lol
ohhh these item prefabs are all child of the scroll veiw, could this be the reason?
and if so, how to fix?
what is secondary texture?
In what context?
im following this tutorial by Brackeys. but idk whats the use of secondary texture
https://www.youtube.com/watch?v=WiDVoj5VQ4c
In this video we create an awesome Glow effect for extra flare!
► Check out Popcore! https://popcore.com/career
● Download the project: https://github.com/Brackeys/2D-Glow
● Get Gothicvania Church Pack: https://assetstore.unity.com/packages/2d/characters/gothicvania-church-pack-147117?aid=1101lPGj
● Learn more about 2D Shader Graph: https:/...
at 9:30
Be more specific please, I don't have time for a 15 minutes video right now
nvm i think i got it
I don't know the answer for this specific case, but more generally:
you can use textures to store much more than plain color data