#💻┃code-beginner
1 messages · Page 165 of 1
how can I make my character NOT to move Diagonally (I use GetAxisRaw)
check which one is higher set the other to zero
yeah, I did that but the problem is that when setting an IDLE Animation (if movement vector == 0) everytime I switch from moving upwards to downwards or to the right and then left the IDLE Animation triggers
if (_xvalue == 1 || _xvalue == -1)
{
_yvalue = 0;
}
else if (_yvalue == 1 || _yvalue == -1)
{
_xvalue = 0;
}
this is my code
(between _xvalue and _xvalue there is an "or"
and the same with yvalue
!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.
hey guys, just wondering is Network ID in a network behaviour always the ID of the owner of said object?
no it's the network id of the object itself
hi, im not really sure which channel to ask this in but im struggling with my code inheriting from an interface after inheriting from monobehaviour
interfaces are implemented not inherited
show your code and the problem you're having
im just trying to make a save/load system and theres no errors on visual studio but on unity it says i can't have multiple base classes
Show the error in Unity
Also you should have errirs in VS since you didn't actually implement the interface
my guess would be you have another script
and you're defining class iData in it
the interface methods have default implementations so they don't actually need to be implemented
ohh yes
yeah they shouldn't have that
it should just be void LoadData(GameData data); for example
ohh okay thank you
Looking for some project guidance.
I have a Unity Windows build that is connected to several microcontrollers over serial ports. I would like other devices (PCs, tablets, phones) on the same local network to be able to access a simple UI to see some variables states and send commands to the main application.
My thought was to have my main application, on startup, deploy a locally hosted Webgl build of an application containing said UI.
Given how simple this should be (I hope), what path would you recommend for handling the networking? Am I on the right path regarding the locally hosted Webgl build? If I ever wanted to access the UI from a different network, how could that be accomplished?
Thanks in advance for any pointers.
Having an issue with the C# Dev Kit, the error is below but it seems I just dont have the right SDK version, my issue is that I can't find documentation anywhere on what version I need, where could I find this at?
The current workspace is using a new version of .NET SDK '8.0.101', which is not supported by current .NET runtime used by the extension. Some functions may not work correctly. This may happen when global.json is changed, or new SDK installation after the workspace is opened. Reloading the workspace may fix the problem.
Where do you see that error?
"locally hosted WebGL build" doesn't make sense in the context of networking. Maybe you mean a locally hosted server build? And WebGL client builds that connect to it on each of the connected devices?
It pops up in the bottom right as a little box whenever I launch VSC
Follow the ide co fig guide:
!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
Thanks!
I'm kind of at the "don't know what I don't know" stage here, but yes I believe that is what I'm after. so I guess I need my main application to host a server for the Webgl clients to connect to it, but I think I also need a (separate?) server so that my devices on the network can open the webgl application. Or am I getting things mixed up
Unity WebGL build creates a standalone app that can run locally. It's just that it is usually hosted on a static website to be downloaded and run by a user. It can distributed in any other way too.
So, if you want to distribute it via a link(i.e. just open a link in a browser to launch a client), then yeah, you'd need to host the WebGL build somewhere in a addition to your actual app server.
For what I'm trying to accomplish (simple UI on other devices providing I/O to the main application), is this a reasonable path forward? Alternative, easier suggestions?
Yes, but if that's all you need, then maybe a simple web app(node js, python, c# blazor or asp) would be more appropriate.
Appreciate it. I already have the UI created within Unity, so part of me prefers the idea of figuring out the webgl angle. Plus I have zero webdev experience. But yeah, it does seem like the more logical path.
How can I reference a sub class in a script?
Same as a non sub class.
Can you show a simple example please?
[SerializeField] private SubClass subClassInstance;
or
public SubClass subClassInstance;
The latter one is a bad practice that I recommend to avoid.
I did that. It doesn't show up in inspector? @teal viper
Is the class serializable?
That means it's not serializable or derived from UnityEngine.Object.
Or you have compile errors
Debug.Log(other.gameObject.layer);
if(other.gameObject.layer == 7){
HealthPoints = HealthPoints - 1;
Debug.Log("Zombie HealthPoints: " + HealthPoints);
}
else if(other.gameObject.layer == 6){
speed = 0f;
}
else{
speed = 10f;
Debug.Log("skibbidi");
}
}```
hi, why is my speed not turning to 10 even when the if statements are not true?
Do you get your log
nope
Then that code never runs
yeah but why?
is it indentation or smth
theres nothing else that changes speed either
This object is never colliding with an object on a layer other than 6 or 7
I forgot that, I'll try. Thank you!
Would it be best to have a script for Player and a script for Sword, or to handle both in one script?
if(Physics.Raycast(
new Vector3(mouse.position.value.x, mouse.position.value.y, -5),
Vector3.forward,
out RaycastHit hitInfo,
10))
{
// do stuff
}
```Hey, is this raycast going to detect my collider even if it's a 2D collider?
nope
they're completely different physics engines
Okay, should I then put a 3D box collider on my flat object? 
depends what you're doing, or use 2D raycast?
3d colliders on sprite is normal, unity is 3D anyway
Well, I wanted to but the thing is I want to raycast perpendicularly to the plane
And I don't see an option to raycast from the camera perspective through the plane to get where the player is clicking (raycasting)
You want Physics2D.GetRayIntersection and Camera.ScreenPointToRay
Camera.ScreenPointToRay
Will that raycast from the cursor? Or always from the center of the camera?
It uses any screen position you give it
Use it with the mouse position if you want it where the mouse is
Okay, quick testing and I almost got it, I did a mistake by taking mouse x and y coords instead of that camera screen point, thanks a lot!
One of the basic princples of OOP is single responsibility principle. Applied to C# and unity it means that one script should be responsible for one functionality alone.
That is if you're interested in writing good code.
For now I'm more concerned about writing working code 😅
Well, then it doesn't matter much. Although good code can lead to a working code faster or to a proper working code, that is more resilient to bugs.
True but a novice like me won't be able to write good code yet hahaha
one day though
Good point
Ray a = Camera.main.ScreenPointToRay(new(mouse.position.value.x, mouse.position.value.y));
RaycastHit2D hitInfo = Physics2D.GetRayIntersection(a, 10);
if(hitInfo.collider.gameObject.CompareTag("Card"))
{
// ...
}
```Great, this piece of code works for me, thanks again! 
With box collider 3D it also worked earlier but this works for a 2D box collider
Very well, your advice has been heeded
private int waittime = 5000;
private int eatwaittime = 10000;
private float eatdelay;
private float delay;
public float SunflowerHealth = 5;
public GameObject SunPrefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
delay++;
eatdelay++;
if(delay>=waittime){
Instantiate(SunPrefab, transform.position,SunPrefab.transform.rotation);
delay = 0;
}
if(SunflowerHealth<= 0){
Destroy(gameObject);
}
}
void OnCollisionStay(Collision other){
Debug.Log("Collision happened");
if(other.gameObject.layer == 3){
if(eatdelay>=eatwaittime){
SunflowerHealth--;
Debug.Log("monkey");
eatdelay = 0f;
}
}
}
}``` is there any reason why my eatdelay doesnt work???????
in oncollisionstay
Why are your numbers so large? waittime is 5000 seconds?
cuz its per tick and updated in update
Also, you're adding to delay and eatdelay without using deltaTime . . .
Unless you have fixed frame rate in the game
You should work using time, not frames . . .
yeah idk how to use time, ive used frames so far
i thought the only way to use time was enumerating
If someone lags, it's game over. All their values are f!@#ed . . .
10000 frames on 60 fps is around 166 sec, so around 3 minutes.
So, perhaps, you just didn't wait enough
so how to i use deltatime?
You should add or multiply values in Update by deltaTime . . .
and deltatime is real time right
the timer also needs to be a float then
It's the time between the frames.
I think you should go do some basics learning.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
No, it's the time taken between the last frame and the current frame . . .
oh okay
and my delay counters should be multiplied by deltatime?
and how would i know how much deltat time is
Technically, an average between the previous frames, and yada, yada, yada. . .
It's not an average. it's actually the time passed from the last frame.
No, deltaTime is added or subtracted from delay (depends if you're counting up or down) . . .
Yeah, but there's a bit more to it than that. That's the simple way to explain it . . .
eatdelay = eatdelay + deltatime;```
As dlich mentioned, I'd watch a quick tutorial explaining how to use deltaTime . . .
okay
It's crucial when changing values in Update . . .
so im making a mc clone and have a script set up for basic chunk spawning the world generation with a simple grass, dirt, and stone blocks, for some reason im getting a layer of nothing under my grass blocks and above the dirt blocks, if i share my generation script could someone help out? this is just for a fun lil side project with a friend
You should definitely share code.
What is supposed to be where the "layer of nothing" is?
its supposed to be grass/ random 1-2 blocks of dirt/ then the rest stone, fairly simple idk why its buggin
!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.
Well, if there's an empty layer, it probably enters the else block that doesn't spawn anything.
If I assume that there are more problems(like missing reference), then there are more possible causes.
Use the debugger to debug that code.
OnDIsable is the last thing that gets called if either the script or the gameobject its on is deactivated right?
Yep
Unless you call something else in the script.
and im guessing OnEnable is the polar opposite to that?
activated state only affects some unity callbacks.
OnEnable can be called in the middle between awake and start I think.
But if awake and start have already been called then yes. OnEnable will be first
https://pastebin.com/D7XJnxbu
https://pastebin.com/Y3cdv7xu
these r my camera and moment scripts can anyone tell me why my camera is also rotating when i press a and d
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.
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.
these r my configs
ping me on reply
Is anyone able to help me figure out why I am getting GC Alloc from my camera? I only have one camera and am getting GC Alloc every frame
Probably because your vCamera follows the rb and you rotate it with A and D
i did the same thing in my last project but it was working prefectly
Line 24 of the camera movement script rotates the camera relative to the "Horizontal" axis which also includes a and d.
oo
okk
let me
try
Assuming orientation is the camera object
orientation is a child of the rotating body
Is it the camera object?
no
Does it allocate in a build as well?
What is the move script attached to?
I'm not sure how to use profiler using the build, im a bit new to that
Time to learn then. Pretty sure it's covered in the profiler manual.
Line 23 rotates the object with the script (camera script). Was that what you wanted?
its like a free cam
like in rpgs
It rotates the object with the script attached
line 23?
transform.rotation = Quaternion.Euler(xRotation,yRotation,0);
doesn't it rotate the object its attached to?
That's what I said
ya so thats what i want
If it's attached to the camera it'll rotate the camera
So a and d will rotate the camera
i want to move in any direction irrespective of the camera
It doesn't move, it rotates
So you found the problem
Then I don't think you got the right vcam body. Pretty sure the one you have selected rotates with the followed object.
see i removed the 24th line which rotated the orientation
Your camera rotates because of that line (23)
yea but i want it to rotate
why does my camera also rotate
and yea this makes sense cuz i follow the object which rotates so maybe when i rotate the object the camera follows that as well is there a way to change that?
It is.
why did it work in my last project it still does even rn 😭
Configure your vcam properly.
Might want to look at cinemachine tutorials
wait let me show u my last project
You probably want to use free view camera(or whatever it was called) instead of a plain vcam.
Also, expanding the "body" drop-down might give more clues.
and the scripts were the same
okk let me see
Unless it's a child of the object with the movement script, have referenced the wrong object or have attached the movement script to the camera object as well.. I'm not sure.
Did you inspect the body properties of the vcam..?
yes
and..?
i couldnt find anything like i get it that cuz the should transfom is rotating the camera rotates with it where as in the other project it doesnt
Does "following" refer to orientation as well?
so i m kinda confused
yes
Or does it just move towards the object?
It does nothing unless the body or aim are set to refer to it afaik
If it stays directly behind the object that's being followed, it'll rotate with the object?
Depends entirely on the Aim
wait
i found a difference
the aim was set to
do nothing
in the other project
let me try now
still doesnt work it rotates with the rigidbody 😭
Show us the inspector for your capsule.
The issue is definitely with your vcam setup
yea
Maybe you should share the details of the vcam with it's properties expanded, as you never did that...
And in the orher project?
So you've got any other script in any other object that we should be aware of?
https://pastebin.com/7Pu0QW69
https://pastebin.com/PiNa6NZM
these r the scripts used in other project
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.
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'm referring to this project with the capsule
nope
So no other objects have any other scripts attached to them?
Okay. Can you record a video of what happens at runtime with the vcam selected and visible in the inspector?
I'm referring to objects with script components attached to them.
sure wait
yes thats all
You don't have the camera script attached to some other object referencing the vcam, do you?
not quite understanding this. i want a sound to play, every time a button is selected. right now i have this and its not working
no
well i took this script from https://www.youtube.com/watch?v=f473C43s8nE&t=288s and as of now i felt like i dont need that line so i removed it from my current project cuz i dont want the shoulder to rotate
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
i have done that
no wait apparently i did that
and it bugged everthing
wait let me show u
Define bugged?
If it can't be described with words then a video may be fine but most of these could probably just be better described.. we'll likely not even know what we're looking at.
when i do that my mouse stop rotating the cam as well
I think the answer to your issue has to do with the Shoulder object and the references to it. Can you confirm if these 2 reference the same object?
And also take a screenshot of it's position/orientation in both of the projects?
okk
Does it throw an error? Otherwise, is the method executred at all?
So, simply by deducing we have confirmed that the line allows you to rotate by both mouse y and key (a and d). Did you perhaps change anything inside the input manager?
i m using old input system
Why is it offsetted like that in the left project?
on the right it only has offset on the y axis
no spfic reason in one case i just changed that from the x y z damping in the virtual cam 3rd person follow
Make it the same as in the other project and test
okk
well
tbh
i think i should just make my own camera script
that will fix everthing
What makes you think so?
I'd say that naming conventions are wrong, but I don't think that's what you're looking for..?
well I am trying to make the button change color on click
Why have isPressed at all?
You already have GetMouseButtonDown
a problem i have that i've accepted
I have it there cause i thought one wasn't working
no idea why you query your input in update loop but not doing in on mouse down
Can we actually get the details on what you're trying to fix?
Or is it a quiz?
nah, just a learning kind of thing. I want to see if i can change the color of another game object from this one when i click it. I can do i on that object itself but i want to see if i can do it from here cause something i want to implement might depend on it
So, what is not working..?
well the color does not change
Great. You should've started the very first message from that sentence, instead of expecting other people to guess.
And you've already been answered by several people about possible causes.
well i originally went through most of those but "why you query your input in update loop but not doing in on mouse down" is something i might not have tried
Its still not working
could it be an attaching issue?
Start from sharing more details. A screenshot of the object that has the script, the latest code, debugging attempts so far.
this is how I have attached
have you tried debug.log if the on mouse down is executed
you should try first and read the api description
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
Your desired color is fully transparent btw. Is that what you want?
the area is pretty dark, i've tested it with something else i can see it
I have noticed it does not send any logs
so the button is just not getting clicked
is it possible to detect collisions between a collider that has isTrigger enabled and one that doesnt?
Where did you put the debug logs?
in on mouse down
Yes, if one of them has a rigidbody.
Then it is not being called indeed.
thanks. can the rigidbody be on either or specifically the istrigger one?
Might want to check the docs to see how it's supposed to work:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
It can be on either.
ok last question: would I use oncollision or ontrigger?
Refer to the manual for more info:
https://docs.unity3d.com/Manual/collider-types-interaction.html
thanks
Whichever suits you.
Depends on what object you want to receive the message on.
I think it makes more sense to have the rigidbody on the character and the trigger on the object to trigger
can just use IsTrigger on anything anywhere if you don't care for collisional events
!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.
hi
I wanted to add controls settings in game, and make player able to move buttons, i wrote script (with help of chatGPT tbh), and it works, but position is wrong (see video), can someone help?
https://hatebin.com/bmyoquyqpt
(lines 29 and 30 are not used)
couldnt you just do
transform.position = Input.mousePosition;
it works with the new input system, not sure with the old one but try it
of course, sometimes simple solutions are the best
Greetings, I have small issue, my IDE debugger evaluates a condition true, but in the code debugging, the if is skipped as if it went false.
else if (eventData.button == PointerEventData.InputButton.Left && toggleDrawUI.isOn)
this is the code, I pasted same code to my watched variables to IDE
its true
yet it never gets into the nested part of code inside the if
and no, it is not caught by previous else ifs
is this whole thing eventData.button == PointerEventData.InputButton.Left && toggleDrawUI.isOn true
yes
well IDE says it is and from what I can see I clicked left button and the toggle is on
show the screenshot?
sure one sec, have to get to the program state
well
now it suddenly works
but until I added a new line inside the if condition, it didnt
maybe some compilation bug idk
yup now it works after I added one new line to the nested brackets of if
Could it be that unity somehow catched old code or something?
hi, im facing a problem using raycast as when i do the raycast on a object with the rigidbody it works and but when i make the rigid body is kinametic or freeze loc and rot it dont and also trigger dont work is there any workaround through which i can use raycast and also make the object stay in air and not acting to player?
show the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace InteractorSystem
{
public class InteractionSystem : MonoBehaviour
{
[SerializeField] Transform orientation;
public bool canInteract = true;
private void Update()
{
if(Input.GetKeyDown(KeyCode.E) && canInteract)
{
RaycastHit hit;
if(Physics.Raycast(transform.position + (orientation.forward), orientation.forward, out hit,100))
{
Debug.Log("Debug");
Interactor interactObject = hit.collider.gameObject.GetComponent<Interactor>();
if (interactObject != null)
{
interactObject.OnInteract();
canInteract = false;
}
}
}
}
}
}
why transform.position + (orientation.forward) as ray origin?
i thought its colliding with the player so i started the location one vector
you could use layers for that
3d raycasts by default do not hit the object they spawn inside of. Also I have no clue what your question is asking tbh, rigidbody has nothing to do with raycast
Use debug.drawray to visualize your raycasts
okay, its happening again 😐
you see the condition is true but on next step it just goes after the if
I am now optimising the ifs anyway cause its a mess I did just to test if it works at all
got the problem as i am taking the players transform.forward so its not hitting the object
it works now
What button were you pressing to go to the next step? You may have just been pressing the wrong thing and it hitting the next breakpoint. If you put a debug.log inside the if statement does it show up in the unity console?
well yes
but then the object would instantiate
if I skipped the code in debug but it happened
I usually use step over btw
Sorry for bothering you guys
this just seem like some non deterministic s*it to me 😄
Step into will execute line by line I believe, I might be misremembering the exact buttons, not on my pc atm.
If I wanted to make a text sprite in 2D, how would I make one without using canvas?
actually step over does, I debugged many times line by line
worst thing is that when I changed a line in the code, it worked, and now it doesnt again, havent touched the IFs tho
seems like the file is somewhat corrupted or something
Step over will skip over functions at least, not entirely sure what happening in your case tbh. Maybe try recreating it on a different file, could just be a bug.
Also you dont need to use Instantiate for a new gameobject. Using the constructor will spawn the object in your world
You might be spawning 2 objects because of it
Instantiate(new GameObject()) definitely spawns two objects
Im talking about the ctor for game object
One will spawn with no parent, then you instantiate another under the parent
One of them won't have a parent
new GameObject()
You just use the constructor, remove the instantiate function. Or use instantiate and make a prerab
(I always used prefabs to spawn objects until now)
I think you should use a prefab here idk why you're not
Also I don't understand how you're doing GetComponent<Meshrenderer>() on it since it clearly won't have one
it does have one
Doesn't that cause an NRE?
How could it have one? Didn't you just create an empty object?
when its so simple GameObj
Without a renderer?
wanted to just generate it
nope, it creates an object with meshfilter and meshrenderer
How?
its made via [RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
I thought RequireComponent only works when creating the object in the editor
Oh actually I just checked the documentation
It does work with AddComponent
That's a new one for me, TIL. I'd still just use a prefab
Does anyone know what I can do to fix this? I've restarted the game, and checked the prefab, but i can't figure out how to fix it
yup, its simply that I wanted to learn if I can make such simple GameObj from scratch
You have another copy of the script where it's not assigned
Oh. How does that work?
Wdym? Very simple. Your script can be attached to many different objects
Theres no second version here
In the scene
Not another cs code file. Just another object with the same script attached
there is only one object in this scene that has that script
- that you remember
Can you search your scene for the script
how?
Search in the hierarchy window's search box
It's also possible you're referencing the prefab somewhere and trying to call a function on the prefab itself
t:chicken in the hierarchy search
don't even need to the t: unless you have objects with the same name too 😄
📃 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.
I manually went through all the objects to check for the script
Fills me with confidence
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Click on the error and show the full stack trace
Doesn't this GameObject fellowpoultry = GameObject.FindGameObjectWithTag("chicken"); imply there are multiple chickens in the scene?
My guess you are spawning chickens in at runtime
This is the code I use for all chickens, throughout the different scenes
And the prefab doesn't have the animator assigned
yes it does
(particle system, but yes too)
Also that code makes little sense since it will likely just find itself
both
Show your chicken prefab
It's my first attempt to actually make something that's not flappy bird, the codes a bit wierd
I bet it's not assigned on the prefab especially since it was an override in the scene
This is the script component on the prefab
also imnot spawning any other chickens in this scene
you don't use chicken 2?
they spawn in a different scene
what?
Seems like you have a number of chicken prefabs
I would check them all, and check your assumptions about what's spawning when
There is a second prefab that is a diffenent colour, with some slightly different variables
and presumably bebe1 and 2 are also chickens
the second chicken prefab also has everything assigned
bebe1&2 both have it assigned
At this point, break out the debugger
How do I do that?
one thing we haven't seen. The chicken script from the scene
apparently it's fine, and they seem adamant about things
hmmm, heard that before
Like the inspector fo rthe component? i sent that at the start
in the first message
where?
Here, theres three images attached
Damn, discord hides the other two from me
Yeah same, its a bit odd
I only see one
You gotta click on it and hit the arrow
Damn I hate that 'feature'
Ok, the only think I can think of is that there are multiple chicken scripts on the prefab or scene object
https://pastebin.com/m7N8B3SX is there any specific reason why the camera doest look up down just left right?
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.
Just a note to not scale mouse delta by deltaTime
You likely screwed up the hierarchy somehow. Either put the script on the wrong object or the camera or something
maybe cuz this script is on the virtual cam which follows the player?
Show the hierarchy and which components are on which objects
I have script to make the character move but the character will net move
how do I fix this
and it has a animation
You should configure your !ide before proceeding
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
i think u need to add a float speed and then multiply that with movement direction
Certainly is a problem that the axes are named differently; presumably there's warnings in the console. However, it needs to be addressed after the IDE is configured
I configured my ide do I just have to add a float speed now
Walk, Run, Jump and Sprint! Easily customizable!
A very simple player movement script that will get you started on your 3d project. Code is pinned in comments.
3D, First person (easy change to third person).
Sub for more :)
Is this a good script to use
after I configured my ide
Look at the console window and address any errors/warnings in it, because this certainly isn't correct
it gave this error
Personally as a beginner myself I prefer rigid body instead of character controller
what is the diffrent between rigid body and character controller ?
Rigid body is easier to use as u can use the unity Phys system and ig in character controller u have to do a lot by yourself like even for gravity u need to add a force pushing yourself down
how do I do that then
You're getting way ahead of yourself
Fix your basic errors first before overhauling your whole system
The error tells you exactly what's wrong.Vertx pointed you at the spot. Compare what you have there with the tutorial
Did u config your vs code or whatever u use?
no
Well that would help
And also just cross check the spelling vertx pointed from the video
this is the video that I copying from
Ya so do u see the difference?
You should consider writing your code the same as the video
I am trying to do that
try harder
Do u see it now?
yes
🔥🔥🔥
I did it correctly but the player will still won't move the animation kinda makes him move
Send your code
anyway I can change these rules? I want it to be _ and not camelCase
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
transform.Translate(movementDirection * speed * Time.deltaTime);
}
}
Did u add a value to speed from unity inspector?
ok I set the speed the problem is just the animation won't stay in place
how do I fix that
Did u download the animation from mixamo?
yes
Export you Blender Character in Unity Engine with the help of Mixamo for Humanoid type characters.
Export Character and Animation from Blender to Unity:
https://www.youtube.com/watch?v=UQGMsL8jXRI
What is NLA Editor in Blender and How to Use it:
https://www.youtube.com/watch?v=ex8CoSKtNK4
My Environment Art Tutorials:
Medieval House Created in...
There is an option "in place" u have to check it before downloading
Select the animation 1st
Hey guys, I'm following a tutorial online and made two scripts. There are no errors within the Visual Code and I'm like 99,99% sure I don't have any typo there or anything, I checked the code so many times that my head hurts now lol. Unity is giving me:
Assets\Scripts\Hit Components\HitBox.cs(9,23): error CS0246: The type or namespace name 'HitData' could not be found (are you missing a using directive or an assembly reference?)
But in the code itself HitData is properly defined and even Visual Studio knows where it is defined and where it is used etc. (I tried typing HitData with a typo just to test this and instantly I get the error in Visual Code, but there are no errors otherwise) So it seems like Unity can't communicate properly with the script files for some reason?
Here is the HurtBox.cs that defines public struct HitData: https://hastebin.com/share/owuquzenoq.csharp
And here is the HitBox.cs that gives the error: https://hastebin.com/share/exatirorih.csharp
I also attach the screenshot of my project folder to see the hierarchy.
Do you get error highlighting and autocomplete in VS Code generally?
I did
It sounds like you do, sorry. You have definitely saved?
there would be a check box of in place
I do, Intellisense is working now etc. if I do anything wrong I can see it, it was quite helpful getting typos right and missing whatnots... But now it thinks the script is fine
ok how do i remove the character
which character? ss
the one that I took a pic of
You could try moving HitData to its own file. Sometimes Unity only sees the MonoBehaviour class
u havent selected the animation
just select the animation
skin doesnt matter
and download it ?
no
check in place 1st
is there any way i can compare this hit with a layer?
ignore the 1st vector3.back parameter
When you say compare, do you mean only check for colliders on a specific layer? Cause if so, yes.
you cannot compare a RayCastHit to a LayerMask, that makes no sense
hmm makes sense
Ah yes, the artof the bodge. I'm almost certain this is the worst possible way to do this but hey. It works.
how do i do it then?
wait
i got it
layerMask = DefaultRaycastLayers
something like this
you compare the Layer of the gameobject you have hit with the Layer ID used to make the LayerMask
Do not duplicate code if you don't need to
wait i m confused
shouldnt something likt this work?
Ok so I'm trying this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HitData : MonoBehaviour
{
public int DamageValue;
public Vector3 HitDirection;
public HitData(int damageValue, Vector3 hitDirection)
{
DamageValue = damageValue;
HitDirection = hitDirection;
}
}```
The problem is, now it is a class and not a struct.. if I try to have a struct with same name as class it doesn't work, but if I rename the class to something else it's basically the same as before, no? When it's a class like this I get "Assets\Scripts\Hit Components\HurtBox.cs(31,32): error CS1729: 'HitData' does not contain a constructor that takes 2 arguments" which I suppose is connected to it now being a class and not a struct.
why are you specifying types in a method call?
which types?
float and int
for the max dist of the ray and all
you do not specify the type in the call only in the method signature
I don't understand why you changed it into a MonoBehaviour. What was the issue if you just copy-pasted the struct as it was?
okk so...
wait
let me try another way
Oh that's what I thought you meant with "sometimes unity only see the monobehaviour class"
dude i dont get it just tell me
how should i compare the hit info with the layer
man, this is basic C# you should know this
void myMethod(int x) { }
...
int a=0;
myMethod(a);
ya i get it but how do i compare hte layer?
I meant that if you have something in addition to the MonoBehaviour class in the same file then it doesn't register the other stuff. Not that everything has to be a MonoBehaviour
how do i get the the layer info after hitting it
https://docs.unity3d.com/ScriptReference/RaycastHit.html
then Collider or transform or rigidbody has a property called "gameobject"
no
does GameObject have a LayerMask property? I dont think so. Go look up the docs instead of just trying random shit
@sonic dome my character does not have a in place option
so I am not sure what to do I thinK I somehow need to put it in place in blender
It worked!! Dude, thank you. Still had one issue that I think I solved in a not so great way lol. Basically when I put the struct to it's own script file, this line (in HurtBox.cs) started giving me error that HitData doesn't have a constructor that takes 2 arguments:
hitbox.Hit(new HitData(_damageAmount, -hit.normal));
so I simply changed it to:
hitbox.Hit(new HitData());
And now it works... But I suppose those two were there for a reason lol and they weren't giving this error when the struct was defined in the same file... Any idea how I could fix this?
Can you show the HitData file you made
where is the constructor? how you define it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct HitData
{
public int DamageValue;
public Vector3 HitDirection;
public HitData(int damageValue, Vector3 hitDirection)
{
DamageValue = damageValue;
HitDirection = hitDirection;
}
}
did you save the script
yes this is saved as HitData.cs
On this line: hitbox.Hit(new HitData()); ctrl-click on HitData and see where it goes
this
hitbox.Hit(new HitData());
should not work. you have no default constructor
why is this code working and not mine
it goes to public struct HitData line in HitData.cs, so it seems to know where it is
Again, you are specifying the parmater type as well as the value. you only need the value
I mean by "work" I mean it's not giving me any errors NOW
struct has a default parameterless constructor
then why is the 1st one working
- 3 is not a layer mask
- You are passing it into the max distance parameter, not the layer mask parameter
- Your syntax is incorrect, no idea why you're trying to perform an equality here
😭 makes sense
do you not see the : that means a parameter NAME, you have a parameter TYPE
oo makes sense my bad g
I just don't understand why the line
hitbox.Hit(new HitData(_damageAmount, -hit.normal));
worked when the struct was defined in the same file, but it didn't when I moved it elsewhere EVEN THOUGH when I click on HitData it goes straight to the new file... And I mean VisualCode wasn't giving me the error it was Unity.. I feel my Unity has some sort of problem knowing where things are
Show the full error message
"Assets\Scripts\Hit Components\HurtBox.cs(31,32): error CS1729: 'HitData' does not contain a constructor that takes 2 arguments"
But I tried to rewrite the line from scratch and it seems to not give any errors now... Maybe it's finally fixed. Thank y'all.
Hi, i need help trying to flip a group of sprite, sorry to repost this here i didnt get help at the 2d tools
A) This is a code channel
B) Do not post photos
https://pastebin.com/mj6V1mAF can anyone tell why my isgrounded is not working?
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.
it doesnt throw an error. when i throw in a debug log, it also doesnt seem to get executed
how can i change a button's text through script?
does anyone know a way to make my character face the direction I last moved to whenever I stop moving it?
A) It makes no sense to do a GroundCheck every Update when you only use the result for one specific key press
B) What happens if the Raycast fails?
no
nice
you are here to learn not to get handouts and be spoonfed
well okk let me see yt tutorials
you would be better off with !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yo, can't seem to get my Particle System working.
This is my script for how I turn on/off the particles:
if(Input.GetKey(KeyCode.LeftShift))
{
accelerating = true;
thrust.Play()
Debug.Log("Started Thrust");
}
else {
accelerating = false;
thrust.Stop();
Debug.Log("Stopped Thrust");
}
The method is called, since I recieve my Debug.Log() messages in the console, but the Particle System doesn't start.
also, the particles works in scene view
I don't see the function that plays particle system in here
Whoops, I pasted the wrong code. The thrust.Play() is in my code.
this in update?
This is in MyInput(), which is called in Update().
so you are calling Play every frame when the key is held down
not what you want I think
So I should only start it once, and then when I release the key I should stop it, right?
yes
Ah, I see. Thank you!
any idea of how I could do this?
use GetKeyDown and GetKeyUp instead of GetKey
Perfect, thanks once again! :)
how do I play an audio clip only when I want to play it ;-;
I've tried a few different methods its always playing as soon as the asset is loaded
turn off play on awake
hello every one
Im starting to program using unity
And i dont understand how does the "do" command work
can someone explain it?
you mean do { } until (condition) ?
yes i think
it is a looping construct which is always guaranteed to execute at least once
How often do you use that Steve?
not often
I've used do like a handful of times
Useful when you need a loop that executes at least once
Only used do-while though
it does have it's uses but they are very rare
how would i add a function to a button, like change the colour of the text, and add audio when you hover over it?
UI.Button component? Add an OnClick event in the inspector, or add it from a script with AddListener if needed
that wont work for Hover
Oh I totally missed the hover part
I think you need to implement the IPointer interfaces
hey steve, can you give me an opinion on my code?
Yeah that
maybe, but you probably wont like it, post it correctly and see !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.
hello, im currently facing a problem with my rigidbody character when move while jump. It jump normal when idle, but floating when moving. Any idea what wrong in my script?
your using velocity and add force, that wont work
You modify the velocity directly in Movement()
One way to solve it is to use AddForce instead of velocity when you are jumping/falling/not grounded
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class CharacterScript : MonoBehaviour
{
public Rigidbody2D CharacterRigidBody;
public float CharacterJumpStrenght = 20;
public float CharacterMoveSpeed = 10;
public int MovementState = 0;
public SpriteRenderer spriteRenderer;
public int JumpsLeft=0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//Inputs
if(Input.GetKeyDown(KeyCode.Space) && JumpsLeft > 0)
{
CharacterRigidBody.velocity = Vector2.up * CharacterJumpStrenght;
JumpsLeft = JumpsLeft - 1;
}
if (Input.GetKeyDown(KeyCode.A))
{
MovementState = -1;
spriteRenderer.flipX = true;
}
if (Input.GetKeyDown(KeyCode.D))
{
MovementState = 1;
spriteRenderer.flipX = false;
}
//Input Stops
if ((Input.GetKeyUp(KeyCode.A) && MovementState== -1) || (Input.GetKeyUp(KeyCode.D) && MovementState == 1))
{
MovementState = 0;
}
//Input Responses
if (MovementState == -1 || MovementState == 1)
{
transform.position = transform.position + (Vector3.right * CharacterMoveSpeed * Time.deltaTime * MovementState);
}
}
//Jump Recharge
private void OnCollisionEnter2D(Collision2D collision)
{
JumpsLeft = 2;
}
}
The code is for character movement
Put it in a paste site, it's too long
See the Large Code Blocks in the bot's message
im using addforce in jump method though
Did you not read the bot message? Specifically the Large Code bit
but velocity in Movement
Yeah but that's just the jump force, I'm talking about the walking force/velocity in your Movement method. spineRigidbody.velocity = ...
Is it ok now?
Currently it will always override your velocity if you are holding movement keys down
should i change the velocity to addforce just like jump?
no @sleek relic
Yes, but only if you are not on the ground
This is just one way to solve it
i see, thank u
You can also have a cooldown/timer that disables walk forces for a short while as you jump
Im confused
read the bot 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.
Large Code Blocks
https://paste.myst.rs/7bcno76s @languid spire
a powerful website for storing and sharing text and code snippets. completely free and open source.
https://gdl.space/raw/ugexofubud
Hello, anyone knows why my character is doing dubble swipe on the left and down animation but not on the right and up one?
Your animation transitions are probably wrong
Or your sprite animations have incorrect frames
You can put the game view and animator window next to each other while playing so you get a better idea of whats going on
Honest opinion
Class name does not need to contain the word Script, we know its a script
Variable names misspelt
Variable name convention not consistent
Empty method
MovementState is not a state
Hard coded value for JumpsLeft
Mixing Transform and Rigidbody movement
Velocity not taking into account existing velocity
Conclusion: Not very good at all
ok thanks
as you can see here it looks exactly the same :/
Looks like it is playing twice every time
I have 0 experience worth it to learn ?
@celest spoke You are using a Bool parameter, use a Trigger instead
Trigger is a bool that gets set to false when it is used
do you mean in my code?
In your code and in the animator
In the animator make attacking a trigger instead of bool
And in code use SetTrigger instead of SetBool
The problem currently is that attacking is true for at least two frames so the transition gets triggered twice
should i remove true and false in my code aswell? Because now i get error that says "SetTrigger does not take 2 arguments"
Yes
You use SetTrigger to set it to true and ResetTrigger if you ever need to cancel it
well now nothing is working
You probably don't need to ResetTrigger here
my character is flying around and cant use attacks
Did you change it to a trigger in the animator?
And did you reassign the transition conditions to use that trigger (in case they disappeared)
You might want to get rid of the condition and create it again
I distinctly remember having a problem when I changed a parameter from float to bool
The condition turned into a boolean condition set to "true"
but the condition didn't work
something was stuck behind the scenes
this was on a VRChat avatar, so it was a reasonably old version of unity
so now its all working again but now i do dubble to the right and up, and triple to the left and down haha
insted of single and dubble
📃 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.
animator.SetTrigger("attacking");
currentState = PlayerState.attack;
yield return null;
animator.SetTrigger("attacking");```
You are indeed setting the trigger twice
wait wait i think i found the problem
I guess you used to set the bool to false where you now have the second SetTrigger
You don't need that, triggers go false automatically
so should i remove the second trigger?
Also is there a reason you are using GetMouseButtonUp instead of GetMouseButtonDown?
Attacking on mouse release is a bit weird
i just followed a tutorial, did exactly what the dude told me to and now its not working like his is
That would assume you didn't do it exactly like they did
But if you want to stick to that claim and get added to the counter, then show your code and what tutorial you're using.
(If you haven't fixed it)
the only difference i did was that he used spacebar for attack and i used left click
i just dont see how right and up is correct but down and left is wrong
@frosty hound may I please dm you ?
No
What part of "ask your question" do you not understand?
Neither can anyone here without you showing your code
You have asked to ask your question multiple times now
Just ask it.
but i have pasted my code multiple times https://gdl.space/raw/durubuperi
show your current code -- you've made changes since you last shared it, right?
Even if you think it's just one line, it's really important to make sure we're all seeing the same thing
Also what tutorial this is from?
I want to share something with someone with a unity experience I want the question to be confidential
good luck with that, then
no, nobody is going to "steal" your game idea
Thanks
But why this server don’t like to talk in dms this is kinda weird am not gonna e kid nap anyone
https://gdl.space/raw/revocifivo
https://www.youtube.com/watch?v=p6Klz_NZpEQ&list=PL4vbr3u7UKWp0iM1WIfRjCDTI03u43Zfu&index=13
here you go
Longer video today, so sorry for that in advance. Today we add simple sword attack animations.
Modified Sprite: https://drive.google.com/file/d/1Jg_llkej7GcUWcP0c7sE72jvV55MJ4N7/view?usp=sharing
Tiled: https://thorbjorn.itch.io/tiled
Tiled2Unity: http://www.seanba.com/tiled2unity
Art Assets: https://opengameart.org/content/zelda-like-tile...
People don't want to commit to helping you without even knowing what the question is about
The question is about unity
because I already have enough spam in my message requests
Ask the goddamn question or stop bothering us.
I'm certain it's not as "confidential" as you think it is
Not a great tutorial at all. Using booleans for what should be a trigger, moving the rigidbody in update..
The top comment has a bunch of fixes for it too
there is no fixes for the problem that i have what i can see
What's the current problem?
and i find the tutorial fun and interesting as a new person to this but w/e
the problem is that when i attack to the right and up i hit 1 time with my sword, and when i attack left and down it attacks 2 times. I only want it to attack 1 time no matter the direction
It's probably fun and interesting. But all the comments are about fixing stuff in the tutorial
Compare your right/up animation transitions to the left/down transitions
Sounds like they are different
And disable loop on the animation clips
removing the loop makes it so that i do 1 stab in every direction so that works, however its not making the full animation so it looks funny
Hey guys, anyone have experience with raycasts?
mouse.z = 10;
Ray ray = Camera.main.ScreenPointToRay(mouse);
if (Physics.Raycast(ray, out RaycastHit hit, 10)) {
}
have this tiny code and am clicking on an object with mesh, yet having no hits (I removed the internals of if for simplicity)
My Physics Raycaster object is on my main camera and set to the layer the object I want to hit is in
any ideas what might cause it?
Keep the loop disabled and check that the animation transition from Attack to Idle is correct. Sounds like it is exiting too early
This definitely seems more like an #🏃┃animation problem at this point
Ok i dont know how i fixed it but now everything is working as it should
but thanks for all the help ❤️
there's no "Physics Raycaster" component
oh, you mean you named this thing "Physics Raycaster"?
please show us the entire script
don't remove anything from your code
i can handle reading more lines, but I can't deal with not seeing code that could be causing your problem
Could arrays be used to make two variable types related (as in, a string for AmmoType and an integer for AmmoMaxCap)
lines inside IF which is never triggered cannot affect the result
That would be a dictionary. It uses a key and value pair . . .
This has nothing to do with using Physics.Raycast
I am not sure I am using it either, but I recall it enabled the raycasts globally
Please share the entire script.
I need to see what you're actually doing. Please humor me.
Vector3 mouse = Input.mousePosition;
mouse.z = 10;
Ray ray = Camera.main.ScreenPointToRay(mouse);
if (Physics.Raycast(ray, out RaycastHit hit, 10)) {
Debug.Log("x");
}```
amazingly game changing
That's not the entire script. That's a few lines.
How do you know that your raycast is even running?
I did Debug.DrawRay
well, you didn't show me, so I couldn't know (:
the other parts of the script has nothing to do with this
and cannot affect it in any way
in debugging I can also see the origin and direction of the ray
why are you fighting with me? i'm trying to help you.
I am not fighting you, but there is simply nothing else
Share the entire script, including your Debug.DrawRay code. I need to see exactly what is going on.
So the code above is everything in your script?
I removed the debug since
If you knew what was and wasn't relevant, you'd be able to solve your problem
you put what on your camera?
yes, the method definition starts above it
OnPointerClick of IPointerClickHandler
Debug.DrawRay?
Why don't you just share the code instead of making us play a game of 20 questions?
okay
full code
if (eventData.button == PointerEventData.InputButton.Right) {
if (drawing != null) { drawing.IsExtending = false; toggleDrawUI.isOn = false; drawing = null; }
Vector3 mouse = Input.mousePosition;
mouse.z = 10;
Ray ray = Camera.main.ScreenPointToRay(mouse);
if (Physics.Raycast(ray, out RaycastHit hit, 10)) {
Debug.Log("x");
}
}
}
This must be a joke. We've asked you to share the full script over and over and you keep sending us snippets.
Why do you need a raycast here?
You are already using OnPointerClick which raycasts to the UI
I see nothing here that proves this code is even running
This code will run when a UI element is clicked on, and will try to do a raycast against physics objects in the scene
We don't even know if it implements the interface
we don't know much of anything!
🤷♂️
Full script then
public class ClickController : MonoBehaviour, IPointerClickHandler, IPointerMoveHandler {
public void OnPointerClick(PointerEventData eventData) {
if (eventData.button == PointerEventData.InputButton.Right) {
if (drawing != null) { drawing.IsExtending = false; toggleDrawUI.isOn = false; drawing = null; }
Vector3 mouse = Input.mousePosition;
mouse.z = 10;
Ray ray = Camera.main.ScreenPointToRay(mouse);
if (Physics.Raycast(ray, out RaycastHit hit, 10)) {
Debug.Log("x");
}
}
}
public void OnPointerMove(PointerEventData eventData) {
//Debug.Log("<color=#" + ColorUtility.ToHtmlStringRGB(GetColour(eventData.pointerCurrentRaycast, transform.parent)) + ">PIXEL</color>");
}}
well I told you here havent I #💻┃code-beginner message
Great.
Now, prove that OnPointerClick is actually running by logging something inside of it.
it is
again, we're playing 20 Questions here
But you couldv'e left the IPoinerClickHandler out by accident
Does your scene have an EventSystem component?
No it wouldn't
no, you would get no error if you forgot to derive from the interface type
and the method wouldn't be called
Yes I have eventsystem
You don't prove this in the code you sent.
You must trust me then
remember that:
- we don't know what you know
- we can't see your screen
Fen is trying to teach you how to debug
I know how to debug
I'm trying to get you to communicate properly.
Then where's your log to prove it is running?
It's going in circles for a reason.
I dont need log for such simple things
Then how do you know this method is even running? You said "it is" and stopped there.
What if it isn't?
I used Debug.DrawRay for debuging if the ray hits the item before
IDE debugging
You didn't use it anywhere in that code.
Okay, great, so you set a breakpoint and had the debugger pause inside of OnPointerClick?
Good. That's what I was looking for.
skip this gaslighting please
Debug.DrawRay(ray.origin, ray.direction * 20, Color.white);```
I also used this for camera update
So I could see the ray is actually going through the item
Not sure why are you acting so weird
You should trust someone's words more next time imo
Don't expect us to know your experience level. We are asking reassuring questions for a reason, it's a beginner channel
While calling it 'gaslighting'
Do you have any idea of the number of people who come here and swear black is white?
Search this channel for posts by me containing the words "The counter" and you'll see why we don't take anything people post here at face value without evidence. Sorry that you got caught up in it but sometimes when all the signs point to one problem but someone swears up and down it's not the case, the simple solution is that person is mistaken.
does somebody know how to make my character face the way it was moving before it stops
What kinda game, 2D platformer, 3D shooter?
Does the object have a 3D collider?
Does it log x?
sorry?
And is < 10 units away from the camera? I see you used 20 as a distance in the DrawRay, but 10 in the raycast itself
nope, thats the issue
it wont detect the hit
yes, camera is, one sec
So if you get no logs, there's a possibility the code isn't running
I only just arrived but from some scrolling, it seems you're having issues detecting something with a Raycast. Remember that mesh colliders are one-sided. If this mesh's normals are backwards it wouldn't detect a ray unless it struck the inside of a polygon
Then you probably want to tell the animator which way you are moving. Make parameters for MoveX and MoveY directions in the animator and control your sprites/animations with that
They did a breakpoint in the function and it's running
its procedurally generated 2D mesh actually
and I can see it so the normals should be fine
I wasn't aware, alright 👌
otherwise they would point towards the side and I wont be able to see them
Try with a primitive collider for testing (Sphere/Box/Capsule)
good idea
2D mesh with a 3D collider, right?
Are you using the 2d variant?
well its 3D mesh but the vertices are all on a plane
so I used 3D mesh collider too
Can you show your mesh generation code?
technically I added the 3D Raycaster just because I did not know how to make it 2D like my other items
Yeah, I think it's the fact that a 2D object has no volume so the mesh basically can't be hit from any direction except straight on. I'm not sure what orientation anything is at but if the ray comes at it from the side it's not gonna strike anything.
trianglesList.Clear();
Vector3 endPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
endPoint = transform.InverseTransformPoint(endPoint);
endPoint.z = transform.position.z;
float stemWidth = Mathf.Log(Camera.main.orthographicSize + 100) - 4.557f;
float distance = Vector3.Distance(transform.position, endPoint);
Vector3 perpendicularVector = new(-endPoint.normalized.y, endPoint.normalized.x, 0f);
Vector3 normalVector = 0.3f * distance * new Vector3(-endPoint.normalized.x, -endPoint.normalized.y, 0f);
verticesList.Add(perpendicularVector * stemWidth);
verticesList.Add(-perpendicularVector * stemWidth);
verticesList.Add(endPoint + (perpendicularVector * stemWidth) + normalVector);
verticesList.Add(endPoint - (perpendicularVector * stemWidth) + normalVector);
trianglesList.Add(0);
trianglesList.Add(1);
trianglesList.Add(3);
trianglesList.Add(0);
trianglesList.Add(3);
trianglesList.Add(2);
verticesList.Add(endPoint + (2 * stemWidth * perpendicularVector) + normalVector);
verticesList.Add(endPoint - (2 * stemWidth * perpendicularVector) + normalVector);
verticesList.Add(endPoint);
trianglesList.Add(4);
trianglesList.Add(6);
trianglesList.Add(5);
for (int j = 0; j < verticesList.Count; j++) {
Vector3 n = new(verticesList[j].x, verticesList[j].y, transform.position.z);
verticesList[j] = n;
}
mesh.vertices = verticesList.ToArray();
mesh.triangles = trianglesList.ToArray();```
its simple arrow
but I wanted more objects in the future
Try calling mesh.RecalculateNormals after all that
And maybe some of the other RecalculateX methods, I don't remember which ones are necessary
If you look at the mesh from behind, you can't see the faces right?
I cant yes
should I recreate everything and make something like LineRenderer instead or
I have no idea about VR/AR stuff but what if you remove thet second parameter from your ScreenPointToRay
You mean inside the arrow creation?
I mean here ^
oh no yeah
actually I removed it since then
now its
public void OnPointerClick(PointerEventData eventData) {
if (eventData.button == PointerEventData.InputButton.Right) {
if (drawing != null) { drawing.IsExtending = false; toggleDrawUI.isOn = false; drawing = null; }
Vector3 mouse = Input.mousePosition;
mouse.z = 10;
Ray ray = Camera.main.ScreenPointToRay(mouse);
if (Physics.Raycast(ray, out RaycastHit hit, 10)) {
Debug.Log("x");
}```
We can't see the scene, inspector/components, hierarchy or anything that may be important. Maybe the collider isn't where we think it is?
I can screen everything if needed
well when I made the collider convex I could see it better
That could help
We wouldn't know if something is wrong with it, we can't see it.
You just have to tell me what you want to see haha
I ll get you the arrow with collider I guess
oh, now the collider is a box when I made it convex
it used to copy the arrow shape
Maybe due to the RealculareNormals?
Commenting out and testing
this is now convex
I ll try to get screen how it used to be
okay, cant get it back 😐
its not because of the normal recalc
I mean I would totally skip raycasting and use the PointerEventData eventData if I could
but for some reason the OnPointerClick PointerEventData eventData is detecting just my 2D sprites/objects
Hello, I am getting this error for my code, followed a tutorial for it and dont really know what is wrong, any help is greatly appreciated thank you!
configure your IDE
you wrote SterializeField instead of SerializeField
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
Typo
Thank you so much, I have my IDE but my intelasense has been acting up
you dont have IDE configured