#💻┃code-beginner
1 messages · Page 369 of 1
but ive alwyas had spaces in my file names before
and never got this error
why do i get it now
File name
public class ClassName
Doubt it
Maybe those other files didn't have MonoBehaviours
im so confused i removed the space now it works i readded the space and it still works
Till you rebuild ur project
When I extend Button, my serialised fields do not show up in the inspector
how do i get all children of a gameobject then iterate through them?
foreach (Transform child in transform)
But I would rather cache the objects you want
ill try that
wait how can i apply all the children of a certain gameobject to an array?
do i use .Add
An array is of a fixed size
.Add would be for a list
Turns out one has to enter debug mode to see the new fields lmao
oh i see, whats the alternative for an array?
I would honestly watch some beginner C# videos first
That's like basic computer science
But you could use a list
strange
i do know c# but i just need a refresher lol tbh i havent coded in 2 years
How do I get the camera to move forward the direction it's facing? This code takes mouseinput and calculates "dragging" on the screen, but it doesn't change the direction when I rotate the camera
{
// Determine how much to move the camera
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
transform.Translate(new Vector3(offset.x * PanSpeed, 0f, offset.y * PanSpeed), Space.World);
// Cache the position
lastPanPosition = newPanPosition;
}```
Because you're using Space.World
But also your offsets are in viewport space??
yes, these spaces are incompatible
if you want to move the camera in world space, then you'd better compute positions in world space
It'll happen to work if the camera is pointing in the +Z direction
but only until the camera rotates
That screentoviewportpoint call is really sketchy. It's supposed to take a position but you're giving it an offset
indeed -- it's ScreenToViewportPoint, not ScreenToViewportDirection.
so it's also wrong if the camera has moved at all
although, actually, it's going from screen to viewport space
it'd blow up entirely if this was world to viewport space
this looks like AI code, so of course it is crap
If I set it to Space.Self, it will move on the Y axis and I don't want that to happen
that'd still be the wrong coordinate space
It's taking the current mouse position and then subtracting where the mouse has now moved to
do you actually have any understanding of what the code is doing?
You'll have to do some math then . Project the direction you want to go along the XZ plane and use the projection
Space.Self would still only be correct for a camera pointing in the +Z direction, and your camera would also move faster in one axis than the other if your screen wasn't perfectly square
I still see no reason whatsoever for ScreenToViewportPoint
or...no, that is fine, I suppose. it'd just have the latter problem
since moving right in the camera's own space moves you right in view space
yes, you should be computing the difference in the world-space positions of the old drag point and the new drag point
(this will only makes sense for an orthographic camera)
Sorry, but the code is complete and utter nonsense
I have a 3D game where the camera has "free movement within a box" (I've set limits) - I recently updated the camera script to used the keyboard to move forward, that code now works when I rotate the camera, but I'm having trouble adjusting the code for moving the camera via mouse click. Everything I've googled says that what I have should work, but it doesn't fit what I need.
Space.World = ignores rotation & Space.Self moves the camera on the Y axis too.
If one of you could go - "learn this" or "do this" that would be absolutely fantastic.
@wintry quarry Thank you. I'll look into that now.
Please write what is correct for me
not a chance, that's not how this server works
lol, so be quiet then? Fen and PraetorBlue are actually being constructive with suggestions, all you ever comment is "crap code" or the like and that is so god damn frustrating when I'm looking for help
Thank you
If you actually put some effort into your code instead of AI generating it and coming here to fix it I might be inclined to help you
you should stop and reason about why this works (and why the old code didn't work), though
If you read what I said, this is from google and other scripts that have mouse movement controls. Maybe this chat is too basic for your god-tier coding so you shouldn't monitor it to just feed your ego using us dumb-newbs.
And I asked you how much of it you understood, to which you did not deign to reply
It's concepts, I'm new to everything. I had code that worked and all I've changed is rotation, so my simplistic brain is struggling to find where I go to translate what I learned before, to what I need to know now. Forums and videos are too specific so it hasn't help me, then I come here for some humans to discuss and I'm met with arrogant people like SteveKingSmith.
I tried to reason long before I tried to ask for help
Because we've interacted before and I think your arrogance is aggressive so you trigger TF out of me
bashing code together from things you found on Google isn't going to be much better than asking a GPU to make it up
you want to write each line of code with purpose
I understand that.
you can use Debug.DrawRay to visualize a vector, which is useful for finding problems like this
Debug.DrawRay(Camera.main.transform.position, moveVector);
if moveVector is very short you might want to normalize it
and to see the line for more than one frame, you can do...
Debug.DrawRay(Camera.main.transform.position, moveVector.normalized, Color.red, 0.5f);
Sorry if I hurt your feelings, it's not my intention. To be fair I don't much care for people but I do care about code. All I ask for is for people to meet me half way and then I am more than happy to help them
hello, i bring love and sprinkles lol
just learning about casting between int and doubles and floats
int = (int)value
double = (double)value
float = (float)value
im starting to remember my uni education on programming
best forget it again, it won't help you much
Am I missing something? I get Object reference not set in the if statement for the distance calculation ```cs
void FixedUpdate()
{
//Scanning for each object in the _interactableMask that overlaps the Sphere
_numFound = Physics.OverlapSphereNonAlloc(_interactionPoint.position, _interactionPointRadius, _colliders, _interactableMask);
//if an Interactable object is found
if (_numFound > 0) {
//Find the closest collider
Collider closestCollider = null;
foreach (Collider collider in _colliders)
{
Debug.Log("collider in _colliders is: " + collider);
if (closestCollider == null)
{
closestCollider = collider;
Debug.Log("closestCollider is: " + closestCollider);
}
else
{
if ((_interactionPoint.transform.position - collider.transform.position).sqrMagnitude < (_interactionPoint.transform.position - closestCollider.transform.position).sqrMagnitude) //THIS LINE ERRORS
{
closestCollider = collider;
Debug.Log("closestCollider is now set to: " + closestCollider);
}
}
}
//Store the closest colliders Interactable interface
var _interactable = closestCollider.GetComponent<IInteractable>();
Debug.Log(closestCollider);
//Interact on input
if (_interactable != null && playerInput.Player.Interact.ReadValue<float>() != 0)
{
_interactable.Interact(this);
}
}
}
Did you get a null reference exception?
yep
it must be something dumb i'm just not getting it for some reason
Thank you for sharing that, we sound alike in that sense, this is me trying to unmask without exploding too, so I hope I haven't hurt your feelings either 🖖 .
Post the error from the console
@karmic kindle Look at this line of code
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
So what it does is calculate a Viewport point based on the difference between, I assume, 2 screen points.
in what way do you think this is a useful thing to do?
NullReferenceException: Object reference not set to an instance of an object Interactor.Update () (at Assets/Scripts/Player/Interactor.cs:46)
What line is 46 of the Interactor script?
the one which i commented with "//THIS LINE ERRORS"
the distance check if statement
Did you debug everything? so everything is there from collider to _interactionPoint and closest collider?
Thank you thank you. Doing all this stuff has finally helped me actually visualise which direction is which within Unity lol but my brain is still wired to find shortcuts like "just stop Y movment in Space.Self" [simples] .... obviously not, but that's a me problem! 🙈 😅
I'm not sure what you mean
"shortcuts" basically always cause problems
you never want something to work by coincidence
Debug.Log all those referecnes and see whats null
So you mean that it's picking up null colliders?
Here's the rest of the call - sorry, this is where I am unsure to post everything I have or just where the issue is if (Input.GetMouseButtonDown(0)) { lastPanPosition = Input.mousePosition; } else if (Input.GetMouseButton(0)) { PanCamera(Input.mousePosition); }
So it's tracking the position where the mouse was pressed and then where it's still pressed - elsewhere on the screen, in a dragging motion
if in doubt, post everything and let us filter it, it makes our lives, and thus our ability to help you, much easier
Yeah it was picking up null colliders from the OverlapSphere. I just wonder why? In the LayerMask i used there are only two objects that both have a collider. Is this normal behaviour?
i haven't seen your code so i couldn't say what the issue is 🤷♂️
i pasted it above
oh you know what, you're just looping over the entire array regardless of how many objects were found by OverlapSphere
Non alloc so the collection doesn't modify it's count
did you not read the documentation about how that method works?
You may want to iterate relative to the return value of num found rather than just evaluate every element
the better option is using a for loop to loop over the correct number of objects rather than just null checking everything. because old colliders could still be in the array and those shouldn't be checked either
I did. I didn't fully get it, I'm guessing it allocates a set size and then doesn't modify it?
the method doesn't allocate anything. you allocated the array with a set size. the OverlapSphere method just populates the array with what it finds
and also returns the number of colliders found
You can't modify the size without reallocating an array
what do you mean by "correct number of objects"? I'm just trying to really understand what's under the hood so that i don't rely on an easy mindless fix
num found variable
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
int Returns the amount of colliders stored into the results buffer
Ok, so lets look at this
say mouse position is 5,5, then becomes 5,0
so
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
will produce a Viewport point for 0,5
which is top left of the screen, nowhere near where, I think, you want it to be
Okay, so i should check only the values of _numFound. Not sure how to do that tho since it only returns an int (?)
Ah, my bad. Did not see the person was using nonalloc.
do you know how to write a for loop?
The example of that page already shows you how to access the returned array.
I do, just thought that the positions of the colliders in the array wouldn't match
read the documentation
Thank you. In my mind, I'm not interested in where the mouse position is or is going (relative to the screen), I am only looking to simulate a smooth drag so that the camera moves accordingly for the player. The code itself works fine when I don't rotate the camera, I can control the speed etc.. but the issue is when I rotate the camera, I can't work out how to make "up/forward" change with it.
I don't really know if it's applicable to your problem, i haven't read your code, but to do something """"similar"""" in my game i just multiply the input values by the camera's rotation
I think, as Fen already said, you need to use ScreenToWorld space then you can calculate a rotation based on that, no need for the offset stuff at all
because you're using the wrong coordinate space
No matter how the camera is rotated, view space is going to range from [0,0] in the bottom left corner of the screen to [1,1] in the top right corner
by using ScreenToWorldPoint, you'll get world space positions
which will depend on the camera's rotation
however, note that this will not work correctly if you're using a perspective camera
you'll need to add a depth (the Z component of a screen space position) first
the depth you pick will affect how quickly the camera moves
if you pick a depth of 1 meter, moving the mouse will move the camera by the exact amount needed to keep an object 1 meter away under the cursor
So if the game world is exactly 10 meters away from the camera, a depth of 10 would be appropriate -- that'll make it feel like you're grabbing the game world and moving it around
I am using perspective view and here's the full code just for sake of at this point 😅 - https://pastebin.com/hw3PcSQT
consider using Debug.DrawRay to see how ScreenToWorldPoint behaves (both with and without changing the Z component of the screen space position)
Just a quick tip, move to the new input system one day 🙂
I understand what ScreenToWorldPoint is doing, what I am struggling to understand is why does it apply in this situation?
As far as I understand, the mouse is a way for a player to interact with the screen. All I want to do is get a distance from them, then apply it to my camera view. So if they drag the mouse** "down" the screen, it will drag the camera "forward" - I don't see a need for any correlation between "ScreenTo#" ?
So you just want to move your camera on world z axis the amount of your screenposition distance normalized?
I don't understand what kind of camera movement you want.
I thought you just wanted to be able to drag it around...normally
so if you move the mouse down your screen, the camera moves up your screen
keeping the mouse in the same position in the world
you're talking about "forward" now
I want my mouse to replicate what [WSAD] are doing but by mouse drag
okay, and are WASD panning the camera up, left, down, and right, relative to your point of view?
{
transform.Translate(new Vector3(cam.transform.forward.x, 0f, cam.transform.forward.z) * panSpeed * Time.deltaTime, Space.World);
}``` Yup
This works if and only if the camera is pointing in the +Y or -Y directions
otherwise it doesn't move the camera like this
oh, wait, that's got cam.transform.forward.x
i see
that is a bit weird
I would have expected you to do this
Vector3 moveDir = xInput * cam.transform.right + yInput * cam.transform.up;
I don't see how your move input is even involved here
oh, you're doing this for every single key, separately
I've set the basic keys up
I don't think this is what you're doing.
You want the camera to move in the X and Z directions
But the camera is not pointing straight down
It's angled
Is that correct?
Yeah
not tilting it and not rolling it
E.G if (Input.GetKey("e") )// || Input.mousePosition.x <= panBorderThickness) { transform.Rotate(Vector3.up * panSpeed * Time.deltaTime, Space.World); }
okay, let's fix this up first; your camera is moving slower forwards and backwards than left and right
Vector3 forward = Vector3.ProjectOnPlane(cam.transform.forward, Vector3.up).normalized;
Vector3 right = Vector3.ProjectOnPlane(cam.transform.right, Vector3.up).normalized;
This will get rid of the Y component of these vectors.
it then normalizes them so that they have a length of 1 again
Vector3 moveVec = Input.GetAxis("Horizontal") * right + Input.GetAxis("Vertical") * forward;
moveVec = Vector3.ClampMagnitude(moveVec, 1);
transform.Translate(moveVec * panSpeed * Time.deltaTime, Space.World);
construct a movement vector, clamp its length to 1 (so that diagonal movement isn't faster), and then move with it
As for dragging, since you aren't just moving the camera around relative to your view (you move forwards, not up, when dragging the mouse vertically), you'll want to do something very similar to this
Vector3 viewDelta = newViewPosition - oldViewPosition;
Vector3 moveVec = viewDelta.x * right + viewDelta.y * forward;
// the rest is the same, except that you don't use deltaTime
You're indeed correct that world space positions aren't useful here, because you are not directly using the change in mouse position as a change in world position
Thank you everyone, there's a lot of information to digest so hopefully I can absorb it all hehe, but I do really appreciate the extra lessons and advice! 🖖
I'd love a beer but I'm going to take a break, maybe I'll come back to shout it's working and bug you that way 😛
getting to know the Vector3 methods (along with Quaternion) is very important
any time I see someone pulling out individual components of a world-space vector, there's probably an issue
i changed my canvas from an overlay space to a screen space thing, and now my raycast for selecting characters is messed up. how can i sort this out??
if (_playerInputController != null && !_playerInputController.characterSelected)
{
_transform.anchoredPosition += _playerInputController.markerMove * (speed * Time.deltaTime);
_transform.anchoredPosition = new Vector2(
Mathf.Clamp(_transform.anchoredPosition.x, -896, 896),
Mathf.Clamp(_transform.anchoredPosition.y, -485, 485)
);
}
PointerEventData eventData = new PointerEventData(EventSystem.current)
{
position = _transform.anchoredPosition
};
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
bool foundCharacter = false;
foreach (RaycastResult result in results)
{
if (result.gameObject.CompareTag("CharacterSelect"))
{
if (result.gameObject.TryGetComponent(out cb))
{
_playerInputController.selectedCharacter = cb._characterInfo;
if (!characterHovered)
{
source.PlayOneShot(hover);
characterHovered = true;
}
foundCharacter = true;
break;
}
}
}
is LoadSceneAsync is the same as LoadScene? What's the difference?
it loads asynchronously
idk what that means
This is actually a pretty good description
https://en.m.wikipedia.org/wiki/Asynchrony_(computer_programming)
Usually wiki is too wordy, but this one is good imo
thanks!
if (_playerInputController.characterSelected)
{
_playerInputController.characterSelected = false;
_playerInputController.selectedCharacter = null;
_playerInputController.colorNum = 0;
print("Removed character!");
return;
}
if (!_playerInputController.ready && !_playerInputController.characterSelected)
{
_playerInputController.pi.user.UnpairDevicesAndRemoveUser();
Destroy(_playerInputController.gameObject);
markerGraphic.SetActive(false);
if (TryCancel != null) TryCancel(id, _playerInputController);
print("Deleted player!");
source.PlayOneShot(hover);
}
why does it execute both even though there is a return statement?
those are probably happening in separate frames or this code is being called more than once in the same frame
you're right, it appears to be doing it twice
Sorry for the trouble, I have a problem with this script, it doesn't give me errors but when I start the game some fireballs rumble very quickly on the ground and if the character touches them they move but they don't disappear anyway
no idea why, though. this check is meant to happen when the player clicks a button. even stranger is this exact system works as intended in another mode.
use the debugger and set some break points to determine why that code is being executed more than once
It's pretty uncomfortable to read the code from your screenshots. Could you, please, share them using a site provided below? !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.
!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.
one mildly interesting thing to add: LoadScene still waits until the end of the frame to load the scene
the method returns immediately
If I add 2 audio listeners or event systems i get a warning that i should not do that...
Could I make only one of each and keep them in a "Dont destroy on load"? 🤔
Is there any adverse effect with doing that?
Just dont use two audio listeners or event systems.
If you add a camera, remove the listener. And for sure always have one eventsystem, because all the API is going into that eventsystem and two will confuse your code on which to use
For event systems, it's very reasonable to just DDOL them
Audio listeners are generally attached to a camera
so it's less reasonable to do that (you presumably have different cameras in your main menu and your actual game)
Assuming you're making proper use of the Singleton pattern and having the duplicate objects destroy themselves, you might get like, a frame of this every time a scene loads and that's probably fine. As long as they don't exist long enough to mess with things like EventSystem.current it shouldn't be a problem
I have my EventSystem on a "main menu" prefab that gets instantiated the moment the game starts
You might want to change the Script Execution Order so that your singleton script guarantees to run before those two though, so they don't update their own singletons:
https://docs.unity3d.com/Manual/class-MonoManager.html
nothing else has an event system
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html is very useful for this purpose!
(i fetch the main menu from Resources)
Unity could’ve done something different than making user to ensure single instance
But well
if you are interested in this pattern..
(Safe is there so that I can avoid creating more copies of the prefab as the game quits)
how do i limit the length of a raycast?
Raycast has maxdistance parameter
did you look at the docs?
i cant find it
yeah and theyre extremely confusing
nevermind i found the parameter
lol
you should really learn to read documentation
If i have a heart container with collider 2D (Set to trigger), animator and the script, and when i enter the trigger i want him to dissapear and make a sound, is there any way to play the sound on the heart container with his audio source but without having to deactivate each component 1 by 1?
don't make the audio source a child of the object being deactivated
Hello Is there a paint system in unity like a drawing app and save drawing as .png format
Use AudioSource.PlayClipAtPoint
Not built in
you mean dont? or make it
They wrote "don't"
the first word is literally "don't"
Custom scripts for example
Is this a question?
Yes you would write the code
so what should i do with the audio to work? like i dont have childs its just a gameobject
with each component on it
No!!! I'll find a tutorial
either keep your audio source off that object or use something like PlayClipAtPoint like praetor suggested which will instantiate a new audio source to play the sound
i personally have an AudioManager class that pools a bunch of audio sources and works very similarly to PlayClipAtPoint, just using the pooled sources
the clipAtPoint thing stays there forever so i dont have to make an audio source in the object? or how does it works
is there a definitive way to make a raycast? i saw a lot of youtube tutorials but they say different things
i want to make a raycast and check if its touching a layer
which will instantiate a new audio source to play the sound
there's also documentation you can read
thanks ❤️
I think that method is perfect
I guess if the object is moving and the sound is long I have to do the other thing 100%
just note that using that method frequently is going to generate quite a bit of garbage since it creates and destroys audio sources
yeah but if it destroys it after producing the sound what is the problem?
the garbage
like residual memory?
as in the memory being allocated then needing to be cleaned up frequently
that affects to performance I guess
a lot of garbage needing to be collected can cause hitching whenever the GC runs
"Garbage" is a term in programming referring to allocated memory that is no longer referenced anywhere. Most modern programming languages will free that memory for you so you don't need to worry about allocation, but that still does take time, and clearing garbage very often can lead to noticeable framerate drops
right now is only for 5 hearts so its fine I guess
the thing is if the object is moving and the sound is long the clipatPoint wouldnt be a good idea cause it doesnt follow the player, or maybe you can attach as a child while the audiosource is alive?
If you want that, you should probably just have an audiosource on the player and swap out the clip
this solution was for when the object is being deactivated/destroyed and you want a sound to play, not for long running sounds that must follow an object
Why does ```cs
for (CircleCollider2D in Physics2D.OverlapCircleAll(pos, .2f)){
}
Throw a syntax error?
Because that is wrong syntax
Because you didn't give the variable a name
and
other reasons
there are several problems yes
also ideally you should use OverlapCircleNonAlloc and a regular for loop
Are you a Python programmer by chance
No
foreach uses in. for does not
Ah. I forgot about foreach. Thanks
But you still need a name for your variable
And you'll get Collider2D
Anyone know how to align tilemap position with gameobject position? I am currently trying to create a liquid system using cellular automata, which requires me to check for a tilemap tile beneath it to decide whether it should fall or not, and currently they are off-centered so when I convert my transform.position of my liquid gameobject to a vector3int required for the "HasTile" function of Unity tilemaps, it (unless very conveniently placed) will always think there is not a tile below. Any ideas would be amazing!
tilemap positions are stored as whole integers so Ideally the gameobject's (-1, 2, 1) will align directly with the tilemap tile at it's coordinate (-1, 2, 1)
I know, but I only want to interact with CircleCollider2D
you will need to type check the colliders inside the loop then
there's no way to filter for a specific collider type until then
Then you need to filter it
Is there anyway to edit a tilemap without getting lag? I have a big map with a lot of tiles and its really laggy and a lot of timesI get the loading pop up, but if i edit in prefab mode even tho is not that laggy each time i do something it also gets the pop up but with the import text
Giving foreach variable specific type gonna cast it and throw if type mismatches
in code or in the editor?
this sounds like #🖼️┃2d-tools question
editor
then why is it in a code channel 😅
No need for anything to align
Thanks, appreciate it!
use the built in tools
Yeah, I assumed there was something like that I was missing. Appreciate it!
Hello there folks! Anybody perhaps know how to hide GameObject content in scene hierarchy and whats important - still allow selecting it in scene?
So far I tried:
- Using this callback: https://docs.unity3d.com/ScriptReference/EditorApplication-hierarchyWindowItemOnGUI.html, sadly I got no idea how to use GUI nor hide hierarchy items, so I could not achieve anything useful :(
- Using hide flags: https://docs.unity3d.com/ScriptReference/Object-hideFlags.html, closest to that what I want to do, but still not enough.
HideFlags.HideInHierarchydo indeed hide it in hierarchy, but also dirty scene and prevent selection, second flaw can be avoided, by putting objects into GameObject and setting hideflag only for that gameobject, but that means all prefabs needs to be modified which is pain for me :(
Sooo, second solution somewhat works with annoying flaws so far, but first one would be perfect, sadly I got no idea how to use GUI there, I would appreciate any help, thx
I'm trying to just rename a script and my player object can't make any reference to it if I do. It tells me to alter the prefab but it's greyed out?
Ok well now that script just disappeared on it's own that's awesome.
If you rename a script you also need to rename the class inside the script
there's a neat rename function in VS if you right click a renamable word btw. Also renames the script file.
for the future
It's back I guess? But still gives this error.
Check your console for errors
Neither of those help this specific circumstance.
why wouldn't that help? that goes over everything you need to check to ensure your component is loaded correctly
you gotta look at your console my man. follow the links there. You can see it says "console errors" as one of the options. Click that.
You're giving me advice and I'm saying I've already done both to no avail.
Show us then
show your console
Show the console including the icons on the top right, show the ide including the file name and class name
show your code
People tell us that A LOT
Show the full !code for MaraUnit and show the console. Also, have you tried simply reloading Unity to force a recompile yet?
📃 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.
what channel should i go in
public override void OnInteract()
{
inventoryManager.AddItem(item);
Debug.Log($"Item {item} added");
gameObject.transform.localPosition = handPosition.transform.localPosition;
gameObject.transform.SetParent(handPosition.transform,false);
isInHand = true;
}
It parents the child object with offset
handPosition is just an empty
I want it to be exactly where my empty is at.
When I run this code its like my object stays a bit further from the handPosition
Looks like #💻┃unity-talk
Oh, tilemap. #🖼️┃2d-tools
Oh, too slow. You already went there haha
set its localPosition to Vector3.zero after assigning the parent
you also never need to use gameObject.transform, every component already has a reference to its transform through its own transform property
this fixed it but why?
Ah all right. Thanks
because if you want it to be exactly at the parent object its localPosition must be all 0
Ah okay, makes sense. Thanks a lot.
That did it. God.
ngl that was a lot of pressure with those ats
So uhh. I parent the object when I take it in my hand. How can I put it back on the ground without physics. Like it will just unparent and be on the ground.
Should I unparent and parent to the ground?
It just stays like this when I try to drop it 😄
parenting it to the ground doesn't make it move
it's just going to follow the ground around now
you can use a raycast to find a spot on the ground to place it
public void OnJump(InputAction.CallbackContext context)
{
if (context.performed && isGrounded)
{
Vector3 newVelocity = new Vector3(rigidbody.linearVelocity.x, jumpForce, rigidbody.linearVelocity.z);
rigidbody.linearVelocity = newVelocity;
animator.SetBool("isJumping", true);
}
}
private void Update()
{
if (Physics.Raycast(transform.position, -transform.up, 0.5f, groundLayer))
{
isGrounded = true;
animator.SetBool("isJumping", false);
}
else
{
isGrounded = false;
}
}
is there anything wrong with my code?
You say what's wrong. We try to figure out why's wrong
well, the animation wont play
the jumping works though
I dont need it to move though. Like it can stay on the ground till I pick it back up again
Well, you set the isJumping boolean to false whenever there's ground below you, which is likely going to be true even right after your jump starts
oh. well what should i change
okay, but it's also not going to make the box fall or appear on the ground
heres my full script if u wanthttps://hatebin.com/duywcoqifj
Ah so it will just stay like that in the air but it will follow the ground as its the child. What kind of spot should I be searching with the ray then?
A decent way is to not count as grounded when your Y velocity is up
you can raycast downward from the box's current position
i tried that but it didnt work, the value for the y velocity got stuck
What do I do with the out info then?
move the box there, presumably
since you just found a spot on the ground
Note that this would put the box halfway into the ground
Yeah I need to offset it a bit then?
can anyone send me an easy script to pause/resume my game? like by pressing p the game just freezes and by pressing again it unfreezes? its first person template btw
It should reset its rotation when dropped.
okay, so you can just set its rotation back to Quaternion.identity, then raise the point you find on the ground by half of the box's height
Goddamn I have to do this with all my equippable items then?
you can automate it a bit
this is what happens when i set it to my rigidbody linear velocity
I guess I can make a method and do it inside.
transform.rotation = Quaternion.identity;
Physics.SyncTransforms();
Vector3 offset = collider.bounds.y / 2 * Vector3.up;
set what
something like that
wait nevermind my conditions were wrong
the SyncTransforms is needed so that the physics system learns about the new rotation
the variable
I never said to set anything
I do not use physics in my game though
I said to check the Y velocity as part of your grounded condition
This just uses the a collider to figure out the size of the object.
You could also use a renderer to figure out some bounds automatically, I guess
ohhh i see
So that you're considered grounded when the raycast hits and your Y velocity is 0 or less
But it'd be nice to just define the size of the object once (with a box collider)
All right I will go and try it now. Thanks a lot.
It just feels like I'm doing everything wrong and not reusable haha.
if (Physics.Raycast(transform.position, -transform.up, 0.5f, groundLayer) && rigidbody.linearVelocity.y <= 0)
{
isGrounded = true;
animator.SetBool("isJumping", false);
}
else
{
isGrounded = false;
}
like this?
ok thank you that fixed it but now it does the animation twice
maybe i could decrease animation speed
or decrease jumpingforce
you'll get it eventually! Just gotta keep practicing, which you are doing, so keep it up! 
Thanks for the motivation!
Disable looping
How do I make sure my player is facing forward? I tried the simple way of changing the sprite to them in the forwards idle position but they reset back to idle downwards
Here's my player controller script code for reference: https://gdl.space/mokuduzozu.cs
I did this now i cannot event drop it
bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f, groundLayerMask);
if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
{
item = inventoryManager.GetSelectedItem(true);
transform.SetParent(null);
transform.position = hit.transform.position;
transform.rotation =Quaternion.identity;
inventoryManager.DropItem(item);
}
Facing forward when they enter the room***
Oh I think I am ignoring the ground layer thats why?
Heya! I'm trying to set up vscode with unity. I installed the plugin and got it set as the editor, but intellisense isn't working, so autocomplete and code insight features aren't working. I don't know what I'm doing wrong, any help is apprecieted
!vscode
follow all of the instructions there
I did all that already
then regenerate project files and restart vs code
also if you've only just installed the c# extension, make sure to restart your PC
so i want to basically move an object directly onto my mouse if that makes any sense i want it to move like its being set to the position of my mouse except its using a rigidbody heres my code and how it works
make the rigidbody kinematic for the duration you are moving it with the mouse so it doesn't do that
then you can just set the position of the rigidbody
It still doesn't work
void Update()
{
bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
{
item = inventoryManager.GetSelectedItem(true);
transform.SetParent(null);
transform.position = hit.point;
transform.rotation =Quaternion.identity;
inventoryManager.DropItem(item);
}
}
So this drops the object(at hit point) it goes into the ground though. I could not manage to offset it. How do?
by adding Vector3.up (times the appropriate value) to the position
if you cannot get vs code to work by following the guide, then consider switching to a real IDE like visual studio which is far less likely to break
I can't use visual studio on linux
it interferes with somecode and doesn't really work how i want it to
And I can't afford rider
i want it to build momentum horizontally as well while being held
that's not very specific
I do it before matching the position to hitpoint?
Yes, you'd be calculating a new position
Any clues on how to set the player's positon to up when inside? Here's what I've attempted so far
/*
* if Player is inside
* Set direction to up
*/
if (isInside)
{
transform.position = Vector2.up;
}```
is there away i can get a similar effect of setting the position to where the mouse is just by using a rigidbodys force and velocity
if there's a collider on the object, you could use that to determine the amount you need to offset it (after the Quaternion.identity step):
transform.position = new Vector3(transform.position.x, transform.position.y + collider.bounds.extents.y, transform.position.z)
```(I think that will work, i typed it in discord)
oh..sorry, here
there is a collider but I cannot access the collider
use GetComponent<Collider> to reference the collider?
Ah okay I'll try
void Update()
{
bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
{
item = inventoryManager.GetSelectedItem(true);
transform.SetParent(null);
transform.position = new Vector3(hit.point.x, hit.point.y * 2f, hit.point.z);
// transform.position = hit.point;
transform.rotation =Quaternion.identity;
inventoryManager.DropItem(item);
}
}
This also works but I'll do it your way I just tried the number.
ah by one y level you mean if any ground is higher or lower I'd have to come back and adjust it accordingly?
yes, since your'e just doubling the Y position of the object
in world space, so it depends on where the ground is positioned
You can just give each item a "size" field that tells it how to position itself
You could even store a Quaternion that represents how it should be rotated when on the ground
try this, but instead of * 2f do + GetComponent<Collider>().bounds.extents.y (which requires all the items have colliders, so you may want to add the [RequireComponent(typeof(Collider))] attribute above the class name
transform.position = new Vector3(transform.position.x, transform.position.y + _collider.bounds.extents.y/2,transform.position.z);
I did this but its way up above the ground
stored the collider at start.
I'm getting confused a bit haha
this just moves the object up
you're using the current position of the object..
oh yes there is nothing about hit.point
you need to stop and think about what these numbers actually mean
otherwise you'll just be banging random variables together
you should create a few variables instead of doing everything in one big one-liner
Vector3 point = hit.point;
point += Vector3.up;
transform.position = point;
for example
store hit point. Then add 1 on the y axis. then match the position
right!
you'd want to do something more clever than that
liike what Heroshrine suggested
transform.position = new Vector3(hit.point.x, hit.point.y +_collider.bounds.extents.y/2 , hit.point.z); Wat about this!
break it up!
but it looks reasonable enough
one concern: your collider will still have the old rotation
consider doing this before you get its extents
Imagine you're putting a stick on the ground, but it was rotated vertically in your hand
The bounds will be huge in the Y axis
ah yes I'm doing that as you said. Wait here is the full thing.
void Update()
{
bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
{
item = inventoryManager.GetSelectedItem(true);
transform.SetParent(null);
// transform.position = new Vector3(transform.position.x, transform.position.y + _collider.bounds.extents.y/2,transform.position.z);
transform.position = new Vector3(hit.point.x, hit.point.y +_collider.bounds.extents.y/2 , hit.point.z);
// transform.position = hit.point;
transform.rotation =Quaternion.identity;
inventoryManager.DropItem(item);
}
}
First of all, you have a condition for your prefabs to spawn if the elapsedTime, increased by Time.deltaTime in the Update method, is smaller than the random value between the minimum and maximum spawn time. This is going to spawn quite a lot of fireballs at the beginning of the game.
elapsedTime += Time.deltaTime;
if (elapsedTime >= Random.Range(minSpawnTime, maxSpawnTime))
This is also not a great way to do it, since the number of spawned fireballs is going to increase according to the user's fps
How the hell am I supposed to use this logic on every item object T_T I gotta think now.,
Thanks for all the help it works perfecto now!
by using the same component on all of your items
you can either inherit from it (to create more specific kinds of items) or just use it along with other components
a tool could have an Item component (that handles picking up and dropping it) and a Tool component (that lets you do something with it)
It looks like the C# Dev Kit plugin version 1.5.20 and above is broken
I have v1.6.8, which works just fine
you have to follow every step on the page; you can't skip over or re-interpret anything on it
if (Input.GetMouseButtonDown(0))
{}
What is the condition for this method? What is the 0 doing in this circumstance?
notably, you need to have:
- the correct packages installed in Unity
- the correct code editor selected in Unity
- the correct extension installed in VSCode
consult the docs!
I did do that, I looked up my issue on google and this issue is what I found
the last comment suggests the pre-release version fixes this
Oh neat, I didn't see that
Possibly because I've got .NET 8
it was installed by the .NET Install Tool extension
Anyone ever spend an hour working in a script just to realize you're in the wrong script? 😂
can someone help me with understanding how I can implement my player's head's face always being where the camera is looking, but allowing the body to rotate independently with tank controls? (will start a thread w/ a diagram)
What I suggested though only works if the collider is the size of the object. In reality you also probably want some “offset” vector serialized in the inspector to add to it so you can fine tune it. So basically, both of what we said lol.
@final kestrel
yeah, I'd just store a rotation and oposition offset
Nah I resized the collider by hand 😄
But thanks a lot for the help. I made it work!
I mean the object so the collider too
- this is a code channel. #💻┃unity-talk or #🔀┃art-asset-workflow would have been more appropriate for this question
- as long as whatever that is produces a supported asset type you just import the asset like any other asset
I know this is a coding channel, you should do what boxfriend said. However, I dont think you’d be able to do it with animations since im pretty sure the only thing it can export as that unity can read is a obj file. So you’d need to re-create the animations in unity.
I replaced the line of code you sent with mine in the Spawner, but even if it still doesn't give explicit problems it continues to do so. From what I saw it started to give problems when I created the void OnCollisionEnter2D(Collision2D collision) method found in FireBallsMovement
Show code
telling you where ur question belongs is helpful imo.. lol
if im ever visiting some foreign country i'd rather people tell me directions than point out that they aren't a map
that said, I thought FBX's could include animation
turns out they crossposted from the correct channel to here anyway. they are probably just mad that nobody spelled out the answer for them or that they never even got a response in the correct channel because they barely put any effort into their question
holy heck, FBX means Filmbox 🤯
i want to make it so that a ball in my game makes a counter go up by 1 everytime it bounces and i did this by checking whenever it collides with something. however when it has stopped bouncing and is laying still on the ground, it just continues to increase the counter because it's still technically colliding with something. how do i fix this?
https://hatebin.com/lzdkwsqurd
you've pasted the class in there twice, but OnCollisionEnter2D is only called when the collision is first entered, it is not called continuously until it has ended so whatever is increasing the score continuously is happening elsewhere
if its helpful u can log the collision w/ debug class and check the console.. see whats causing collisions
my character has a landed mechanic.. soo when I jump and i lose contact with the ground i change my bool inTheAir
then only if thats true.. and i collide with the ground it calls a function.. this sets the air bool to false.. so the
function doesn't count any more of hte collisions unless i jump and leave the ground again
but OnEnter is fast and simple
i fixed it using this logic, thank you!
no problem 🍀 good luck
What is up
a direction
Y axis
not much what is up with you?
I have math class rn 😢
Vector3(0,1,0);
I actually have to go goodbye
<looks around> okiedokie
im seeing something abnormal which the docs say shouldnt be. Im registering C# events in OnEnable and OnDisable but getting null reference exceptions. if i have one such registering object, it works as expected. if i have two or more, then any gameobject after the first gets null reference exceptions. however, if i move the de/registration to Start and OnDestroy, everything works fine. I have verified my script excecution order is at defaults, etc. anyone else seen this?
is the NRE happening when you invoke the event, or when you try and subscribe to the event
it's getting thrown in OnEnable upon trying to reg. but, again, only for GOs beyond the first one.
show relevant code, how you subscribe as well as the object the event is on
the event is being fired by a Singleton.
well that validates my assumption that you are likely destroying the object you are referencing in those objects that subscribe to the event. you still need to actually show relevant code so that we can confirm what is actually happening
{
// subscribe to the event
TimeManagerScript.Instance.TickWithID += this.tickedUpdate;
}```
the reg'ing GOs have that. OnDisable is same but -=
now show the singleton like i already asked you to
sry. misiunderstood. no need to be jerk
TickWithID?.Invoke(new TickEventArgs(this.ticks));
like i said, it's straightforward and weird.
not being a jerk, you're just making assumptions. but now i'm not going to help you, good luck
cool. you too
also FYI, i didn't want just the line where you invoke the event. the entire class would have been helpful
hence why i said "the object the event is on" and not just "only the line where you invoke the event"
ive moved on. you should too
oh my bad, here i was thinking that helpful advice might actually help you get the help you are seeking in the future. if you don't want to get help from anybody though, that's fine too
fair, i retract my last.
ill figure it out. ty for offering to help
(but there is zero way that saying, "as i already asked" isn't something less than polite)
I disagree
It is a polite reminder imo
fair. it doesnt come off that way to me. maybe it's subjective.
or we just have different expectations. all good.
Some common members of this server ends remarks with "..." - not implying dissatisfaction but etc (the rest)
Don't read into it too much. It's just text unless they outright insult you.
when i use 2 input directions, my movement speed increases, how do i fix this?
Normalize your input vector before multiplying it by your speed
well said. . .
RandomUnityInvader(); must be out. just wanted to chime in for him lol
Is this the right way to get a button onclick and offclick? It seems to not work as intended
public void OnPointerDown(PointerEventUnit pointerEvent)
{
buttonPressed = true;
mText.text = "a";
}
public void OnPointerUp(PointerEventUnit pointerEvent)
{
buttonPressed = false;
mText.text = "Hint";
}
Is this on a UI object and does it implement the interfaces that define these functions?
Hmm I don't think so, let me take a closer look at what I'm doing
using UnityEngine;
using UnityEngine.EventSystems;
public class ButtonClicker : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("button pressed");
}
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("button released");
}
}
``` you'll need an EventSystem and a GraphicRaycaster component w/ this setup @dense root
private Collider2D GetLiquid(Vector3 position, Vector2 direction)
{
RaycastHit2D hit = Physics2D.Raycast(position, direction, 0.5f, layerMask: 4);
Debug.DrawRay(position, direction, Color.red, 5f);
return hit.collider;
}
Hey! I am currently creating a function that is supposed to simply detect whether there is a liquid in any cardinal direction for use in a liquid simulation script, however it is always returning null even when there is a very clear ray going through the collider when using "Debug.DrawRay", if anyone has any ideas as to why this may be any help would be amazing! it is currently being used in an if statement as so:
GetLiquid(transform.position, Vector2.right) == null
They all have "Box Collider 2D" components with the proper sizing as-well.
your layer mask will only detect things on layer index 2, which also happens to be the Ignore Raycast layer
oh! Haha, that's probably not a great thing. Is layerMask: 4 not the layer labelled 4?
nope
no, read the link i sent
oh fantastic, I'll just define it haha.
thats what i do.. cuz i suck at bitshifting and watnot
That seems a little unintuitive in my inspector but I appreciate the help!
LayerMask.GetMask("Water"); would return the "Water" layer's bitmask I assume?
you are trying to use a layer index, but layer masks are bitmasks
int layer4Bitmask = 1 << 4;
Debug.Log(layer4Bitmask);```
something like that lol
edit: actually idk, so why i use layermasks
okay, perfect! I appreciate the explanation, I suppose that makes sense. There are a lot of different "masks" in unity that all have wildly different usecases I see haha.
Yeah, I'll just be using layermasks as they seem a little easier to read lol.
Yeah I had a peek, I think I understand the concept a little. But I don't really think it's all too important for me at the moment haha!
nah, probably later on you'll find a need for em
I'm just mocking up a simple cellular automata liquid script and I was wondering why it wasn't watering haha
oh probably, I do appreciate you bringing that to my attention. I'll at-least know to look into that when someone brings up bitmasks vs layermasks.
the layers are like binary
1, 2, 4, 16, 32, etc
so layer 4 is 16
you can bitshift 4 spaces 1 being 0001, so 4 spaces 1 << 4 is 10000 which is binary for 16
im talkin out my arse tho.. lol cuz i get amazed anytime someone else explains it..
esp when they explain it like its 2nd nature
haha, I'll probably look into it. It sounds pretty interesting but I'm too tired to not take the easy route of LayerMask.GetMask with a string ahah
already working on a decently complicated concept for water simulation right now, anything more and I might just cry lol.
theres a raycast overload that takes in a layermask
wouldnt even need to convert it to a string or anything
Physics2D.Raycast(transform.position, Vector2.right, Mathf.Infinity, layerMask);```
"Ray hit something on one of the specified layer(s)."
could just chose Water in the layermask.. and just use a layermask but i guess that works too ^
if(Physics.Raycast(transform.position,targetDir,out tempHit,rayDistance,layers))
{
hit = tempHit.collider.gameObject;
success = true;
}``` one of my raycasts
true, but it's nice to have an actual name in script since I am planning on hardcoding a few different liquids, so having the actual word might actually be useful, but honestly it doesn't make a huge difference either way haha.
How can I make the code blocks with color?
hardcoding 😅 👻
spooky
your code block
three backticks the language -> enter to drop down a line.. -> paste ur code
then three more backticks
oh so cs makes them with color?
yeah for now, the final implementation will almost definitely not be but inspector references break/release a ton if you mess with them wrong. I usually just hardcode and fix later ahah.
Yes, if you use actual cs within' it.
cs makes C# code colored.. syntax highlighting
Theres many different languages it can highlight tho
there are a lot of usable languages which will color it.
You can use markup which allows you to directly color text I believe.
ah nice thanks a lot.
discord doesn't allow markup it supports markdown tho
true I meant markdown 
Markdown
- is
- pretty
- awesome tho
true
default dashes used in a list automatically convert to markdown I believe
- test
- test
yeah
oh i found a bitshifting calculator.. thats cool
i bet i could write a function that takes in a layer number and returns the bitshifted value
would make me finally use em a bit more often lol
haha, maybe!
for single layers its easy
i mean, that's easy. it's just public int IndexToMask(int layerIndex) => 1 << layerIndex;
its multiple layers where i get screwd up
oh damn, see boxfriend already did it before i could finish thinking bout it haha
ya, i think i finally comfortable with single layers
just bit shift 1 by the number
doing multiple is just as easy.
public int LayersToMask(params int[] layers)
{
var layerMask = 0;
foreach(var layer in layers)
layerMask |= 1 << layer;
return layerMask;
}
ohhhhhh i think i just had a rev-e-lation..
int combinedMask = layer1 | layer2 | layer3;
Revolution 😂
gottem lmao
also are you able to set a custom fixedUpdate rate?
yessir
like 5 updates per second rather
in the Time section
of Preferences or Project settings.. cant remember which one
or thru code
is there a custom FixedUpdate that allows you to define the updates/s
directly in code that is
project settings it was
Time.fixedDeltaTime = 0.02f;```
It’s always that?
Alright, I'll look into it. Thanks!
1f / desiredFPS; if u want to use ur desired frames per second instead
What’s difference between normal time delatime
deltaTime is the time between frames.. depends on ur frame-rate
fixedDeltaTime is the physics step, and is locked to a constant value
Oh
deltaTime is the Update()
and fixedDelta is the FixedUpdate()
I see
constant fixed step = reliable physics
AddComponent creates a new instance when adding to an existing gameobject, right?
I don't have to call new before, correct?
you should never call the constructor for a component
I have this odd behavior where my text field is being changed yet the only time I call CorrectResponse is shown in this field.
public InputField inputfield;
[SerializeField] BattleManager battlemanager;
[SerializeField] Text correctResponse;
private void Start()
{
}
private void Update()
{
string inputText = inputfield.text;
if (inputText == "a")
{
//correctResponse.text = "Correct!";
}
//if (battlemanager.inBattle == true)
//{
// inputfield.Select();
//}
}
Did you save your code
Yup I did
I guess a better question is how do I diagnose what is calling my CorrectResponse game object? Since this script is obviously not the offender
well if u disable or remove the component u should get a null error from the script trying to call it
Deleted the component but it's not throwing an error, very strange
lol, must be that script then
What is the issue?
phantom code running i think
The intended behavior is for the text to appear within the box, yet somehow I coded it so that the Correct Response text displays the text being inputted
Is your text input component referencing that correct response text?
show the entire script
show the input field component
Yeah the inspector of it
this is not the input field
No the Input Field component
it doesn't even have a text component assigned to it
Why the text component none?
I think when I was tinkering I put a value there then removed it
Anyways it works now that I assigned the text component
👍
Does Unity automatically go to a text component if none is found?
Because I thought in theory it should just do nothing with it
heres another tip for ya, i used a text input field a while back for inputting a password.. and i could not get the fields to match.. even when they did..
turns out that there was an extra character that i couldnt see
password was the text i was looking for but
password was the text that it kept comparing
so might be something u run into. but it was long long time ago.. so may be a non-issue now
he could check the component in runtime w/o the variable and see if it gets populated somehow
Remove the Text variable and test again?
text mesh pro input doesn't do it
Sure you could do that for sanity check
text mesh pro is like 'nah bro, u aint that lucky'
Well I deleted all the previous stuff but I can try it again if I am able to recreate it and then report back.
👍 recreating a bug/issue is sometimes harder when ur trying lmao
lol
Might be just gone like Heisenbug
Is there any prior art for using a cylinder for a character controller's collision
I'm trying to do stuff with 3d platforming and using a capsule doesn't make sense and a box sucks for rotations
CCs don't use cylinders since they're not mathematically friendly for calculating physics/overlaps.
Why does using capsule not make sense?
Probably edges. I was about to ask the same thing haha
Falling off of edges
Just do a cast downwards and don't apply gravity is on the ground. A wider cast like circle, or multiple rays (front, back, and maybe middle)
Maybe use a different method for ground checking then
capsule is the best fitted collider
I'm currently trying to implement a collide and slide algorithm for it using a kinematic body instead of a primitive, but it phases through surfaces when not moving across the surface's normal
This is my code for it
Wait, are you using a CharacterController?
No I am not
Oh, we were all assuming you were because of this
#💻┃code-beginner message
My bad
what type of collider are you currently using on it?
A cylinder
wdym a cylinder? there is no cylinder collider unless you are using Unity.Physics which is for dots
hehe facts
body is a RigidBody with a cylinder mesh
i asked about its collider
the cylinder mesh uses a capsule collider
yes
so it's got a convex mesh collider. that is fine then
At first intellisense for the input system worked, but it didn't work in unity because i forgot to restart the editor, so I restarted unity & vs, but now intellisense doesn't work in vs and the input system does work in unity
regenerate project files and restart visual studio
thanks
how do you change the bounciness of a physics material 2D through script?
regenerate project files in preferences>external tools doesn't do anything for me
it doesn't do anything visually, but it will re-create the csproj files so that when you restart visual studio it uses the newly created ones which generally fixes issues with types and namespaces not being recognized in visual studio (if there isn't supposed to be an issue with it)
so if that does not work, then either you are using asmdefs in your project and need to reference the input system's assembly in your asmdef or you might need to regenerate your project's library
oh or you just aren't generating enough csproj files
although I will say i've not had issues with the input system namespace and i have 0 options selected for the csproj files
I've restarted vs and deleted library entirely
are you using asmdefs?
you would be surprised at how many people have claimed they aren't using them and have no idea what they were but actually did start using them for some reason or another
u dont have the VSCode package installed do u?
as well as having this updated to the newest version?
sometimes when my IDE wigs out like that I can delete the csproj file and restart unity and it fixes it
visual studio editor was updated, I can't find a VSCode package anywhere is that in unity? I am not using VSCode, VSCode 2022
I'll try that though
deleting the .csproj worked, thanks guys
good to hear!
sometimes Cinemachine does that to me so thats the reason I knew of (a) fix
If I use code to dynamically change tiles in a tilemap during runtime (like a player character editing terrain for example), do the rule tiles dynamically update and apply to all changes or do I need to code the changes to the surrounding tiles manually?
Basically, do tile rules apply in real-time during the game or only while initially painting the tilemap?
Hello, I am pushing my unity project to git, and I added this unity .gitignore found online,https://github.com/github/gitignore/blob/main/Unity.gitignore,
but these two webGL build related stuffs got pushed to git, just want to have a confirm whether I should keep them on git
Dang. Thank you. I saw someone on YouTube using this technique and their tiles updated automatically and they didn’t mention how except to say “the rule tiles handle the rest” or something like that. I was skeptical but hopeful
I'm pretty sure they work at runtime...
painting tiles is equivalent to calling SetTile
Oh hm… now I’m confused lol. I guess I could test it by making a mini game and seeing what works. Pita though.
I will go check it
That would be so kind of you. Don’t put yourself out though
yeah, it works fine!
void Start()
{
BoundsInt bounds = new(-2, -2, -2, 4, 4, 4);
foreach (var cell in bounds.allPositionsWithin)
tilemap.SetTile(cell, ruleTile);
}
just set a bunch of tiles through a script
(in hindsight, this was trying to set tiles in a cube, which doesn't really make sense for a 2D tilemap)
@swift crag wtf you are amazing, thank you! I dunno how you even did it that fast, I was expecting it to be a whole big thing.
no problem (:
I'm still learning 2D, but I've been doing a lot of scripted tile setting
hadn't actually used rule tiles yet though
Hello! I'm trying to do twitch integration on Unity and I'm having trouble making it so that if someone does a command for their avatar on stream, it only does it for that avatar and not all of them. I was attempted to use a concept of checking all the avatars in the list and whichever avatar name matches someones name who is doing the command, it does whatever. However, I've run into an issue because the avatar itself is a clone of a prefab and thus it's looking for that original prefab.
if you instantiate a prefab instance you should have its own independent reference
are you not storing these reference, or probably post what code you have
You mean right here?
what is player
Player is the prefab that all the avatar copies are made from
but specifically the var Player is the rigidbody2D of the prefab
!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.
not really enough information from that. Need to know where player is being created, and how those instances are being handled
once an object is instantiated, the changing the prefab should not reflect those that were previously instantiated by it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't see you instantiating player anywhere. You're just using the serialized reference that you inserted from the editor it seems.
so I'm not really understanding where these multiple players come from
You do make avatars, whatever those are. But player is a member value here and you only access that specific instance
if (layers != 0) // Check if enum set to a specific layer mask
{
// Raycast with the specified layer mask
if(Physics.Raycast(transform.position, targetDir, out tempHit, rayDistance, layers))
{
hitObject = tempHit.collider.gameObject;
hitPosition = tempHit.point;
success = true;
}
else
{
hitObject = null;
hitPosition = Vector3.zero;
success = false;
}
}
else
{
// Raycast without specifying a layer mask, hitting all layers
if(Physics.Raycast(transform.position, targetDir, out tempHit, rayDistance))
{
hitObject = tempHit.collider.gameObject;
hitPosition = tempHit.point;
success = true;
}
else
{
hitObject = null;
hitPosition = Vector3.zero;
success = false;
}
}``` this lookin uber repetitive to me. whats a good way to simplify this?
can probably stick the else into its own method but other than that you're using two different filters
it's like one of those things you just toss into copilot for an opinion
whats layers in this case? i think you could just set it to include all layers and then suddenly the code is the exact same
Hey, I think I figured it out. You brought an obvious fact to my attention.
yea i would just swap this logic around. You're checking if its set to "nothing" but instead you could just use some local value which includes all layers
i have a similarity on another set of variables
but they were as chunky in the comparison.. i just used a ternary for it in awake
if nothing is selected the raycast will desireably hit everything
soo.. i could do the two, or a bool maybe
yes, what i am saying is do this
int layersToHit = layers == 0 ? ~0 : layers;
if its 0, set it to include everything. else just use the editor value
then do your raycast ALWAYS from layersToHit
this removes the need for the if else
see... thats an epic thought
lol.. soo simple
ohh, I found Physics.DefaultRaycastLayers
Hello, so I was able to make it so that a person in chat will only move their avatar that is on screen. However, now it's making it so the previous person's avatar can't move theirs. I believe it's due to the fact that "spawned" is only attached to the most recent spawned avatar. I'm not sure how I can loop through all created avatars and check to see if the person making the command is the owner of a specific avatar. I've attempted a simple loop that looks through a list of avatars but I continue to get stumped on how to apply it. https://hastebin.com/share/ragezaqoqa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
void PerformRaycast()
{
success = Physics.Raycast(targetObj.transform.position, targetDir, out tempHit, rayDistance, targetLayerMask);
hitObject = success ? tempHit.collider.gameObject : null;
hitPosition = success ? tempHit.point : Vector3.zero;
}```
noice..
i used `targetLayerMask = layers == 0 ? Physics.DefaultRaycastLayers : layers;` in the awake to avoid that extra conditional in update
Hi guys, i'm trying to change the texture of material by using material.SetTexture but it dont work. Anyone have any idea about this? My material use ArnoldStandardSurface!
My Func:
{
rend.material.SetTexture("_BaseColorMap", texture);
Debug.Log("Floor Changed");
}```
try creating a copy of material, setting the texture on the copy and applying the material back to the meshrenderer
i'll try it, thanks!!
How would I detect Input.GetKeyDown(KeyCode.S) on an item gameobject, but only while hovering that item with the mouse?
Do you already know how to check hovering on the item?
u just have to combine the two...
if(isHoveringButton && Input.GetKeyDown..) or..
{
if(Input.GetKeyDown...)
{
// do something
}
}```
is there an option for it?
I just added a bool that is set to true with IPointerEnterHandler and back to false with IPointerExitHandler
I don't know what you mean by option
If you already know how to do it by any means, you can just combine the two with && like scg showed
maybe there's an easier way to check if an object is being hovered?
not that im aware of, i use the EventTrigger component alot b/c its quick and even in the option dropdown I went looking for a hover option, cant find it
all the hover mechanics stuff i remember doing it like u do, with an enter and exit bool change..
there might be tho. maybe someone would know
yeah pretty sure I'm using PointerEnter & PointerExit, in code though, didn't add the component to the gameobject, but think it works the same
mmhmm similar stuff
You can do a raycast with ScreenPointToRay but if that's easier is up for you to decide
https://paste.ofcode.org/WU4iuFHAxBnQGEQzvELUQy. this is your code
Thanks ChatGPT
ray = new Ray(cam.transform.position,cam.transform.forward);
if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
{
if(hit.collider.transform.TryGetComponent(out IInteractable interactable))
{
cachedInteractable = hit.collider.gameObject;
if(Input.GetKeyDown(interactKey))
{
interactable.Interact();
}
}``` i prefer Interfaces and Trygets
I'll just stick with the pointer enter & exit lol
how can i change struct values in unity ?
{
public AgentData agentData;
public void SetSpeed(float speed)
{
agentData.moveSpeed = speed;
}
}```
adjust agentData = new AgentData doesn work too
Do you get an error? Why do you say it "doesn't work"?
the data doesn't change. just that
Structs are a value type, NOT a reference type. That agentData variable is a COPY which will not affect any other copy. Which copy of this struct are you looking at when you say it doesn't change?
It should change this local copy owned by physicsagent
debug agentData.moveSpeed; immediately after you change it
i got it. thanks so much
Hey guys, I have text that is attached to an empty child of my player. How would I go about making it so that it doesn't get reversed when the player goes the opposite direction?
textsObject.transform.rotation = Quaternion.Identity;
could reset its rotation in update or something
could unparent it and have it just track the player's position with an offset added.. textObject.transform.position = player.transform.position + vectorOffset;
could have it look at the camera.. theres lots of ways lol
ohhh transform.rotation = camera.transform.rotation!
id say you are just reversing the wrong object in the first place, it can still be parented in such a way where the visual cube is a child under the actual moving player. Text can now also be a child under that. You swap those visuals around and it doesnt affect the text
too lol
I'll try, thanks guys!
I like to stick rotational constraints on them and link em to some gamemanager that doesnt rotate
ah yea, cool component
does manually resizing minimized window trigger an event?
It worked!
Hi @rocky canyon , i'm trying this way but it doesn't work 😦
hmm,cs Material newMaterial = meshRenderer.material; newMaterial.mainTexture = testTexture; meshRenderer.material = newMaterial; something like this normally works for me
My Func:
{
Material newMat = rend.material;
newMat.SetTexture(BaseColorMap, texture);
rend.material = newMat;
Debug.Log("Floor Changed");
}```
what if u used rend.sharedMaterial; not sure the difference in the two actually
if that doesn't work then idk.
nothing change :((
There my material
that ^ would work too
ohh its a shadergraph material
ya, that might be a bit different on how u access the graph's properties
nah, that is my last choice!
this thread seems to chagne it like u do.
id make sure ur variable is exposed and everything in the graph.. and it should work.. w/ settexture but unsure why it doesn't in ur case
ur _Reference is probably different
nah, i'm sure it's correct
maybe i need to create some material
oh, i figured it out. the last character in my nameID has not been capitalized 
Sorry for my carelessness!
im following a tutorial to add a gradient to a progress bar but when i click on the menu it doenst open, how can i open the gradient editor?
when i press it nothing happens
So I have a class called "ProjectileHandler", and I want to create a script which is basically an alternate version of it which is the exact same, except that it has a different method for moving, like "ProjectileHandler" normally moves the projectile in a single line, but the alternate version (lets call it "CurvedProjectile" sends it off in a way that it curves over time
Can I use inheritance for that?
i have something like this until now
in a way i want to extend it
basically be the exact same thing, but it also has curving
By the comments it seems like you already have some SetMoveDirection method in the base class. Is there a specific issue that's not working?
i decided not to go with that approach in the end
problem is that if I have this script enabled, the movement stops working
Either inheritance here is gonna be used to set a vector, being the next move direction that the projectile does.
Or it directly moves the object however it wants.
Im not really sure what you mean by that last line, all the movement related logic is commented out
in that case yeah I did, but overall it just didnt work
ignore the inheritance messages actually
rn im having issues with rotating my projectile....
{
if(Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
if(Input.GetKeyDown(KeyCode.Z))
{
Debug.Log("CTR + Z");
}
}
}``` How can i detect CTR + Z key shortcut in unity runtime through script, I have tried this code but its not working , btw i'm building for web.
CONTROL + Z
Oh, I am not mac and pressing control is not working bcs i have pc keyboard
Hello, do you know how to draw these spheres? I would like to debug 3d vector visually
You could just google Unity Draw Sphere and get to https://docs.unity3d.com/ScriptReference/Gizmos.DrawSphere.html
But I don't know how drawing spheres and debug 3d vector are the same, so perhaps I don't understand your question.
Its all I need thanks
by debug 3d vector visually I mean draw it in the scene so I can see where it is instead of looking in an endless list of vectors in the console 😃
How can I use rb.MoveRotation to rotate an object by x degrees per second?
the example on the unity documentation straight up doesnt work
show what you tried
private void Awake(){
//main = GetComponent<ProjectileHandler>();
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 angleVelocity = new(currentDegreesToRotate, currentDegreesToRotate, currentDegreesToRotate);
Quaternion deltaRotation = Quaternion.Euler(angleVelocity * Time.deltaTime);
rb.MoveRotation(deltaRotation * rb.rotation);
}```
it does nothing
and yes I wanted to rotate it in all directions
wait
look at the unity example again, the order of operators in your move rotation is different
im stupid, nevermind
i used the wrong parameter
yeah thank you
idk how i didnt notice
cuz like
using Transform ways to rotate it works perfectly
except when I have a rigidbody
in which case it ignores it
it is still being ignored
it works in one scene
doesnt work on other
the main problem is that I'm also setting velocities
but not in the same thing way/script
you should be controlling the rb from a single place, just for ease when it comes to debugging stuff like this. Also for your issue above, its likely they both have different settings. Maybe the environment has friction or the player does. Hard to say without seeing the setup but shouldnt be so hard for you to go through and see whats the same
Hi! I'm a real beginner in unity and I am just trying to understand how a button works and idk why but my button don't do anything when I click it
you need an event system in your scene. it shouldve been added when you added the canvas so maybe try just adding a new canvas or manually create the object
so i added an auto jump and it applies a force when the player enters its trigger
but after it applies the force, i cant jump anymore
[SerializeField] private float jumpForce;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
other.GetComponent<Rigidbody>().linearVelocity = new Vector3(other.GetComponent<Rigidbody>().linearVelocity.x, jumpForce, other.GetComponent<Rigidbody>().linearVelocity.z);
}
}
How does your jumping work?
does that code even compile?
Also consider caching the rb value: var rb = other.GetComponent<Rigidbody>()
linearVelocity seems to be a new thing in Unity 6
oh yea i just saw that
public void OnJump(InputAction.CallbackContext context)
{
if (context.performed && isGrounded)
{
Vector3 newVelocity = new Vector3(rigidbody.linearVelocity.x, jumpForce, rigidbody.linearVelocity.z);
rigidbody.linearVelocity = newVelocity;
animator.SetBool("isJumping", true);
}
}
yeah i dont even know what the difference is between that and angular velocity
i just used linear
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider-attachedRigidbody.html
you dont need get component at all also
as for your jumping logic, add debugs. you likely arent considered grounded anymore
yeah i thought that was the problem
ill try that, thanks
okay so the problem is that its not grounded anymore
hm some messages get deleted or my discord bugging?
why is it that even if my projectile is rotating, it doesnt change trajectory?
yeah i saw that too
my problem still isnt fixed tho
idk why its not registering the ground check
Add debugs, print out if your raycast is even hitting anything. If so, print out what its hitting, and if you're considered grounded after that.
Is anything telling it to move towards its own forward direction?
the object is rotating, but the movement ignores it
Rigidbodies arent rockets by default
doesnt rb.velocity do that?
i added debugs, the jumping input works its just the raycast not working
so therefore the jump isnt applied
Rb.velocity is in world space, not relative to the object
lord....
alright
how could I add it here?
i know I have to multiply it by transform.forward
You could multiply it with transform.rotation or rb.rotation
moveSpeed * transform.forward.z?
Or this yeah
how could I even multiply it by that
Well no, you cant just take the z component
not working is very vague, what specifically isnt working. Use stuff like Debug.DrawRay to visualize your raycasts. Check if its even landing in the first place. One note, in 3d raycasts wont hit objects they spawn inside of by default
Quaternion * Vector
To rotate a vector
debug.drawray doesnt work, ill try printing what the raycast hits
that gives an error
it does work, this should indicate to you that something is wrong
because you cant implicity multiply those
Did you copy it directly?
Just telling how these two types can be multiplied
probably..
nor Vector3 * Vector3
Use the correct values
I didn't, I know they can't be
Physics.Raycast(transform.position, -transform.up, 0.5f, groundLayer) how would i get the raycasthit for this?
riight true
Check the docs, theres an overload that gives you the hit as an out parameter
i did check the docs but i cant find the info im looking for
still no rotation.
out? ill try that
thanks
Scroll down on the docs page
ohhh i found it
thats not good
didnt know i needed to scroll down
What have you done
rb.velocity = new Vector3(rb.velocity.x * rb.rotation.x, rb.velocity.y * rb.rotation.y, -moveSpeed * rb.rotation.z); at first
does nothing
rb.velocity = rb.rotation.eulerAngles * moveSpeed;
makes it move at mach 10
i probably need to normalize it actually
Yeah no, the first one doesnt work because rotstion is a Quaternion and wuaternion's xyz components sre not angles, and well it doesnt really make sense anyway
rb.velocity = rb.rotation.eulerAngles.normalized * moveSpeed; makes it go up
Why use Euler angles here?
still, in a straight line
so its not a quaternion
Makes no sense either
you cant multiply a quaternion and a float
but you can a vector3 and a float
what do you suggest then?
What exactly did you type