#๐ปโcode-beginner
1 messages ยท Page 504 of 1
this ?
correct
do i change it to both?
ok, you did save and recompile your code didn't you?
yes everything is saved
no need, you are not using the new system here
keep it Input Manager (old)>?
then there is no reason for your debug not to appear when you press space unless you have compile errors
yes, since you are using the old one
can you put a debug.log in the update itself, just to check it is actually running
hm, are you entering playmode? your code should work
did you try do up the values in the inspector?
maybe the script/gameobject is disabled
doesnt seem like it
it does debug.log
how i check that?
i have it checked
if the debug.log is showing then it's running. show the console
no errors or warnings, unity isnt giving us a lot to work with lmao
ok, good, you can remove that
im just dont understand why no work
are you tabbed into playmode?
i just click the play button at the top
there are only 2 reason why the Debug.Log inside the if does not print
- An error is happening before the if is reached
- You are not pressing the spacebar
ok sooo umm
i figured out the problem
i was clicking the top screen not the bottom one
im sorry for wasing time
i feel bad now im use to unreal engine
for wasing your guys time
no problem, even I have been known to make mistakes (admittedly a very long time ago), lol
everyone starts somewhere
i try many engines UE4/UE5, RPG Maker MZ, GameMaker and now Unity so now i hope i can get use to this engine
hey guys, quick question
when using the or operator ||, it means only one of the conditions needs to be true, right?
if you dont understand the basics i would suggest you !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
How do I make my sprite jump while gravity is inversed? My gravity switch code is here, its seperate from my player movement code. Thanks ๐
correct, the first one that is true will break out of the if
thats what OR means yes
dont kick yourself though
!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.
i am using a Udemy class
ok great, because then why is this code considered cleaner than the other one, when it's very different on what it does?
(im aware it's js code, but i figured the syntax is pretty similar so it accomplishes similar results)
I would look up java operators then, they are probably the same but still
javascript operator works the same as c# operator
then the link stands true ๐
so then why not use an && here in place of an || ?
or well no
not an ampersand
but rather checking if authorized and then checking in a nested statmenet if authenticated
generally if there is an authorization problem you do not want to be too specific on what the problem is, it gives hackers too much information to work with
because that requires both to be True
&& needs both conditions to be true
that i do understand, but wouldn't this allow someone that's only authorized or only authenticated to access whatever the code allows access to?
that's a pretty fatal flaw here
yeah im aware of the silly question mb
corrected it
this code is bad anyway, missing early return..if first one logs why even run the second if statement?
!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.
indeed, should be | not ||
now that's something i should probably search up
| means both conditions will be evaluated
Im wondering how to make my character jump while inversed
This script is seperate from my player movement one
so basically ampersand but only one of them needs to be false to trigger it, and not both, right?
yes
alright, thanks a lot!
and nav is correct, there should be a return in there for it to make any sense
are quaternion understandings a beginners issue?
about to kick a gimbal to the moon over here
absolutely not, quaternions are black magic boxes
so I need an angry wizard
how about, copying a quaternion and making sure its the same quaternion?
to the same object too
no, you need a priest, just have faith they work
just use the same quaternion in a variable
and pass that for whatever
ig
heres the silly part, im sending it via osc, and reciving it via osc
so the meaning gets 'lost' and I have zero clue what Im doing
its for osc out to blender, but I had issues, so Im doing unity > unity first
90% the way there now
to blender will be another monster
RECEIVE | ENDPOINT([::ffff:127.0.0.1]:54057) ADDRESS(/rotation/L_Wrist) FLOAT(0) FLOAT(0.95881975) FLOAT(0) FLOAT(-0.28401527) this is my osc message, I can send hatebin stuff too, I hope this isnt too wizardry like when its quaternion to quaternion
if im being honest, i have zero clue what OSC is
worst part is when i can swap an axis, it follows but you do another rotation and its no longer following, its crazy
code please
sorry, preface, im learning a ton too didnt understand last week, osc is a protocol for sending info, I have a client and server on the game objects, just wanted to give preface and context because im using unity to build a app / tool here, was easier than using openxr and setting a dev environment, enough context though sorry
https://hatebin.com/vupfpvzruu < Parent object that sends the osc data OUT
https://hatebin.com/rvqfgqjqcl < Listener object that follows those rotations
position follows fine now, although its an euler, works fine, didnt before lol
line 46 is a big, big nono
Some osc output: https://hatebin.com/icsmggcojo
testRotation = new Quaternion(testRotation.x + 0.01f, testRotation.y, testRotation.z, testRotation.w).normalized;
not Debug.LogWarning($"Position data mismatch or invalid for '{objectName}'."); Right ?
yes, you can never manipulate the internal values of a Quaternion, so the + 0.01f and the normalized are out
'black magic box', do not touch for fear of explosion
Gotcha, removed that for now, for now won't be able to set it back to 1, 0 , 0 , 0 without it with my f key, not sure if I don't need it or not though for 'reset'
I want to be nice to the box
1,0,0,0 is not a valid Quaternion.
that is Quaternion.identity in unity speak
oh are you making a unity to blender exporter or smth?
Unity to blender for openxr so I can use a mocap glove / oculus quest 2 hand tracking in blender
ohhh you are gonna copy position and rotation from unity to blender
oh thats pretty neat
there's a tool out there already for now mocap fusion but processing time is ~15 mins for 2 mins of mocap, need something instant I have vmc4b with slimevr that works wonders
sod that, I'd just write a python add on for Blender
I've been dying to animate something with hands so bad
or c++
I have some of the python for blender ready to go too
I tried c++ openxr and the dev environment after ~8 hours got set and then couldnt get openxr to detect hmd ๐ง ๐ฅ haha
1.5 days bye bye
wait why not just make ik in blender and control it via Python or c++ (maybe)?
never done c++ for blender, always done it in python, didn't even know you could c++ tbh
c++ was for openxr, just couldnt get the dev environment running
quaternions were 1:1 awhile ago, but I kept writing code and ... oops
you might be able to do c++ for blender but i do know you can do python for it
you should be able to use c++ for it?
i wouldnt see why you couldnt
unless blender just says no to it
not sure how you would link the libraries
Only need OpenXR skeletal data to blender bones so I tried to use unity, wish it wasnt because the xr stuff takes a bigger load on system already running face mocap at the same time in conjuction with it, takes more resources, makes more lag
tbh everything you need to do should be doable in python inside blender
but for now its been ~1 week, it'd feel wrong to give up
do need access to openxr skeleton though
blender has openxr sort of
but not sure if 3.6 lts would support, that's where I'd need it
Blender 3.6? That's old
my LTS has ~50 addons lotsa paid stuff thats intertwines, lotta custom code, old but stable!
ah, legacy tie in, gotta hate it
Yeah, 90% are updated but I have so much custom code backed into blender for my own comfort too, I tried 4.x, my friend switched over he also relies on addons like animaide that dropepd support in 3.4x but he rewrote some of the code to make it work, he's been carrying the old along with him regardless of support ๐๐ดโ
unfortunately blender 3.4x vr experimental stuff is limited on documentation, not sure if it'd be worth debugging around to see if vr skeletal data would even be there
its just unity has the openxr stuff pretty accessible, with some resources, I think this might be a good method
anyway, back to your problem, your ocs output looks ok, but are you sure you are reading x,y,z,w on the blender side because they are switched you may be better outputting w, x, y, z from Unity to make sure
there are ~15 + vtuber apps, virtual motion capture has finger capture, but the pinky finger does not rotate correctly, so much searching on github for example code hahaa
for now I need to get x y z w to be 1:1 in unity I think
I couldnt get the child objects to rotate right in blender so I wanted to try in unity first if that makes sense
unity > unity 1:1 make sure that its doing the right stuff
makes sense, as I said apart from line 46, your code looks fine
thanks for poking around with it! for now I tried flipping values, it just got more confusing haha
kinda like rotating a rubix cube around if you dont know what youre doing
rotations are always a bitch, try simulating a gyroscope if you want to end up in the mad house
oof no gif
rotates rubix cube around until it breaks again
I will try asking slimevr, they somehow figured out the madness histerical confusion
sorry I could not be of more help, as a politician would say ' I think you are being very brave'
thank you for reviewing the code and giving me some no nos haha, I've been afraid to ask for help from some and now learning how to explain the situation to others has helped a lot too I think, just beginning to string my questions together to some people who use openxr maybe they might know too haha!
no problem. we call it 'rubber ducking' in the biz, a very useful form of debugging
this is my little ducky haha, it hurt my hand once when I grabbed it and forgot about the needle in his head
he isnt used as often as typing a giant question into discord and then deleting it after though lol
rofl, my rubber duck is in my head, it's why people are always giving me strange looks when I walk around talking to myself
Subvocalization requires louder vocalization sometimes ๐ฃ haha
rubber ducking debugging what even is that ๐
ah nevermind just looked it up, yes we rubber duck around here
Does anyone know how I can make my character jump while gravity is inversed? Here is my gravity switch code: https://paste.ofcode.org/3aSVxzWy3Ex992c6RDtwva4
that looks a bit painful for that needle being in his skull like that ๐
just reverse the jump
i dont see any jump code so
but thats the basic premace, just reverse whatever you are using to jump, probably a vector so reverse that
๐ 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.
Which line and where do I put it
rb.linearVelocity = new Vector2(-rb.linearVelocity.x, jumpingPower); this should work
just make a check if you are actually flipped
just add a Boolean in Flip() that either toggles or doesn't depending on what the code does and see if that is true and if it is then use the opposite inverted jumping
And would I put that script you just pasted in the gravity script or in my movement script?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Under an if statement?
Yeah im doing the learning, im just trying to get this figured out
if(isinverted){
//do something
// use inverted jump
}
if(!isinverted){
//do something
// use normal jump
}
How do you make it know if youre inverted though
I dont know how to do that lmao
its as easy as making a boolean variable and using it, either toggling it or not depending on if your code already toggles
boolean = !boolean; to toggle it (this should work, although i havent tested it)
hello i am trying to spawn an object then launch it and be able to control bit but it isnt accepting any inputs when spawned what am i doing wrong? i can seem to find any refrences online
have you tried using debug.logs to see whats running and what isnt
yeah im workin on it right now says no rigidbody found even though i have the prefab assigned on it
I was interested in creating a first person shooter, but I cant' really figure out what's more beneficial, a rigid body player controller or using a regular player controller. Any ideas?
i think people say, Rigidbody if you want to make collisions easier or character controller for easier movement.
however neither matters what you use, both will work fine
Rigidbody uses physics so might be better for certain things if your doing that
character controller might be used more for something realistic however again both can be used the same way
Kinematic character controllers are very robust and usually what I go with
I was wanting to make something that would use more momentum kinda.
(https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131; noting it's not super friendly for beginners to iterate on, but is super powerful)
Huh, shouldn't I make something from scratch though? Wouldn't using that without knowing scripting too much be bad?
Thats something im torn over quite a lot 
Yeah, if you have little scripting knowledge it's probably not the best recommendation. But there are tutorials that go over making a kinematic character controller from scratch. You mentioned momentum so it might not be the most suitable? It's really hard to say, and sadly it's not the simplest topic even though so many games require one haha
Yeah, after looking through Halo 3 vidocs, I realized just how complex controllers are despite being so simple to play with.
just try making each of them and see what fits what you need, no harm in trying and learning all you just get experience
That was something I was doing. Was pretty cool to have that click moment with adding momentum to a rigid body. the mouse look is a bit weird though. Almost kinda like its choppy? or stuttery?
probably the way your handling the camera movement then
Just make sure you're not multiplying mouse delta by deltaTime
Rigidbodies seemed smarter for calculating velocity though.
anyone know what happened to gdl.space? i used to use it to send code but its now turned into this? Is it safe that i went on this site? cause it says im running this thing in the cloud now
Looks like we'll have to remove it from our recommendations
I think i'll monkey with a regular controller later, but has anyone heard of the game I am your Beast?
ooh, im fine that I went on the website right? kinda confused what it means by im running it in the cloud now
of course you're fine
https://store.steampowered.com/app/1876590/I_Am_Your_Beast/
Like I want to replicate this sort of character controller but was thinking rigid body was the best idea.
I Am Your Beast is a shortform covert revenge thriller FPS about getting hunted across the North American wilderness by the military-industrial complex โ and turning the tables.You are secret agent Alphonse Harding. Retired for six years, you've been asked to complete โone last jobโ, one too many times. Declining your latest mission sets in moti...
$19.99
1044
That's the default nodejs template page. Looks like their website got wiped by a software update
oh alr idek what nodejs is lol, im good though right? nothings running in the cloud rn?
Basically, their website got reverted back to the template project. You did not get a virus, their website is just down
cool thx
anyone know how i can modify my drag a bit more, to check if im on a different type of floor like ice or something or like glue? Would it be better do this a different way instead of making layers for each type of ground like NormalGround, Ice, and Glue?
You could use physics materials to define friction.
does that work with player movement or just physics objects?
If you're moving the player via physics,then it would work of course.
pretty sure i am ya, i just tried it though i set dynamic and static friction to 0 and i dont seem to be sliding at all when i let go of my movement or while im moving either, it feels pretty much the same, unless the object is on a slope then it kinda pulls me down slowly but i dont gain any momemtum
Share your code then.
You're probably doing something like setting the velocity directly I guess? If you're resetting it when the input is zero, obviously it's not gonna slide anywhere.
this is what i got for the movement atm, and the drag is just this, i also have stuff for sprinting crouching jumping and dashing, but that shouldn't affect this i dont think
Oh, you're using forces. The object should keep on moving then. You probably have some other code that affects it.
Where is MovePlayer called?
FixedUpdate
Share the fixed update. Share the whole script actually.
!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.
what is wrong with this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Handanimcontrooler : MonoBehaviour {
[SerializeField] private InputActionProperty triggerAction;
[SerializeField] private InputActionProperty gripAction;
private Animator anim;
private void Start() {
anim = GetComponent<Animator>();
}
private void update() {
float triggerValue = triggerAction.action.ReadValue<float>();
float gripValue = gripAction.action.ReadValue<float>();
anim.SetFloat("Trigger", triggerValue);
anim.SetFloat("Grip", gripValue);
}
}
Share !code properly and provide a proper explanation of the issue:
๐ 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 said Handanimcontrooler thas y lol
Hmm... I can't see anything that would specifically interfere. Maybe make sure that the drag is being 0 as well when you want to slide.
how should i check to see that im on ice to then set the drag to 0?
i tried just doing it on an ice layer but then the layer of the ice isnt ground anymore, which prevents my player from being able to jump on it
For starters just make it 0 all the time to see if that's what's preventing you from sliding
Great. So you can use the physics material instead of drag.
anyone here familiar with using unity and github together?
me and my friend are new to source control and can't seem to upload the project we've been working on, into a single github repository. we have a central folder and don't know why we can't upload it to a github repo
wait u mean dont use drag at all? Wouldn't drag be better though since i can change the amount of air control and ground control better if I'm using drag?
If you really need to, you can use it during jump only. The rest of the time just let the friction control the slipperiness of the surface.
There are plenty of tutorials on that. Did you try following any?
oh yea thats true, so just change my code to set drag to 0 all the time while grounded and still set the drag to my air drag value while in the air?
and then just use physics materials for every object that i want to the player to walk on?
Something like that.
i haven't found any tutorials, im just googling our problem
Then try searching a tutorial on using GitHub with unity first and make sure you understand the process correctly.
What kind of tips? This is really vague. If you don't have a very specific question, there's not much we can help you with.
I'm not telling you to figure it out. I'm telling you to follow a tutorial that explain everything in detail. We can't afford to make a lecture on discord.
If you have an issue with the tutorial then come back with a specific question
I have a folder containing a bunch of unity test projects. I want to be able to upload them to a github repo so my friend can have access to the same projects and make changes to them accordingly, but it isn't allowing me to take my centralized folder and create a repo out of it. I guess my question is, how can I do that? OR is my understanding of how repos work wrong?
What "isn't allowing" you to do that?
A repo is just a set of files. There's no specific rule preventing you from uploading several folders
so in the structure, does it go:
- repo/folder
or
2) folder/repo
because I'm choosing 1
only problem im getting now is the friction isnt really working like how the drag was working, it kinda makes it take longer to start moving based on how high the friction is and then i just keep speeding up forever, with the drag it seemed to not exceed a certain speed when i had the drag set at a value of 6 and i would accelerate almost instantly to my player walk speed of 6 also
and it's not saying I've made any changes to the repo
Either one is fine. A repository is just what you have uploaded to GitHub. It doesn't matter how or where it's located on your local PC or what exactly it contains.
What doesn't say that?
github desktop
Try setting static friction to 0
Take a screenshot of the setup and the actual error
and as I've added folders to the repo on my local machine, it isn't updating github for my friend who cannot fetch the changes I'm trying to make
and I've tried pushing those changes as well
Then you didn't push your changes.
Again, I can't really say anything specific without seeing the context.
uh it still feels about the same except it doesn't speed up forever, but it speed up a ton still
Then increase the dynamic friction.
Aah, actually, I see what the issue is.
I guess you'll need to use both for finer control.
As for how you can detect a surface type, you could use a raycast or OnCollisionEnter to get the surface collider you're currently touching. Then you have many options to identify the surface type. For example, you could check the physics material it's using. Or check the object tag. Or have a component that defines the surface type.
I have a custom grid in unity. I'm trying to brainstorm how I would snap objects to the grid when created and when moved around while in the editor. Currently struggling on the idea. Any help?
You could have an editor script that snaps the object to the grid in update or something.
Hmmm. I imagine I would need some way to tell what objects to snap right? I wouldn't want all objects to snap, just certain ones.
Well, the first thing that comes to mind is that the script only affects the object it is attached to.
Ah, I was thinking the other way around, searching for objects with a certain component.
Sounds expensive and confusing.
What I was thinking too. Your way sounds a lot better
how do i do a code so that on collision it takes the Y value and multiplies it by -1 and multiplies the X by 1?
Put whatever logic you need in OnCollisionEnter
how do i multiply the y cord
idk thats y im asking
c#? i think. that wat unity uses
It is yes.
Then you should go learn the basics of C#.
so how do i multiply the y value?
Same as any other number. If you don't know how to multiply numbers, you should go learn the basics properly.
For example here:
https://www.w3schools.com/cs/index.php
there is also the Junior Programmer Pathway on the !learn site, and also this video if you are in a rush to get this done without a real understanding of things (You will Really need to learn those things, as it is expected in order to use Unity)
https://www.youtube.com/watch?v=sYf4bSj9j2w
@tender ravine
In this video I tried to cover as much useful information about Vectors in Unity as possible. We start by discussing what Vectors are, what useful properties they have then we go through most useful methods and at the end of the video I am giving 2 examples of solutions that require vectors.
This was until now the most challanging video to make...
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
i just tried doing the OnCollisionEnter and checking for tag of Ice to see if the ground is ice before settings my drag to 0, but for some reason even when im not touching the ice anymore and i jump or something it still says im touching the ice until i come in contact with a different object
is there a way to make it so as soon as i stop touching the ice it stops settings isGroundedOnIce to true
OnCollisionExit
thanks
God, I love editor scripts so much
is this the correct way to do it? Also is this performance heavy at all/not really optimized to do, im not really sure on what the best practices are atm to make something optimized
this is also how my drag is now
Yes, this is fine.
As for performance, don't think about it until you have an actual performance issue. At which point you should be doing profiling based optimization.
ok thanks
just dont wanna develop any bad habits lol by doing something that's really costly. I've done some stuff in Unreal Engine before and ik ppl say to not put a bunch of heavy operations under the event tick that's called every frame, which is comparable to like void Update i think
None of what you shared could be called a "heavy operation", so it's fine
guys don't use Linq constantly, especially if you have high amount of subjects
I have done that mistake, lol.
like, I saw my mistake by the performance loss that I had to detect in the profiler
code not displaying the ray
using System.Collections.Generic;
using UnityEngine;
public class control : MonoBehaviour
{ public float x,y;
public float movSpeed;
float speedX, speedY;
public float dist;
public GameObject start;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
x = 1f;
y = 0f;
}
// Update is called once per frame
void Update()
{
if (speedX >0){
x = 1f;
}
if (speedX<0){
x= -1f;
}
if (speedY>0){
y = 1f;
}
if ( speedY<0)
{
y = -1f;
}
RaycastHit2D ok = Physics2D.Raycast(start.transform.position, Vector2.up*new Vector2(x,y),5f);
speedX = Input. GetAxisRaw("Horizontal") * movSpeed;
speedY = Input. GetAxisRaw("Vertical") * movSpeed;
rb. velocity = new Vector2(speedX, speedY);
if (ok.collider != null){
Debug.DrawRay(start.transform.position,Vector2.up*ok.distance*new Vector2(x,y),Color.blue);
}
else
{
Debug.DrawRay(start.transform.position,Vector2.up*ok.distance*new Vector2(x,y),Color.blue);
}
}
}
the direction is wrong(haven't configured) but the code isn't displaying anything
it isnt drawing anything unless the distance of raycast is 500f
or more
Make sure gizmos are enabled in that view
If the raycast doesn't hit anything, distance is 0 so the debug.drawray length is also 0. Use a fixed length in that case
Also multiplying two vectors shouldn't even work
Certainly a concern that the code shouldn't be compiling
if errors aren't underlined in red your !ide needs configuring
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
but it draws a upwards ray when i make the dist 500f ?
it still isnt colliding with anything
The code you've shown doesn't compile
whaaaaa
Bruh.. did you even read what vertx wrote?
more like i have no idea what he said in the first comment
do you see the sphere in the most right? that's what enables the debug draws
compliling as in there should be an error in the console?
just enable it, that's what he said as first
Never mind, Niktu was wrong and Vector2 has a multiply function.
Change it to this:
if (ok.collider != null)
{
Debug.DrawRay(start.transform.position, new Vector2(x, y) * ok.distance, Color.blue);
}
else
{
Debug.DrawRay(start.transform.position, new Vector2(x, y) * 5f, Color.red);
}
Vector3 doesn't have a multiply, but Vector2 does
Yeah, it just doesn't make sense here
Your logic is very weird though, as Vector2.up*new Vector2(x,y) doesn't make much sense
The outcome would be the same as new Vector2(0, y)
Also change the raycast to use new Vector2(x,y) instead of multiplying
i was having trouble getting that too, original code wasnt working so i copied it from a youtuber๐
realised he did so as he was making a side scroller
it works now! thanks
also if may not be too much trouble could you explain what was wrong with my logic?
and what you did?
Like I said, ok.distance is 0 when the raycast doesn't hit anything so the DrawRay was also 0 length when you multiplied by it
and like vertx said, multiplying the vector by Vector2.up doesn't make sense
Hi my friends.. quick question.. when I mouse over the non active objects never turn into active.. any ideas? The script is on the gunright object.
Place a log and see if it's called
It is not being called the debug log. But why would be that? it is an object with that script.. and that is it.
If you're writing UI code you should be using the IPointer...Handler interfaces https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.EventSystems.IPointerEnterHandler.html
IPointerClickHandler
IPointerDownHandler
IPointerEnterHandler
IPointerExitHandler
IPointerMoveHandler
IPointerUpHandler
You want enter and exit in this case
Thank you. That way is working great !!
Using UnityEvents, the event has a float as an argument but for some reason, this field is here and calls the function with 0.
How do i make it so it actually uses the event argument?
Assign the function from the dynamic parameter list
Not the static list
Hi everyone! help please. i make a multiplayer game using Photon Pun, and i have everything working, [actually], there are players on the server, but they are not visible in the game. i can throw all the scripts for multiplayer that i used. i tried to fix it, but it didn't work out.
How many lines of code should my player script have?
42
42 seems VERY low
43?
much better ๐
60
60 seems too many
50
but i think i need to cut down my script then, mine has 630
630 is small
yeah? What should i try keep it under?
Why do you think you need to? It's a silly question
That's the wrong question to ask. A script should have as many lines as are needed
If it starts to get several hundred lines long, it's time to consider if it could be split into multiple classes
HELLO again
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class mapManager : MonoBehaviour
{
public Tilemap map;
//control script;
void update()
{
if(Input. GetMouseButton (0)){
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int gridPosition = map.WorldToCell(mousePosition);
TileBase clickedTile = map.GetTile(gridPosition);
print("At position" + gridPosition + " there is a " + clickedTile);
print("YESSS");
}
}
}
you must be effing kidding me
Nothing. Counting lines of code is pointless
MAN ive been trying to correct it for hours now!!!!
just for the update to be wrong
It's not the only thing that's wrong ...
You need to configure your !ide so you can actually see errors.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
thanks
also got it
Ahhh alrighty
how do you specify unmanaged types?
Vector2 lookDirection = (mousePos - pivotPos).normalized;
float lookRotation = Quaternion.FromToRotation(Vector2.right, lookDirection).z;
weaponPivot.rotation = new Quaternion(weaponPivot.rotation.x, weaponPivot.rotation.y, lookRotation, weaponPivot.rotation.w);```
I'm trying to rotate an object towards my cursor, and it works fine except that when the z-rotation is between -120 and -180 degrees, it just flips and becomes positive, and I can't figure out why or why it's for those angle specifically. Does anyone have any idea?
you should avoid creating Quaternions like that, they're pretty tricky to work with
check the docs for FromToRotation to see how the rotation is applied properly
if you want to specify the rotation in angles, use Quaternion.Euler
can someone help me with this, it doesn't work for some reason:
!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.
lol this is the best way Ive seen someone share code
wtfff
i've seen someone share their code as a gif once. i think that was objectively the worst way to do it i've ever seen because you can't just pause a gif to read the code lmao
mb I don't know how things work here
#๐ปโcode-beginner message
check out the bot message how to share code, and use screenshots instead for anything visual most of the time
https://hatebin.com/bkpvdcmtop
like this?
yes
now go through this: https://unity.huh.how/physics-messages/2d-physics-messages
Why cant i create a reference to a script here, and how do i properly do it?
do you have a component called ObjectB?
some lines missing code btw (not saying its problem because its on video but you somehow didn't paste it)
no but what im trying to do here is make a reference so i can access and change the code of another gameobject in another code
gameobject names are not variable types
oh yea i was trying to make a new vector instead of using rb velocity
if you want to reference a GameObject then use the GameObject type. however GameObject does not have a variable called ammo so perhaps you want a different type, probably one of your components
i wanna make it so that once it collides with a player/paddle, it bounces in the other direction at the same angle as its initial impact
i would use Vector2.Reflect method
i tried that but the outcome is the same
did you bother going through the link i sent that will tell you why that code is not working?
it doesnt explain specifically why my code isn't working, it's a general overview on collisions in unity is it not
it guides you through debugging your method with common issues
did you click through the steps?
the issue is also answered by literally the first step
oh is it cause it was Collision and not Collision2D
make sure you read all of the information presented to you
thank you for the um clues
now collision works but it just goes in a rectangular path
show your current code
Doesnt matter but if its a simple controller then you might have a lot of useless things
like this? https://hatebin.com/amlifrwgqe
doesn't really reflect, just kind of slides off the surface to another surface and slides across that one too. rectangular path again
happened the last time i tried vector reflect too
and what debugging have you done to ensure the values you are using are what you expect?
I just made it write a line for when it detects collision with the walls or paddles, and it doesn't write anything
well that at least indicates that the if statement is never true if a log inside of it never prints
which means you need to check the tag on the objects you expect this to collide with
So question, why use ScriptableObjects when you can serialize variables in the inspector anyway? Is there any benefit or is it just cleaner code?
ScriptableObjects allow you to define a type of asset rather than just a component (which is what MonoBehaviour is for)
when i print the tag of the object it's colliding with, it does detect collision with the wall and the paddle once, but after that it doesn't register anything
make sure you are printing that information outside of the if statement
yep, same problem
after it collides with the wall and paddle once, it doesn't register the tag anymore
show your current code
so if nothing at all is printed, then no valid collision is actually happening. are you sure nothing is printed, rather than maybe you have your console set to collapse mode?
no it prints the tag correctly twice, then it just prints the last printed thing over and over even though the tag isnt correct
it is printing the tag of the object that it collides with. if you think that the tag isn't correct, then it is colliding with something that has the incorrect tag. the logs are not lying to you
replace your log with this: Debug.Log($"{name} is colliding with {collision.gameObject.name} with tag {collision.gameObject.tag}"); and you'll see more info about what is colliding and can get a better idea of why that is happening
if it is a proper screen recording and not recorded with a shaky phone camera, yes
I dont think that using Reflect with rb.velocity really works when colliding. When OnCollisionEnter gets called, the collision has already modified rb.velocity
Probably better to keep track of the velocity manually
sure but that's not what we are currently debugging. they are saying that the object being collided with has the wrong tag. i am trying to show them why. then we can move on to debugging the actual values they are using (like i suggested before this)
does anyone know why ScreenToWorldPoint is always returning 0,0,-1 for me? I'm trying to get Input.mouseposition to work with a camera space pixel perfect canvas in unity 2d
nvm, fixed it. had to set the Z to the camera distance
Because you're using it with a perspective camera without passing a z coordinate
for some reason my camera was on perspective
when it should have been on orthographic
pixel perfect was overriding it, not sure if it was just an inspector thing
can you screenshot your console when this is happening. because we were trying to figure out why it was colliding with objects that had the incorrect tag. we need to address that before addressing your incorrect reflect
I dont know why the dash isnt working, it is going inside the rolling state but somehow the coroutine isnt being called. https://hatebin.com/rveihitmij (rollingState) , https://hatebin.com/zczsevonoe (PlayerBaseState), https://hatebin.com/fbegwzbpyr (StateManager)
the logic for going into the rollingstate is correct, made a debug of it and was working well, only thing is that the roll coroutine isnt working
Coroutines must be started with StartCoroutine() from a MonoBehaviour
you can't just call the function
i completely forgot
you deserve all good that happens to you and even more
may god bless you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class mapManager : MonoBehaviour
{
public Tilemap map;
control script;
void Start()
{
script = GameObject.Find("Square").GetComponent<control>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{ Vector2 pos = Camera.main.ScreenToWorldPoint(script.ray_end);
Vector3Int grid_pos = map.WorldToCell(pos);
TileBase selected_tile = map.GetTile(grid_pos);
print(grid_pos );
print(selected_tile);
print("YESSS");
}
}
}
the code works but the detals of the tile at the given position is wrong
as if the entire map is shifted
can anyone help me figure out why my enemy is doing this for the rollaball tutorial?
EnemyMovement script
using UnityEngine;
using UnityEngine.AI;
public class EnemyMovement : MonoBehaviour
{
// Reference to the player's transform.
public Transform player;
// Reference to the NavMeshAgent component for pathfinding.
private NavMeshAgent navMeshAgent;
// Start is called before the first frame update.
void Start()
{
// Get and store the NavMeshAgent component attached to this object.
navMeshAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame.
void Update()
{
// If there's a reference to the player...
if (player != null)
{
// Set the enemy's destination to the player's current position.
navMeshAgent.SetDestination(player.position);
}
}
}```
like the tile is hills_22 here
but it should display hilla_11 here which it is not
but if i move a but up it shows the tile name as hills_11
Maybe show the balls inspector/collider
And the collider in scene?
I'm wanting to suggest that maybe the ball's collider is preventing the agent from getting closer.
if i were doing an inventory system where the player would use their wasd keys to move around it, for different rows would i have the lists be nested inside another list, or tell it to just jump a certain number of slots (assuming the amount of slots is a multiple.
Like if I have 24 slots as a 6 x 4, and I want to go to the slot directly below number 1, it would need to check 6 slots down the list
i dont know which seems more reasonable
i feel like telling it to move 6 slots lower or higher if they click w or s would be easier but im not sure if its the best method to go about it
hey Im starting to develop my first game and Im stuck on making my jump work
if anyone can help me on VC I would grately appriciate it
You could just paste the code here so we can see what have you done so far.
!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.
I dont want to use forces because it makes the game feel harder to control
so I'm implementing them using vectors
!csharp
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
also your code makes little sense
something like this might work:
private float jumpTime = 0.0f;
private float buttonTime = 0.5f;
private float jumpForce = 10.0f;
private bool isJumping;
private bool isJumpCancelled;
void Update ()
{
Jump();
}
private void FixedUpdate()
{
if(isJumpCancelled && isJumping && playerRB.velocity.y > 0)
{
playerRB.linearVelocity = new Vector3(0, jumpForce,0);
}
}
void Jump ()
{
if(isGrounded() && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
isJumpCancelled = false;
jumpTime = 0.0f;
}
if(isJumping)
{
jumpTime += Time.deltaTime;
if (Input.GetKeyUp(KeyCode.Space))
{
isJumpCancelled = true;
}
if (jumpTime > buttonTime)
{
isJumping = false;
}
}
}```
Did not make it myself
thanks those are good fixes for my code but I dont think that the problem is in the code anymore
I tried to do a basic add force function for when I press 'w' and the character still doesnt move
then you are overwriting the velocity perhaps with a .velocity in your movement
thats the problem thanks
bump pls idk what is wrong
did you accidentally make it the child of the player?
Did you try creating empty object and put that empty object as a child of a player and then tried to follow that empty object instead of player ?
bro y dose this have to be so cunfuzeing using
System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.ImputSystem
public class PlayerJump : MonoBehaviour
{
[SerializeField] private ImputActionProperty jumpButton;
[SerializeField] private float jumpheight = 3f;
[SerializeField] private CharacterController cc;
[SerializeField] private LayerMask groundLayers;
private float gravity = Physics.gravity.y;
private Vector3 movement;
private void Update() {
bool _isGrounded = _IsGrounded();
if (jumpButton.action.WasPressedThisFrame() && _isGrounded) {
Jump();
movement.y += gravity * Time.deltaTime;
cc.Move(movement * Time.deltaTime)
void Jump() {
movement.y = Mathf.Sqrt(jumpheight * -3.0f * gravity);
}
private bool IsGrounded() {
return Physics.CheckSphere(transform.position, 0.2f, groundLayers);
}
}
AND IT STILL DOSENT WORK
post !code properly according to bot. Look at Large 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.
seems like a syntax error
thats what i did at first and i got this
huh ?
use links to post large code
thats the result of it
the result of what?
those websites
its not, you have to send the link after you pasted and saved the code on the site
hu what link
If you used the website why didn't you actually post the link
it only says to past it
paste
Yes, and then share the link here so we can actually see the code
this did not work
OOOOOOOOOOOO
line 25 why did you ignore the error you have
can't expect it to work if you have code that doesn't even compile
Okay now what is the actual question
try to debug what destination is trying to reach
man im new to all of this idk what im doing im just following a totorial and it ant working๐ญ
{
// If there's a reference to the player...
if (player != null)
{
// Set the enemy's destination to the player's current position.
navMeshAgent.SetDestination(player.position);
}
}```
(This is Enemy script)
like i would log the player.position?
did you not copy the same as the tutorial?
i did
send the tutorial link, n screenshot your Unity Console window
tripple checked
ok
Learn how to JUMP in VR using Unity's XR Interaction Toolkit. In this video, we create a new script for our Player and implement a jumping mechanic for our player using Unity's Character Controller!
Previous video: https://youtu.be/mYhVNtRGAhw
Get the source code: https://www.patreon.com/posts/unity-vr-source-88131424
// JOIN THE COMMUNITY DI...
corporate wants you to find the difference
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 179
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-10-05
navMeshAgent.SetDestination(player.position);
Debug.Log($"{player.position}");
im new to C#, whats the difference between Debug.Log(player.position); vs what you wrote
looks like its getting the correct position still
-they look exact
you sure about that?
๐ข
Go character by character. Compare the Move line between both
Its a string interpolitaion you can read more here https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
You have the answer right in front of you, it's not going to be any easier to read it if we write it instead of the tutorial
gotcha
so position is the exact player position but the enemy still isnt moving towards it
i definitely followed the tutorial to the T so im not sure why its not moving on its own
Try restarting your unity
this is like my 5th time trying to figure it out so i dont think that would help
If that dosent help try to draw a sphere and see where its trying to get in Scene view.
void OnDrawGizmos()
{
// Draw a red sphere at the transform's position
Gizmos.color = Color.red;
Gizmos.DrawSphere(player.position, 1);
}
where would i put that? in the Update func of enemy?
Just outside anyMethod
void Update()
{
// If there's a reference to the player...
if (player != null)
{
// Set the enemy's destination to the player's current position.
navMeshAgent.SetDestination(player.position);
Debug.Log($"{player.position}");
OnDrawGizmos();
}
}
void OnDrawGizmos()
{
// Draw a redlow sphere at the transform's position
Gizmos.color = Color.red;
Gizmos.DrawSphere(player.position, 1);
}```
No outside of Update
your not supposed to put methods in other methods usually
do i just put the function or do i call ti somewhere
leave it like that, it gets called automatically by Unity
Yea just put the function
Try re baking Nav Mesh
was it the nav mesh ?
no man im dumb, i positioned enemy body and not enemy parent object...
nvm about following tutorial to the T....
thanks for the help though appreciate it
using UnityEngine;
using UnityEngine.PostProcessing;
namespace UnityEditor.PostProcessing
{
[CustomPropertyDrawer(typeof(MinAttribute))]
sealed class MinDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MinAttribute attribute = (MinAttribute)base.attribute;
if (property.propertyType == SerializedPropertyType.Integer)
{
int v = EditorGUI.IntField(position, label, property.intValue);
property.intValue = (int)Mathf.Max(v, attribute.min);
}
else if (property.propertyType == SerializedPropertyType.Float)
{
float v = EditorGUI.FloatField(position, label, property.floatValue);
property.floatValue = Mathf.Max(v, attribute.min);
}
else
{
EditorGUI.LabelField(position, label.text, "Use Min with float or int.");
}
}
}
}
what is this error
unity is struggling to know which MinAttribute you want to use i think
yes, you should specify which one you want to use
you can do that in 2 ways
by just doing UnityEngine.PostProcessing.MinAttribue attribute = ... when using it (or the other one if you want that)
no, it's just matter of using correct namespace
or just do using MinAttribute = UnityEngine.PostProcessing; i think
what is a great way to have a field dissapear in the editor if a bool in that scriptable object is set to false?
curious, do you have a preference or is either one more common than the other?
this way is easier since if you wanna use it multiple times it saves you from writing the whole namespace
but both work
custom inspector
gotcha
What im trying to do specifically is something like (pseudo code) public class Attack : ScriptableObject { bool ranged; if(ranged) ProjectileType projectile; int volleySize; float damage; float cooldown; }
Will what you referenced work for this?
yes CustomEditors
btw those fields are private though.
Anyway you'd do something like
EditorGUILayout.PropertyField(rangedProp);
if (rangedProp.boolValue)
{
EditorGUILayout.PropertyField(projectileProp);
}
if you want to still show but make it not interactable use this https://docs.unity3d.com/ScriptReference/GUI-enabled.html
EditorGUILayout.PropertyField(rangedProp);
GUI.enabled = rangedProp.boolValue;
EditorGUILayout.PropertyField(projectileProp);
GUI.enabled = true;```
Do you guys use statemachines for coding ?
Anyone got a Teleport script for a gtag fan game?
no, make one or find one online
if you actually want help then you can ask questions about making one, but usually people dont give out scripts for free here
im new to unity and im following this flappy bird tutorial to make my first game. should i learn some c# before diving into unity?
yes, itll be a lot easier if you have a basic understanding of how to write code before trying to learn the whole unity part too.
do you recommend any specific tutorials on youtube or online? or should i keep following my flappy bird tutorial?
if it fits the situation . . .
Example ?
When I'm trying to use an interface from another script and have a class inherit it do I have to reference the script that I'm getting the interface from? I'm attempting to have a class in another script inherit an interface but im getting an error of " The type or namespace name 'IInteractable' could not be found (are you missing a using directive or an assembly reference?)" I have the interface inheritance placed after Monobehavior like "Monobehavior, IInteractable"
character controller, a turn-based battle system (any turn-based/ordered system), or anything that must be in one state of being at a time . . .
is Interactable the class or an interface? it looks like a class based on its name . . .
It's an interface, I just renamed it cause I realized its poor naming convention, its IInteractable now
Nevermind, just solved it myself my bad
I gotta reference the original script just using dot notation, so I just had to make it "Monobehavior, InteractionHandler.IInteractable"
that's because you made the interface a member of InteractionHandler. it should be outside of the class (in its own file) . . .
Yep you're right, I accidentally nested it inside InteractionHandler, I left it in the InteractionHandler file just cause I dont have a file just for interfaces right now so it just makes sense to me to leave it there, but moving it out of InteractionHandler so its not nested fixed it so I dont need to reference InteractionHandler before
Iโve never coded before
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yeah thanks Iโm tryna Learn but rn I donโt know how to do the simplest script
thats what the learning material is for, you know..to learn..
Ikkkkkk
I hate the blender server
I said one thing
Not knowing itโs a rule
And got flamed for not knowing
Can anyone help with my camera code? for some reason it feels inconsistent like it has some sort of mouse acceleration on it somehow, I'm following a pretty popular fps controller tutorial and everything is copied correct I'm pretty sure
you should not be multiplying mouse input with Time.deltaTime, mouse is already framerate independent
hmm weird that he has that in it then, i tried doing that though and it didnt seem to change anything
this is how everything is setup currently
its just something to do in general
thats why your sens is 450+
do i also need to lower my sens to a really small value when doing it that way? Cause if it feels crazy fast unless its like 0.5 without the delta time
but it still feels inconsistent
yea
most likely because your camera and body are rotating at different times or same forgot which
parent the camera to player remove the rotation on Y axis for cam
player rotating will make camera follow that rotation
wouldn't that make it jittery though, cause i tried doing a different tutorial for a camera that had it on the player and it turned out very jittery
i think i have the rigidbody rotation frozen rn atm too
Yea
rotating not matching the physics time on cam usually causes issues
yea, also on top of it feeling a little inconsistent it sometimes like skips a bit fast in the direcetion im looking around in, kinda like almost teleport in the direction im currently moving my camera but not really
You can try maybe seeing if cinemachine will deal with it better on the cinemachine brain
!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.
https://paste.ofcode.org/5x5w7qzrD3bmmptY7hkN7L
im having an issue with room generation where the minimum rooms is not always reached
sometimes it works
sometimes it doest
the max rooms is 30 and min is 20

Is there some logic here that prevents rooms spawning on top of each other?
yeah they dont spawn on top of each other it just doesnt reach enough
in the console you can see it looks at a room that already has one but doesnt spawn it
it doesnt reach the generation complete message
i seemed to have got it fixed by following a diff tutorial that changed up a few things
Anyone know how i can show my moveSpeed float value on screen as text constantly changing so i can see my speed in real time?
what are the changes ?
private void OnGUI()
{
GUI.Label(new Rect(0, 20, 200, 30), $"{movSpeed:F2}");
}```<https://docs.unity3d.com/ScriptReference/GUI.Label.html>
or use a canvas
it seemed to just add subtract and multiply the variables i had a bit different and without the delta time, and also just switched what the scripts where placed on, and what objects i needed to drag into the inspector
I see, a bit vague but as long as it works 
here's the whole thing if ur curious :D https://hatebin.com/vdzgpjkmmn
seems to work now though so thats good lol
thanks
sometimes it just does this
i have no clue why this happens but i keep getting out of the rolling state in the statemachine i made even if i dont switch the states https://hatebin.com/jwspyefhrp (rolling state code), https://hatebin.com/hwbgjstoya (state manager)
it goes inside the roll state and afterwards goes back to whatever state
i try to copy an examine system of a girl's tutorial but it doesn't seem to work, when i move close to front of table, the console immediately shows error at line 111, and for the back of table, it shows error at 121, here the code of her: https://github.com/yasmeen2001234/Unity-3D-Examine-system/blob/main/Assets/Object_Interact.cs
but it shouldnt get out since i dont call the switch state void
question
I'm referencing a player gameobject position from one script to another,
but its x,y pos is coming as 0,0 even if i move the object
How are you referencing the object
vector2 aa = obj.transform.position
what is obj
in the first script๐
square player in my scene
with a rigidbody2d and movement controls
how are you assigning obj
in second im using it as vector2 bc = script.aa
im referencing the movement script in the object where ive defined this
and, as I have asked several times, how are you doing that
how are you referencing that object
sir
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class mapManager : MonoBehaviour
{
public Tilemap map;
control script;
void Start()
{
script = GameObject.Find("Square").GetComponent<control>();
}
void Update()
{
if(Input. GetMouseButton (0)){
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int gridPosition = map.WorldToCell(mousePosition);
TileBase clickedTile = map.GetTile(gridPosition);
print("At position" + gridPosition + " there is a " + clickedTile);
print("YESSS");
}
if (Input.GetKeyDown(KeyCode.Tab))
{ Vector2 pos = Camera.main.ViewportToWorldPoint(script.ray_end);
Vector3Int grid_pos = map.WorldToCell(pos);
TileBase selected_tile = map.GetTile(grid_pos);
print(grid_pos );
print(selected_tile);
print("YESSS");
}
}
}
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class control : MonoBehaviour
{ public float x,y;
public float movSpeed;
float speedX, speedY;
public float dist;
public GameObject start;
public Vector2 ray_end;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
x = 1f;
y = 0f;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W)){
x = 0f;
y = 1f;
}
if (Input.GetKeyDown(KeyCode.A)){
x = -1f;
y = 0f;
}
if (Input.GetKeyDown(KeyCode.S)){
x = 0f;
y = -1f;
}
if (Input.GetKeyDown(KeyCode.D)){
x = 1f;
y = 0f;
}
RaycastHit2D ok = Physics2D.Raycast(start.transform.position, Vector2.up*new Vector2(x,y),dist);
speedX = Input. GetAxisRaw("Horizontal") * movSpeed;
speedY = Input. GetAxisRaw("Vertical") * movSpeed;
rb. velocity = new Vector2(speedX, speedY);
if (ok.collider != null)
{
Debug.DrawRay(start.transform.position, new Vector2(x, y) * ok.distance, Color.blue);
}
else
{
Debug.DrawRay(start.transform.position, new Vector2(x, y) * ok.distance, Color.red);
}
Vector2 ray_end = start.transform.position* new Vector2(x,y)*dist;
}
}
i did correct the code later
Okay so you're finding a random object named "Square", and getting a control component from it. I don't see you getting the position from here
but referencing the position of the obhect from the other script isnt working
What line is giving you a position you don't expect
here, Vector2 ray_end = start.transform.position* new Vector2(x,y)*dist;
when i refer to this variable in this script, Vector2 pos = Camera.main.ViewportToWorldPoint(script.ray_end);
Okay and how are you assigning start
Okay and what is it assigned to
Please stop saying sir and actually answer the questions I ask
How have you assigned a value to start and what is it assigned to
Okay, so you have dragged in this object from the scene into itself
I'm really sorry for being so difficult, and does this clarify it?
My first question would be why have the start variable at all instead of just using this.transform.position
i didnt know you could do that
So, every time you use start.transform.position you're getting this objects current position.
Then, you're multiplying that position by 5 and using that as ray_end
yes
So, that'd be the position five times further from the origin than the object currently is, in each direction.
Is that what you're going for?
yes
wait
im going for the 5 times the pos in the current direction the object is facing
Nothing here involves a facing direction. You're just multiplying the position by 5
So if the object is at 0,0 the ray end will be at 0,0. If it's at 1,1, ray end will be 5,5. If it's at 100,100, ray end will be 500,500
i dm'ed you the script
I dont know why its changing states, even if isDashing is still true after the duration of the roll it still changes to some other state and doesnt check the update inside the rollstate https://hatebin.com/hpzrpuipte (state manager), https://hatebin.com/ymqgluhfmm (Player states), from what i think since im changing the state and the code isnt working unless that state is active the only thing that matters to read is the state manager and line 162-204 in player states
ive been stuck with this for hours, and its not that i cant fix it, its that i dont even understand it
any help is aprecciated
(pls ping, ty)
i need to reference a button that on click it shows some text and i need to find displaymessage from operators but i just dont see anything, im trying to learn from a tutorial that is 2 years old, did anything change? (sorry for bad english)
Did you reference the object with the component?
I'm assuming you meant you attached the component to the object and referenced the object
yes
so for more context first, im following a tutorial and it said to create a script called my operators, add that script to the text, and reference the text to the button
Hello people. Do you know how to get a GridLayout reference from a Gameobject who have a Grid as component? I didn't found how online even on Unity Manual
hi, im trying to figure out how in the world to enable VSync. unfortunaley the Quality Settings doesnt really seem to affect the vsync when im playing in the editor and it's left unchecked.
QualitySettings.vSyncCount = 1;
apologies if this is the wrong place to ask this
Last time I had problem with text (and I didnt coded for a long time) was because I was using Textand my variable was using Text from TextMeshPro
Or possibly they've got an invalid function - limited one parameter etc
If i have vector3 P1 , how to get Vector3 P2 on the direction line Vector3 V1?
is it Vector3.Project(P1, V1) ?
Depends what you're doing
I imagine P1 being a point relative to the center of the world and V1 could be relative to whatever you're getting it from and to
Projection works for vectors of the same origin as far as I'm aware, so if that's the case then just try it out and see for yourself
!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.
im trying to instantiate throwobject from prefab and get it back to player (then deleting it) by making 2 overlap boxes https://paste.ofcode.org/jSLLZmrTGXWfpDD2Eja4kU one on throwobject and another on the player it works alright but somethimes game doesnt detect when these boxes overlaped and i have this. if someone knows what the issue is i would be very happy. here the full code: https://paste.ofcode.org/WbmePj6Jh5WYpF7NnspRmi
Use !myList.Any(...
why would you want to use LinQ when a simple for loop will do the same job and is much more efficient?
Either Any with double negative, or All. Linq is very readable, so just think about the logic you're performing
E.g.
itemInfos.All(a => a != b)
All elements don't equal b
!itemInfos.Any(a => a == b)
Not any (i.e. none) elements equal b
foreach(Transform a in transform.Find("App Windows Parent/App Window/Layouts")){
bool found = false;
for (int i=0;i<itemInfos.Count;i++)
if(itemInfos[i].ItemDisplayName = a.name)){
found = true;
break;
}
if (!found) Debug.Log(a.name);
}
or better
List<int> itemInfos
foreach(Transform a in transform.Find("App Windows Parent/App Window/Layouts")){
bool found = false;
for (int i=0;i<itemInfos.Count;i++)
if(itemInfos[i] == a.gameObject.GetInstanceId())){
found = true;
break;
}
if (!found) Debug.Log(a.name);
}
where itemInfos contains the gameObject instance id's so no string comparison
If it was the same object then they could just do normal equality, or walk the hierarchy to see if it's a child
did you see I updated the code?
look at my updated code if you want only objects not in the list
explain exactly what you do want, not what you don't want
but that logic is flawed. it will destroy all gameobjects
the current gameobject will not match at least one of the names in the list
then my updated code will work
guys im trying to learn game development, should i use unity?
If you want, it does depend on what you are looking for
i want to make a VR game.
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
its just hard to choose the game engine because people are saying that ae5 has better graphics and that roblox studio is better for success haha
i like unity tho
Unity is well suited to VR
yeah, what kind of game are you making?
does Roblox even support VR?
first lesson of Game Dev. Learn how to make informed decisions
I have never heard in my life that people actually use roblox for success
if you get like 100 consistant players in your game youยดll most likely earn a lot of money
As stated if you are thinking of coming over to unity you must learn from the link above
ive been coding for about 3 years with lua and ive met a lot of other devs that have made a lot of money
and if that is your main critera you are in the wrong business
i never said that
i just enjoy making games, im just having a hard time choosing. Thatยดs all.
a physics based game with gorilla tag movement
why not?
thankfully c# and lua are kind of similar so ive made 2 simple 2d games in unity the past 2 weeks
what are you making?
oh nice!
dang
that is still not my updated code, it will not do what you asked to do
how else do you expect to check if the name does not appear in the list at all. And if you dont like proper logic figure it out yourself. I'm done
and that from the man who wanted to use LinQ
Btw lua is not C#, but the basic premace is there but you will have to #๐ปโcode-beginner message to get better with unity. You will eventually find what you like and what you dont like.
i never said it was the same
If you are wanting to solely make a VR game then Unity is fitted for it
is there any way of feeding variables into the [Range(,)] attribute?
Values passed to attributes must be constants. So you can make two const fields and put them into attributes (they won't show in the Inspector), but impossible for regular fields/properties
A custom property drawer and attribute could emulate that like Naughty Attributes does, where you pass the names of the variables instead of theire values, and they're resolved at runtime:
public int Min, Max;
[CustomRange(nameof(Min), nameof(Max))]
public int Value;
Do you know how can I draw like in this video with these physical blocks. I created the cells but couldnt think of anything about drawing. https://youtu.be/IEhWPowlS98?si=unlC8LrucSkAR4ue
Recreating pixel/cellular automata based simulations from Noita and Powder toy in the Unity game engine.
Links:
Source code: https://github.com/NivMiz0/Draw-With-Physics-Automata
Play the game: https://nivmizzer.itch.io/draw-with-physics
Twitter: https://twitter.com/NivMizzer
Discord: https://discord.gg/Qj7uDk9Nnc
Mickey (nextProgram)'s channel...
is there a consensus about whether to explicitly mark MonoBehavior event functions as "private" or not?
just in terms of style
Since Unity calls them, and that you're not meant to call them yourself (either from the same class or from another), I'd keep them at the highest restriction level which is private
If you do not specify an access modifier, private is implied
makes perfect sense, but the thing is that if you create a MonoBehavior from Unity, the default code doesn't use "private"
Read the message right above
oh so you're saying just leave it as-is since it's private anyways?
Yep it's a matter of code style, if you prefer it to be explicit or not
the thing is that in normal C# code I use private explicitly everywhere
The .NET convention is to specify
and I think it's almost misleading to call them "private" since they're not really private, they're just called by Unity magically
Unity script files are taken from template files which you can modify yourself
oh neat
h++ mean increment AFTER so, yes, if youj did ++h then h would be 1
you do specifically say 'h=0' do you not?
yes but its the adding at the end
i always forget if i remember it correctly ๐ญ
memoryception
++h has no effect in a for-loop
h would still start at 0
!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.
It's down right now
ah
any idea what might have caused a memory leak on my project? https://hatebin.com/eyefcijmmy https://hatebin.com/johduwatsi https://hatebin.com/syomrgbvpz
it seems the issue is in the first script since thats the one i changed right before it started leaking?
that should be Destroy(gameObject) not Destroy(this)
i guess but its just a precausion anyway
Technically Destroy(this) is also valid, and safer
In case you have multiple components on that GO
im going to try reimporting all assets and see if that somehow fixes it
yeah no that didn't fix it
why dont you try doing what the messages tell you to do?
so this causes the memory leak
What is ChangeColour?
And this also calls GameOver in a recursive loop?
Using . material instead of .sharedMaterial creates new materials
omg
i see it now
Destroying the component is a bit different from destroying the game object. I haven't looked at the code yet but what's their intent?
No clue about their intent as I also didn't look at their code, I only commented on the Destroy part and passing this instead of gameObject
its a singleton so its to make sure there is always only 1 of them in scene
i think both destroy this and gameobject work in my case
You'd probably want to destroy the game object if you're using Singleton pattern unless you're just wanting to destroy the script and not the game object.
yeah it was that, i fixed it now thank you
i had no idea that would cause a memory leak though wow
Umm how would a script a teleport script when it is clicked with hand tag, I have no idea how to script so if someone could please teach me it would be a pleasure.
I have a Quaternion.FromToRotation() that is used to rotate an object along the z axis, but when the object has to rotate 180 degrees it instead rotates along the y-axis. Is there a way to make it always calculate the rotation around a specific axis if possible?
Could first get the angle around that axis with Vector3.SignedAngle and then use that angle to rotate the object
IPointerClickHandler seems more so for OnRelease, rather than click itself? 
I've just started using Unity.Netcode in a script. But Unity complains about the namespace not being available. I've doubled check that NGO is installed, I've already put some network script on go.
Does anyone recognizes the problem ? Unity hints to reference an asmdef but none are available for Unity.Netcode. (Though there's com.unity.netcode.editor but that seems to be internal)
asking some guides again for this
in my code the tower that detects enemy can only detect one game object so im planning to make an array so that every game object it detects within range can be detected and have those values transferred to another tower
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yup! You can do: string[] s = myTMProTextReference.text.Split('\n');
\n is actually a character, not a string, and represents the beginning of a new line in text
thanks
you can swap '/n' with System.Environment.NewLine which is more correct for multiplatform, but in Unity splitting by \n will always work.
okay
Hi, can someone tell me what am I doing wrong? I want to use scritable objects for a card game to assign different effects to cards easily.
Then in my card script, I want to assign the effect in Inspector
However, I can't drag and drop the effects in
I simply have public effect cardEffect
where is the created scriptable object?
Nevermind I have smooth brain
I'm supposed to create the scritable object via the asset menu
Not directly drop the .cs script in
hello, i was using the camera normally but now i cannot scale it somehow. Why is that? Im using a canvas for my text
i want to scale my camera because some objects that arent text or buttons cannot be seen for some reason
you should scale your objects then, not your camera
your objects are too big and outside of the camera's view frustum. that white rectangle you see around all of the objects is the canvas which is for UI. that tiny white rectangle that is in the center of the screen is where your camera actually is
also not a code question
Hi I need help. Why I can't see it in inspector?
Item is not serializable, you need to mark it as such to be able to serialize it and edit it in the inspector
the struct or the list?
the struct which is the only thing here called Item
still nothing or I'm probably idiot
did you save the code and recompile?
wow it looks so weird inline with class definition, unlike SerializeField
(don't mind me just randomly seeing something like this for first time lol )
It is normal for me. Idk why it is happening
yeah i mean still functions the same, just looks freaky instead of above it. Anyway ๐ ๐
for some reason public GameObject[][] enemiesInWave; won't show up in the inspector
unity cannot serialize multidimensional or jagged arrays. you could create a struct that has a GameObject array and use an array of that if you need to
Unity will not serialize jagged arrays
[Serializable]
public class Wave {
public GameObject[] enemies;
}
public Wave[] waves;```
I would recommend this
oh so how do I do it?
ah I see
I'll try doing this
problem is enemiesLeftToSpawn = enemiesInWave[currentWave - 1].Length comes up with an error
(I changed waves name to enemiesInWave)
you need to access the array variable inside that object
do you initialize your arrays?
how do I do that
the same way you access any variable on any object. using the . operator
remember your array does not contain arrays but rather your class that itself has an array
what
to use praetors example
waves[i].enemies.Length
comes up with what error?
It's important to read and understand the error message, rather than just seeing "error" and guessing
ooooh ok I get it now
thank you everybody who helped me ๐
you could also just make a property Length in Wave that returns enemies.Length
{
while (RTL.hasPassedArea == false)
{
gameObject.transform.up = player.transform.position - new Vector3(0, +4.5f, 0);
yield return null;
}
}```
this is my function that makes my light point at the player however when i reach the end of the level and the next scene loads the light in that scene is tracking me but pointing the opposite way as if its reversed
Why are you using a hardcoded position on the right side of the subtraction?
why not:
transform.up = player.transform.position - transform.position;```
true ill give that a go

apologies if this is the wrong place to ask this. I've used QualitySettings.vSyncCount = 1; but I can't find like a visual way to see if it's working. How can I check? The line of code doesn't seem to affect the VSync checkbox above the editor window no matter what I do.
When you do that, the FPS will be fixed to your current monitor's refresh rate
Alternately you can make a few tall cubes whose color contrast with the background, and wiggle your mouse left to right. If you can't see any tearing along the vertical lines, VSync is active
So theres two things that i dont understand currently. First of all, i dont know what i did but after editing this script and running the Game it freezes the entire thing. Also, I want to make it so that every time timer or timerA hits zero it spawns a gameobject at the random x and y coordiantes. However when testing all the Prefabs spawned at one coordinate instead of a random one.
public class GameManager : MonoBehaviour
{
[Header("COLIN")]
public int maxSprites = 8;
public int currentSprites = 0;
[Header("SCORE")]
public int currentScore;
public float timer = 3;
public float timerA = 3;
[Header("AYBARS")]
public int maxAybars = 3;
public int currentAybars = 0;
public GameObject Colin;
public GameObject Aybars;
public StatsManagerScript statUPDATE;
Vector2 spawn = new Vector2(Random.Range(171, 215), Random.Range(380, 300));
void Update()
{
timer -= Time.deltaTime;
timerA -= Time.deltaTime;
while (currentSprites < maxSprites)
{
if (timer <= 0)
{
currentSprites++;
Instantiate(Colin, spawn, Quaternion.identity);
timer = 2;
}
}
while (currentAybars < maxAybars)
{
if (timer <= 0)
{
currentAybars++;
Instantiate(Aybars, spawn, Quaternion.identity);
timerA = 2;
}
}
} }
what do you think this does
while (currentSprites < maxSprites)
{
if (timer <= 0)
{
currentSprites++;
Instantiate(Colin, spawn, Quaternion.identity);
timer = 2;
}
}
So i ASSUME it does is: Whenever the timer is below or zero, the variable currentSprites adds 1, it Instantiates a Prefab (Colin) at the "spawn coordinates" which is a Vector2 with 2 Random.Range values, and it instantiates the prefab (Colin) with its original Rotation value and sets the timer back to 2
ok, what is the value of timer the first time it executes
3 if im not mistaken
3 - deltaTime to be precise. So how is currentSprites ever going to increment?
as the code is in the Update() function i thought that timer decrements every real time second until it hits zero and is then set back to 2
or are you saying it isnt going down at all?
but you are in a while loop, not the Update loop, it never exits it once it enters
Execution enters the loop. Timer is greater than 0, the if is skipped, and the loop's condition is evaluated again. currentSprites hasn't changed so the loop continues. Timer is still greater than 0. The if is skipped. Repeat, infinitely. Your game freezes since your code never ends.
Unity will not render a new frame until all of the code has finished executing.
oh ok that makes sense, so the timer variable is always 2?
no, it is always 3 - deltaTime
ah ok
and the while cannot exit
that should probably be if statements not while statements
im going to try to implement something else with my code regarding this thank you so much in advance
Ok i changed the conditions into the if statments alone and it worked thank you guys! However im still kind of confused about the random.range Vector
see pinned messages in #๐ปโcode-beginner
oh this is great thank you
I could be entirely wrong as to what you mean by this, but I can't really seem to spot a difference.
Try a standalone build, the editor might apply its own settings
Is it possible to make a GameObject-variable except the variable only accepts a specific prefab or variants of that prefab?
that totally fixed it thank you so much!
You want to make a field that accepts only a particular game object? Have the field be of that specific type. Not sure how you're going to restrict it to prefabs only or component references only though..
This is just stupid, it's giving me a thousand errors and i don't see anything wrong with it, and guess what? It wasn't giving me errors for this same thing before.
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class Rafael : MonoBehaviour
{
public Rigidbody RafaelBody;
public int RafaelSpeed = 3;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A))
{
RafaelBody.velocity = Vector3.left * RafaelSpeed;
}
if (Input.GetKey(KeyCode.D))
{
RafaelBody.velocity = Vector3.right * RafaelSpeed;
}
if (Input.GetKey(KeyCode.W))
{
RafaelBody.velocity = Vector3.up * RafaelSpeed;
}
if (Input.GetKey(KeyCode.S))
{
RafaelBody.velocity = Vector3.down * RafaelSpeed;
}
}
}```
What's the first error?
you have a duplicate script
that is what duplicate means, yes
of course I am
Is anyone able to help me with a clamping issue?
if (isRotating)
{
currentMousePosition = Input.mousePosition.y;
mouseMovement = currentMousePosition - startMousePosition;
transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
startMousePosition = currentMousePosition;
}
I know I could track the values by using transform.localeulerangles.x but I don't know how to store the angle since I can't do transform.localeulerangles.x = MathF.Clamp ~~~~
I want to track the angle of the shape that's being rotated
then clamp it so it can't go past certain angles
Ok
