#💻┃code-beginner
1 messages · Page 484 of 1
eventSystem.current.IsPointerOverGameObject() always returns true
i mean makes sense, in a game engine i always hover over a gameobject
means you have a random image/graphic blocking the screen
no
EventSystem only works on UI
it works with layers, has nothing to do with ui
just on a note. EventSystem can work on colliders if you use PhysicsRaycaster / Physics2DRaycaster
thank u
i didn't know that before
you just add this component to the camera and you can get all the EventSystem methods on colliders, like OnPointerEnter etc
ah yeah i removed it and now IsPointerOverGameObject works only with ui
i thought wtf this function is useless in a gameengine 😭 because you always hover over a gameobject hahah
show where you put logs
What runs this code
vsc c#
well Console.WriteLine wont work in unity btw
i know
so how you know those cases are hit ?
ive been trying to run this on for 3 days now
that's not what I asked
It's very clearly C# because it's Unity
what actually runs this code
where is it
Uhm idk which channel to ask something about converting a unitypackage to fbx, where d i ask?
which gameobject is it on basically
Okay, what function is this in
you don't convert unity packages..thats like saying convert zip to .jpg
you cannot 'convert a .unitypackage to a .fbx
unitypackages are opened inside unity
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
so i was coming here to see if anyone could help me with it
i tried sumthing simple
Why are they static
default
oh lord
static ????????????
No, they aren't
The only way those would be static is if you made them static
So, why did you do that?
Are you intending to call these functions yourself? If so, where?
help what exactly ? what are you trying to grab
even if i emove static, problem persists
the problem is my console doesnt display outputs
it displays errors
there is still a static in there
i downloaded all packages
What object is this component on
uuhhm its a splatoon lightstick , and i was hoping i could use unity to make it import to roblox and roblox only uses fbx 💔
no code there
main camera
Show it
how do i show it
Screenshot
i dragged it there
like you've done multiple times already
how do i sho a drag tho
Show the object
with the component on it
unsure if this is what you mean
Okay, now, did you actually run the game
why cant you install unity real quick? importing a package wont be much processing power
play right?
oki
yes
Show a screenshot of the game in play mode, with the console open, and this object selected
Okay so the reason it wasn't printing is because you literally did not start the program
didn't think I'd ned to have explained that
sigfh thats the thing i tried again and i still have parental controls from years ago bcs this ia old pc 💔
It took you three days to think of "run the game"?
yes
i was searching every website for a solution and they all talked about the box
checking message box
"years ago"
well idk then lol reinstall the OS ? pretty sure you could bypass that if you just wipe it from bios / usb setup
Then you were mistaken
hey, the simple code was executed. When I changed my code, it was still attaching itself to the previous code.
You also have to save the file
no
wait ill try to restart
r u a beginner too or just a saint trying to help beginners
what makes you think hes a beginner?
the channel name
that doesnt mean he is?
i helped many people in blender when i was still a beginner man
so i thought
maybe he is as well
some people are beginners yes, some people are advanced, everyone is different but they can all still contribute in each channel
alr
im not mad?
why would i be
please use links for !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.
Is there a way to make a player can't press two or more specific keys at the same time? I coded it but doesn't work.
try using else statements
what are you trying to avoid here?
directional movement?
if(
else if(
What doesn't work about your code
Looks like it should work fine
Unity doesnt detect an error, but the code doesnt work
What doesn't work about it though
how are you validating it's not working
THere's no "error" that Unity would detect
Did you populate the restrictedKeys array properly in the inspector?
Make sure that its not a hardware issue also. Like a bad keyboard having trouble detecting multiple keys
Note that your code only does Debug.Log when a key is pressed. It's going to be hard to tell if it's working from reading these logs since they will fly by so rapidly each frame
One way to check if this is working:
private void Update()
{
CheckRestrictedKeys();
if (!areKeysBlocked)
{
Debug.Log("Doing movement");
HandleMovement();
}
else
{
Debug.Log("Multiple key presses detected. Not moving!");
}
}```
That will be a bit more readable than what you have right now
You'll want to make sure Collapse is turned off in your console as well
Greetings everyone,
I can no longer drag files into my Unity Editor Project folders to import new sprites or any assets. When I do so the circle with a slash through it appears.
I can import assets manually by right-clicking on my Project Folder.
I believe the project may be starting in admin mode, but I can’t figure out how to prevent it from doing so.
-I uninstalled/reinstalled Unity entirely, and the same issue is still happening.
-New/old projects do not have this issue
-I did drag an asset directly into my project directory rather than through the editor. The bug has been present ever since, but I do not know if that is the issue
-The project was synced with Google Drive, but I have unsynced the project
-I have tried duplicating the project entirely, but the error still occurs
At this point, it seems like only one project is stuck in admin mode or something else.
Does anyone have any ideas?
Could there be a startup/temp/main script that needs to be manually changed?
Is there a way a single project can be started in admin mode?
try making new project that works, then import the broken one as a unitypackage, see if that works
Ok, let me see if I can figure that out. Thank you @rich adder
basically everything in your Assets folder goes into its own Folder like "projectxyz" then on the unity export package window just select that folder so its all inside there neatly
So I need to export my previous project first? Or, does this automatically happen and that's how Unity organizes it's internals?
get the blank project working to where you know the files import properly, then go to ur broken project and create a folder inside Assets whatever name you want, put all your asset files in there so easier to export as 1 folder. You might have to match the projectsettings
Great documentation! I'll get to work on this real quick and post back soon
Lol, I tried to import my asset package from the Package Manager...
Glad the documentation had the next step in the process.
importing now
Looks like I need to update the renderer and input controller but aside from that it has worked!
Thank you for the help @rich adder !
Yes, I'm quite curious as to what actually created the bug
whats the last thing you did before it broke?
It occured right after I tried to backup the game to google drive so I could work on it via laptop over vacation.
oh how did you back it up ? like some type of file sync or something
I didn't REALLY see anything happen right away. But after two weeks on vacation, when I returned home and tried to drag in some new sprites I created, the bug was present
weird..maybe it was just library folder that needed deletion n rebuilt ? worth a try ig
Very roughly lol. I use Google Drive on my computer and have a shared drive directly synced. I gave permission to also sync the google drive to my game project folder (which now I see would of been smart to make a copy since this is the first test).
I was essentially trying to make a simpler version of Unity Version Control where I didn't have to check-in changes every time
I'm willing to give that a try. Do you have any documentation on how to go about that?
oh dam..just use git. I would not trust any type of filesync software like drive or onedrive , they might mess up your file structure or permissions
there is nothing to it, close the project delete the library folder. Open project again, let unity rebuild project, open old scene
Yes, I need to learn Git.
Desktop version was pretty friendly.
Apparently it does mess up the file structure lol
yup, once its connected repo you're just pressing 1 button / writing description
Ok, I have a copy I made for debugging this issue. I'll try the 'library replacement' method now
yup. Library folder is harmless(mostly cache files), that's why we don't commit to it via GIT / vc n its bulk of size
trying to declare a scriptableObject that ive already made, in my last code (dumpsterfire to be fair) this exact line works but here SO doesnt exist
ive probably forgotten a step
where did you declare SO class
you need to set it in the inspector of the script
yeah ive done that
Ah yes, I do recall reading that it isn't needed to share the Library folder when sharing projects.
Opening the Library-less project now
not sure what you mean
im basing this on the old satan child of a script we made last time
where is SO class defined
ive only declared SO here
what you shown, no you declared a reference to SO
your scriptable object script
OOH WAIT
where did you define you class
SO is horrible name yes
i assumed SO was shorthand for scriptable object or something but thats
literally what i named it yeah
fixed
nahh scriptable objects are just like any other classes, that's why we define them as public class SomeSOScript : ScriptableObject
they just have some special functions in unity
The Library rebuild method was unsuccessful.
in what way?
I cannot drag in new sprites. The bug still persists
hmm yeah idk.. its possible something else that isnt in lib maybe..project settings ? 🤷♂️
as long as new project works 😆
can you make a video
Scrolled through there twice. Couldn't find anything.
Surprisingly struggling to make the video lol
As a note, I have successfully dragged a few of those sprites into other projects
The problem would appear to be with you picking up, not dropping into Unity
Do elaborate please?
This method works fine with other Unity projects
Elaborate what? Is the image not sufficient to show the item has not been picked up correctly?
dragging and dropping works fine into other projects. It doesn't work for this one
Also I'm not sure what your Unity Assets folder is but it seems rather odd
Unity does not play well with these types of follders
That's why I also showed the download folder. But definitely learning it doesn't link the sync files that much
Here is a video of me doing the same thing with another project
It is strange that the circle with the slash comes out of Unity and into my file explorer when I have the bugged project as the second window open.
Note, the bugged project is currently open and running in the video when I made this video and successfully dragged in the files to Unity Edititor in the new project.
the google drive one probably messed up folder permissions and unity is reading whatever permission was set
Defintely agree there
I can't figure out how to adjust the permissions for the Unity project though
I've tried a few different methods but permissions are not my forte
Recap in case it helps:
-I uninstalled/reinstalled Unity entirely, and the same issue is still happening.
-New/old projects do not have this issue
-I did drag an asset directly into my project directory rather than through the editor. The bug has been present ever since, but I do not know if that is the issue
-The project was synced with Google Drive, but I have unsynced the project
-I have tried duplicating the project entirely, but the error still occurs
difference is here, you are copying a folder not a file
folder works fine in other projects though/
copying over the whole thing that is
The issue in the bugged project seems to be when I synced it with Google Drive
Even after unsyncing it, the permission seems to be messed up.
Now I cannot 'read/write' new files into the project
Any thoughts on how to reset the permissions?
Hello, guys! I have a problem you know. So, I am making currently a horror game. So, what I want to make is when the player collects an item to change the task, so somehow I have to connect tasks with items inside my game. At the start of the game, I have a key inside the house, and when I am taking that key I want the first task to change.
This is my interaction method, so when I press the E button I am collecting the item.
Interactor.cs
{
Ray ray = new Ray(interactionSource.position, interactionSource.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, interactionRange))
{
Interactable interactable = hit.collider.GetComponent<Interactable>();
if (interactable != null)
{
interactable.OnInteract();
StartCoroutine(DisplayFoundItemText());
}
}
}```
and
Interactable.cs
```public class Interactable : MonoBehaviour
{
public virtual void OnInteract()
{
Collect();
}
public void Collect()
{
gameObject.SetActive(false);
}
}```
Something like a task/quest system I ve never done that before very unfamiliar with that
hello, so I did nothing but test my game, and suddenly the editor started taking up EVERYTHING
any idea why
like the game lagged suddenly and when I looked the editor decided to eat my game
I also get this error
and this one
Hii
restarting the PC seems to have solved the problem
anytime you see UnityEditor in the stack-trace.. just assume it'll be fixed with 1 of 3 advancing steps..
- Reset Layout(s)
- Reset Unity
- Reset PC
then for extra credit:
*. Delete ** \Library\ ** folder
its possible make the particles dont flip when the player jump?
use position constraint instead of parenting
yeah I'll keep that in mind
how can i do it?
I'd ask why are you making geometry dash but, you shouldn't parent the particles to the cube
put position constraint component on the particles
Particles can be emitted in world space (a setting on the particle system), so the emitted particles don't follow the object they were emitted from
Requires no code or hierarchy changes
It kinda looks like it's in local space, but previous particles stay where they were when the character rotates, so I'm a bit confused
that is if they don't want the particle to follow, i bit confused if they meant just rotation or pos too lol
I think the particles are parented to the cube
Looks like it's already in world space tbh, but the emitter shape (Shape module) is rotating with it
Yes I'm assuming that too
I think you'd just have to unparent it and then either use a position constraint (although I've never used one) or make a simple script that says
yourParticle.transform = player.transform - offset;
in some update
because parenting changes the position and rotation of the object and I'm assuming @tranquil hollow want's to move it along with the player and not rotate
@verbal dome btw I heard parenting isn't allowed for multiplayer games, is that true?
ty
You can but its complex because of ownership transfer
Probably depends on the networking package you are using, I'm not the guy to ask about networking though
netcode for example handles it this way
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
notice how its in "Advanced topics " 😛
working on this myself (have a CTF project)
Netcode docs look pretty good 👀
yea! we actually have header tags that work here
link to specific sections . wooo
I use the same documentation software, I believe its Docusaurus
guys i need help my camera is not working properly basically it is showing something else in scene view and something else in game view and my scripts arent the reason because i disabled them and the issue is still there.
what is different ?
its like going on top of the character's head instead of being infront of it
Type t:camera in the scene hierarchy search to see if you have an extra camera
maybe you have 2 cameras?
I checked and there is no camera other than the main camera
Is there an Animator involved?
wait u were right
there were 2 cameras
idk how but when i typed camera in the hiearchy i found 2
thx guys
Anyone fancy helping me with a script
Just ask your question
I need a script where the zombie will play attack animation when in range of player
You need? This server doesn't do handouts.
!learn how to use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
and learn the animator system
check the distance between the two or use a Collision message or a Physics.Overlap...
im not sure where to start when making a scrolling text effect
im not sure how to explain the effect well but i mean like whats in undertale when any text shows up and it slowly reveals itself
parent it to a transform and animate that right to left then back again
typewriter effect?
you can loop through each char in the string and add delay between
that makes sense thanks
use a coroutine with and the maxVisibleCharacters from TextMeshPro. you can find a tutorial on it . . .
i ended up doing that
i would have searched myself but diddnt know the name of the effect so could not
Hi
how do i make my player fall when he is descending the stairs for example
I mean the player falls but very very slowly
the reason your player is falling right now is due to the rigidbodys default gravity settings. id toggle use gravity off and control what you want it to be yourself. right now you have no control over it.
check the slope of what the player is on, then set the velocity accordingly
can anyone point me to why this script is preventing me from rotating the camera?
void Update()
{
Vector3 offset = new Vector3(distance, distance, distance);
transform.position = player.transform.position + offset;
if (Input.GetKey(KeyCode.Q))
{
transform.RotateAround(player.transform.position, new Vector3(0, 1, 0), rotateSpeed);
}
if (Input.GetKey(KeyCode.E))
{
transform.RotateAround(player.transform.position, new Vector3(0, 1, 0), rotateSpeed);
}
transform.LookAt(player.transform);
}
The camera should orbit around the player when you use Q and E, but instead while pressing Q or E it temporarily moves the camera rotateSpeed degrees (3 in this case) around the player, and then returns to its original position when you let go
The first two lines should be in Start, and the camera should be a child of the player object so that you don't need to set its position manually
but wouldnt making the camera a child of player also associate it with the players roation?
I want the player to be able to rotate independently of the camera
I might have forgotten to say that lol, it's late 
The hierarchy is usually like this:
- Player container
-
- Player model
-
- Camera
You move the player container and rotate the player model
hmmm, ok yeah. I did think of that but said what I have works and went with it. I'll try rearranging it
oh lol thanks for pointing out the Start thing, I didnt notice I was dumping new vector3's everywhere in memory
That's not a problem
Oh so that isn’t leaking memory?
No, vectors are structs
Oh wait it goes out of scope every frame and I guess gets cleaned up
if I have a reference to a class with data and a variable with a new instance of that same kind of class.
is there a quick way to copy over the variables or do I have to set them one by one?
if I just set the new instance to the data it'll change the original data if I change variables in the instance which I don't want.
the quick and dirty way is to serialize the original and deserialize into the duplicate, otherwise you will have to implement your own Cloning method which is field by field
cloning method it is, could just make a constructor that takes the class itself in as a parameter now that I think about it like that.
indeed, that is a standard implementation
remember you have shallow and deep copy options.
Shallow copy creates new primitives but leaves the references
Deep copy creates both new primitives and references
may sound stupid but how do i use oncollisioneenter2d too do smth like this
OnCollisionEnter2D and read the docs
Also, do NOT nest methods
Oh jeez, didnt even see that 😄 yeh, rare case of local nested methods 😄
which is gonna be a problem seeing as temp is a local variaible, so basically the whole code is nonsense
this is all i could gather
Maybe read, what Steve wrote abot NOT nesting methods like this
btw temp is a terrible name for a variable. Try to make your names meaningful
just realised it should be a boolean too
How can I scroll sprite renderer objects left and right like we use horizontal ScrollView for Canvas with images?
Integer works too, but if you're just checking a true/false/yes/no ish value without more states then a boolean is obviously preferred
Though usually you'd use an enum then (with more states)
i got this although when i click lefthshift nothing is printed in the terminal
lol
didnt call it
What would be a smart approach to outline the edges of a polygon prism? Using a linerenderer or a shader
Just use an outline shader, there are a bunch of them, easy and efficient.
Also free outline shader asset on the store so it's easy to get.
Unless you mean not the outline but the actual edges between vertices?
Actual edges
📃 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://gdl.space/efecorudiq.cs
I want to make a mechanic to clean objects. This code works on PC and when I connect the VR to the PC, but when I build it in the VR it doesn't do anything. any idea why it happens.
Is it feasible to use Unity's Animation Editor to flip sprites on the x-axis?
I rigged up a couple animations doing this but the 'flip x' stays engaged even when an animation is triggered where it has been turned off.
Seems like I need to flip x again but that doesn't really work in the animator.
Is this why I see most people flipping sprites with code rather than the GUI or am I doing something wrong?
Did you debug it at all?
I don't know how to debug the VR build
It's android(presumably?), so you should be able to attach a logcat to see the logs.
Also, should be able to attach the debugger.
No, not really, I just knew they existed, and that screenshot is from a free github version one for Unity.
No clue if that's a good one.
Is there a way to see if I have correctly created two submeshes? I'm trying to set materials in the meshrenderer and it doesn't work, so I want to see if my submesh algoritm actually generates submeshes or not
IIRC you can see that when you look at the mesh inspector/properties
Yeah here:
Yea it says I have two submeshes
Any way to see them seperately?
Or the mesh logic doesn't work like that idk
Not sure how to do that without assigning materials to a mesh renderer
You can show your mesh !code and I can take a look
📃 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.
int[] frontFaceTriangles = new int[(sides - 2) * 3];
for (int i = 1; i < sides - 1; i++)
{
frontFaceTriangles[(i - 1) * 3] = 0;
frontFaceTriangles[(i - 1) * 3 + 1] = i * 2;
frontFaceTriangles[(i - 1) * 3 + 2] = (i + 1) * 2;
}
mesh.subMeshCount = 2;
mesh.SetTriangles(triangles, 0);
mesh.SetTriangles(frontFaceTriangles, 1);
It generates a polygon prism based on sides and radius before that
This code is supposed to seperate the front face and the rest into submeshes
Also, just FYI, unity has a wireframe view if this is not something you want to ship with your game, but just to debug.
Cause it seems like you are debugging things atm.
Not just to debug. I wanted my prisms to look sharper
I have some wireframe shader in my project, IIRC it comes from some HDRP sample or something - I can take a look in a moment
Just FYI I don't want to see through my prism
I just want my prism's edges to be outlined/highlighted
See if you have this shader:
Is it see through
No
It does change color based on distance though, I didn't remember it does that
Yeah probably not useful since you can't really edit it
Could replace lines 132-134 with a solid color for the wire instead, since you don't need the distance-based coloring
how can i solve cinemachine lag in 2d
ok
I need to reference the z rotation of an object in script, but whenever i try to it goes to a value between 0 and 1 instead of the value it is in the inspector. How do i get the inspector value instead
Because you're trying to read from a quaternion
you do not
what you see in the inspector are the euler angles, not the actual rotation. however you also don't typically want to use the euler angles for logic because they are interpreted from the quaternion that actually represents the rotation at the time you access them. you would be much better off manually tracking the rotation by keeping a float that represents the current Z rotation and read that and also use it to assign the rotation
But yeah trying to get the inspector value is a bit of a fool's errand. It's better to use something like Vector3.SignedAngle, or track it yourself yes.
{
while(inMainSequence)
{
var heliumPush = Instantiate(Helium, UICan.transform);
heliumPush.GetComponent<Rigidbody2D>().AddForce(Random.insideUnitCircle * heliumSpeed, ForceMode2D.Impulse);
yield return new WaitForSeconds(heliumSpawnRate);
}
}```
im using this to spawn a sprite and then propell it in a random direction inside a unit circle however the problem is is that it doesnt launch at a consistant speed each time because it doesnt propell it in a random direction on a unit circles edge. so how would i fix that
normalize the Vector2 returned by Random.insideUnitCircle
kk ill give that a go
Hi, I'm trying to make camera rotate during a wallrun, but it always rotates towards one direction (presumably towards 0, 0)
private void Update()
{
CheckForWall();
WallrunInput();
if(Input.GetKey(pm.jumpKey)&&!pm.grounded&&pm.readyToJump)
wallJump();
if(isWallrunning)
{
playerCam.transform.localRotation = Quaternion.Euler(playerCam.transform.localRotation.x, playerCam.transform.localRotation.y, wallrunCameraTilt);
orientation.transform.localRotation = Quaternion.Euler(0, 0, 0);
if(Mathf.Abs(wallrunCameraTilt) < maxWallrunCameraTilt && isWallrunning && isWallRight)
wallrunCameraTilt -= Time.deltaTime * maxWallrunCameraTilt * 2;
else if(Mathf.Abs(wallrunCameraTilt) < maxWallrunCameraTilt && isWallrunning && isWallLeft)
wallrunCameraTilt += Time.deltaTime * maxWallrunCameraTilt * 2;
if(wallrunCameraTilt > 0 && !isWallLeft && !isWallRight)
wallrunCameraTilt += Time.deltaTime * maxWallrunCameraTilt * 2;
else if(wallrunCameraTilt < 0 && !isWallLeft && !isWallRight)
wallrunCameraTilt -= Time.deltaTime * maxWallrunCameraTilt * 2;
}
}```
!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.
playerCam.transform.localRotation.x, playerCam.transform.localRotation.y```
these x and y on the quaternion are NOT euler angles and you cannot use them as such
you're putting a square peg into a round hole here - it's meaningless.
rotation and localRotation are quaternions, they are not euler angles.
hi, if anyone has spare time can you help me while I'm sharing the screen?
you would be much better off just !ask ing your question here and providing any relevant screenshots/videos instead of expecting someone to privately help you with a screen share
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
!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://gdl.space/acipatosul.cpp
https://gdl.space/menawuqowu.cpp
Yo, I have these 2 codes, the top 1 is basically the Unit for the stats and numbers for the player and the enemy and the bottom is the battle system script for my turn based combat game, I'm trying to write each enemy a diffrent behavior in a unique script but I dont know where to start. any help?
like I just need some guidence to how I start
Start what?
how do I code a unique behavior to each enemy
Like I have the enemy prefab
and all the diffrence I can make between each enemy is the stats numbers
via script component
Well. There are many different ai techniques and algorithms with different level of complexity.
What kind of unique behaviors should they have/?
I mean, I have no expirience with AI at all but the thing is I'm not sure how do I even change the enemy's stats from the other script
like If I want to create new attacks / skills for them. I dont know how to attach them
You need to actually know how you want your AI to behave, in plain english, before you can start actually figuring out how to create it.
You either have separate objects in these scene or prefabs that you assign the different stats to. Or maybe implement a system that does it procedurally. There are many ways, depending on how you want it to work.
This is details of implementation. Once you have the desired design down on paper, it shouldn't be too difficult to implement. Though I guess it depends on the complexity of your design.
I just want to know how do I change their behavior manualy before I get into AI
Just hardcode it.
For example I have this enemy prefab and I added a goblin script, and lets say I want him to heal every time he gets lower than 50% hp
or like just have to options and choose at random
I just want to learn how to do that before I get into AI in general
if hp < maxHP * 0.5f
heal
At the very basic level, something like that. It's all very basic coding.
yes I know but I mean like
I want it to be diffrent for each enemy
and I dont know how do I do that in diffrent scripts
hardcode different behavior for each enemy
Have different scripts do different things?
Wdym? What's the problem?
so like I created a script called GoblinScript right here, and lets say I want to write instead this script the goblin's behavior
how do I attach the behavior from that script to the battle system
Reference the goblin script from the battle system script and do whatever you're needing to do with it.
what does the battle system do?
its like the battle manager
What does it do?
it controls the state of the battle like who's turn it is and what options do I have
And what's it's relationship with the ai behavior?
and it has a few method for player skills
And what's it's relationship with the player?
You realize, that we can't help you with things specific to your project, unless you provide details on them?
I mean the code is here, but in general the battle system is responsible for making the attacks deals damage / heal and in general just every action that in the battle goes through it
and its contains the methods for the enemy's and the player's turn
and what happens in those turns
Then call the enemy's methods. And each enemy behavior script would provide a different implementation. As easy as that.
Lets say I want to create inside the goblinScript an EnemyAct method that inside that method is what is the enemy is going to do in its turn
Make Unit a base class, and implement it for different behaviors. For example public class GoblinUnit: Unit. Each of such classes would implement their own TakeDamage and HealHP behaviors.
how can I attach it to the battle system without refrencing the code
You have to reference it somewhere.
I mean
if i'll have like 100 diffrent enemies I'd have to refrence a 100 differnt behavior codes?
and even if I do that how do I know which behavior method do I choose?
a 100 if statements?
No. Only the one specific enemy you're processing.
They would all implement the same methods. Just provide different implementation
Only the different enemy types would need a new script. That's very normal for a game
A HealerUnity for example would heal it's alies in Act method. An AttackerUnit would attack the enemies. And so forth.
I think this is a good opportunity to go and learn OOP. Once you get it, it would be a piece of cake to implement what you described.
what is oop
can I get all of the enemie's script in an erray?
then just like use the one i need each time?
No. You probably shouldn't do that.
like a library i think its called
Learn oop, and you'll see how easy it is to solve your problem.
what is the refrence to Pos x i cant find it
tbh I dont think u still completly understand me but maybe there is something I dont know yet that could solve it
I do understand you completely.
In your battleManager you'll have something like:
IEnumerator EnemyTurn()
{
foreach( Unit enemy in enemies)
enemy.Act();
//....
Then you'll have a base Unit class:
public abstract class Unit
{
public abstract void Act();
}
Then you'll have many derived classes, for example:
public class Goblin : Unit
{
public void Act()
{
//goblin turn logic
}
}
And for example another different behavior:
public class GoblinHealer: Unit
{
public void Act()
{
//goblin healer logic
//heal it's alies
}
}
aight then I'll stick to that example just need to learn wha foreach and abstract class are
I'd suggest going over the C# basics, if you don't know what these are, before trying to continue your project. You can't get far if you don't know how to code.
all i know about c# is from school
hello , can i add a box collider to a UI image ? and then use onmousedown ?
i don't wanna use buttons
which isn't the best way to learn I guess
if you dont wanna use buttons, use eventsystems like this https://docs.unity3d.com/2018.2/Documentation/ScriptReference/EventSystems.IPointerDownHandler.html
not box colliders
Doesn't sound like enough if you don't know the things I mentioned.
The website I shared earlier is a good start. The C# manual could be useful as well, although it's easy to get lost in it as a beginner.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/
I guess you are right
The fact I got pretty good grades in my finals and still dont not shit about c# means something
how do i refrence Pos X of rect transform
maybe about me or maybe about school idk
thanks i appreciate it , but what's wrong with onmousedown ? used it in a match-3 game where the items have box colliders and it worked fine
i was just asking this time because it's a UI element
hi, im trying to learn and implement ml agents in unity
so does it matter if my pythons version is 3.12 whereas the ml agents documentation stresses on the fact that i should have 3.10.12 instead?
i just wanna confirm
Honestly, you don't need school to learn programming and/or gamedev. And just learning at school is not enough to make you a programmer/gamedev. The most important quality of a dev is being able to constantly learn and improve yourself.
anchoredPosition I think, but don't quote me on that. Check the docs.
Because UI elements don't combine good with physics. Both of the systems can modify the object's position which is gonna mess with the other system in various ways, for example.
Hard to say. There might a compatability issue of some dependencies. Try it and see for yourself.
oh i see , UI aside should i start using IPointerDownHandler for nonUI gameobjects too ?
You don't have to, but in my opinion it would result in cleaner and more consistent code.
Though, if it's for mouse interactions with scene objects, I'd still raycast manually from a script, just to have more control over it.
i tried using raycast but honestly too complicated for my 2 brain cells
so i just been using box colliders + onmousedown
can particle systems block buttons from being clicked
Depends.
Are these UI buttons? Is the particle system parented to the canvas and has graphic component/s?
they are UI buttons and the particle system is attached to the button
Normally, it shouldn't interfere. Though, you probably shouldn't have a particle system in the ui anyway.
Here's a question. I've heard that Physics.CheckSphere is bad. is Physics.OverlapSphere and Physics.SphereCast bad too?
None of those are 'bad'. They all do different things
I remember hearing something about it looping through all colliders in the scene. Is that true?
CheckSphere when you need to know if anything is hit, but don't care what it is
OverlapSphere when you need to know each collider that was hit
SphereCast is just a thick raycast
That's just wrong. Unity uses Nvidia PhysX as the default physics engine and the people who made it have optimized it pretty well
those are localized checks, aint no way its going through all colliders
There's some spatial structure that allows the engine to only check for nearby colliders
Wow, okay. I've been scared of 3D for no reason then...
not surprising , premature optimizing kills any project early
one thing to note , for the Ovelaps or the ones that return more than 1 result then you absolutely should be using the nonalloc version of it.
The performance gain is actually incredible if you saw the profiler, ofc allocating a new array is more expensive than having a fixed one ready to go
Wow. Good to know. SphereCastAll would also return more than one, right?
correct
you should use https://docs.unity3d.com/ScriptReference/Physics.SphereCastNonAlloc.html for example
Alright. I can't seem to find one for SphereCastAll. Only a nonalloc for SphereCast
thats cause if its non-alloc its returning usually multiple ones
thats the whole point of prefixing the array with length as field
SphereCastNon alloc is SphereCastAll without alloc lol
basically you would declare how much you want allocated for example
private RaycastHit[] results = new RaycastHit[30]; // 30 is plenty for some use cases or even less
some non-alloc will want to declare them as Collider[] instead, always check the docs
they always return an int aka the amount actually found
Thank you so much for the great explanation
One last thing though 😅 If the player (blue) does a spherecast at its position, will the read object hidden behind the green wall be registered? or what?
yes
you would do an additional raycast to check if between you and red is wall
oh nvm that you said spherecast not overlap
it works just like a ray (a thicc one :P)
it will hit wall and stop
Ah, alright. I was wondering about that
So overlapsphere if I want all colliders within the sphere?
yeah overlaps I usually use for "whats around me" then check for wall blocking visions with ray
or maybe an explosion, etc
Perfect. Thanks once again. I feel ready to get to work
np. goodluck 🫡
can you have multiple curve in a single animation curve object?
naw
👌okay
no react gifs . . .
okay 👌
how else do i compare vectors?
read what the error says, anyway with structs you can use < > just ==
anyway compare the magnitude
Hello. I have added a movementDisabled bool to my Player Movement script, so that I can disable the movement in certain coroutines. It works if I set it to private, however, I need it to be public, so that it can be used by other scripts, but when I make it public, it gets overridden in the inspector, and I can't use it as intended. What do I do?
the operator "<" cant be used between a type "Vector3" and a type "Vector3"
well if a variable is getting overridden in the inspector, check your scripts to see if nothing is changing the value constantly
yup. Structs you can't do that since it would make not much sense. Structs are similar to classes
thats like saying classA < classB . Its nonsense
so i have to compare each number on their own?
that or the magnitude
cc.velocity.magnitude < myV3.magnitude
sqMagnitude is prob more performant
depends what you're comparing too, if its distance or something there is V3.Distance etc
or you can do
var myNumber = 3f
cc.velocity.sqrMangitude < myNumber * myNumber
why does bool point to the Boolean class? is there a way i can make my own classes do something like that too?
I think what you want is alias ? iirc the using statement has something to do with it
no idea why its saying dark souls LOL
will research this, thanks!
I think this
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-12.0/using-alias-types
just wasnt sure how to google that question
thats interesting
not sure why you'd do that but
can you use a variable name as a variable?
like
int x = 10;
x somethingElse = 3; ?
dont think c# allow that no
seems to let it happen
Is there an easyway to get the specific key pressed?
@verbal dome I have googled and I cant find anything
Oh I thought you meant declaring as field
i found this but it isnt working
if (Input.anyKey)
{
Debug.Log("A key or mouse click has been detected");
// get the pressed key:
String keycode = Event.current.keyCode.ToString();
}```
thats not a specific key now is it
thats not what I asked
I want to know what key is being pressed
I dont want 100 if statements for every key input
Is user pressing a key? yes -> get the key they pressed
I get it, and well..You still need GetKey
you have to loop through the keycodes and see which one was pressed, its not diffcult
making if statement for each one is not smart
you know KeyCode is an enum, right?
This is how to handle it with old Input system. If you want to just get any key input use new one
how does unity create the nameHash for animator states?
you would need the C++ source code to know 😉
oh lovelty
I wonder if Input.anyKey + Event.current.keyCode works
i was going to try and use the same hash system to generate the same IDs
I'm slowly but surely getting the hang of what to do for the board but I'm having 2 problems. The player won't go to certain nodes that are neighbors to the one they are next to sometimes and the player won't move the given dice roll but can only move one space at a time as well as the debug shows it twice with one right and the other not what was shown on the die. How do I fix these problems?
https://gdl.space/uyaviwuzoh.cs (Dice)
https://gdl.space/iciniralem.cs (Pathfinding)
your code is picking random nodes as the possible next moves
if those neighbor nodes aren't randomly chosen, then it won't let them go there
isn't that intentional?
No the player is supposed to move anywhere they want on the board depending on the dice roll. How could I fix that?
get rid of that whole part of the code that's chooosing the available next moves randomly then, no?
GetPossibleMoves is doing that. The nodes are chosen randomly in GetNextNode
Been trying to print out the correct Type that a script is in a custom editor, but it prints the type as monoscript or something other than the correct type. Is there a way to drag in a script and print out its type?
I'm using sourceGameObject = EditorGUILayout.ObjectField(sourceGameObject, typeof(UnityEngine.Object), true);
where sourceGameObject is a UnityEngine.Object.
Do I replace it with something else to remove that altogether?
Shouldn't you just add all cardinal directions to the list of available nodes, as long as they have a valid space there?
No idea why you're doing any randomness there
That's what the Node list was for, no?
i wonder if its just using a simple hashing algo , you might be able test a bunch and see if they match maybe ?
maybe they use Animator.StringToHash?
I'm talking about the fact that the way you are populating the list doesn't make sense.
In fact the whole way you're using the dice roll in that function also doesn't make sense
I thought thats what we were talking about this whole time no ?
that static method is external to cpp backend (StringToHash)
The dice is connected to the path so that the player can move depending on what was rolled.
i didnt know if nameHash was generated using that hash or something else
The number of moves is based on the roll, right?
The actual spots you can move next have nothing to do with the dice roll
unless I'm missing something
Not sure I understand what you're going for here
gotcha. yeah very difficult to know without source code, you can try a few hashing algos but for all you know its something they probably custom made or maybe put trim or shifting in there
I was trying to have it where once the player rolls the dice, they are are able to move the amount of spaces they roll and cannot move until they finish moving the spaces and roll again.
i mean i just wanted to get the same result, im not too bothered about the algorithm
well the algorithm is what gives you the exact hash based on specific string/chars no doubt
without it, there is no way to replicate it lol
Guys why does my debug give a nullreferenceexception?
Yeah exactly what I thought. In other words, the possible next moves have nothing to do with the dice roll. Your function just needs to do something like this:
- Make an empty list of possible next steps
- Check each direction (left, up, right, down)
- If the direction has a valid space there, at it to the list.
- Return the list
The actual handling of how many times the playe can move should be separate
attackMethods is null prob
you're probably calling StartAttack before Start runs
Yep it is, which means StartAttack was called before Start
it cant be i call much later after the object with this script is initialised
how do you know start is running in the first place?
If the exception points to the Debug.Log line, it's the only thing that can be null
? 😭
How would I rework that into the code I had? It does what I wanted except for moving to certain nodes or moving the determined spaces rolled.
put a log inside start, then put a log before the log with the dictionary. See which one runs first
Dont understand the error
you need a reference to the instance (the object created from the blueprint aka a class) otherwise it needs to be static
running a method on a blueprint is nonsense
yep start is first
where u put logs show new code
so second prints and then you get null ref?
start
then second
then null
Post the full exception message, make sure to include the stack trace with it
debug attack
NullReferenceException: Object reference not set to an instance of an object
Player.StartAttack (System.String attack) (at Assets/Player.cs:37)
AttackButton.Update () (at Assets/AttackButton.cs:20)
always write that in the log next time
Debug.Log($"attack value {attack} ")
never assume
Log: attackMethods != null and attackMethods[attack] != null. Make sure it logs as true for both
i debugged attack tho
Also, when debugging, output some actually useful information, not just strings
You need &&
So it means attackMethods is null, if yours throw
Either
your Action is null ?
my action is a method thats written
Please use two separate logs, so the values are differentiated!
for this?
Yes
Debug.Log(attackMethods[attack] != null);
this gives me the error
And the first log? Gives you false or true?
Action means method no?
false
Okay so the dictionary is null
Yes but you call Attack on something that did not run Start
i have a debug in start it runs
ie. Your other script is referencing the wrong instance
you are not calling the method on the prefab rather than the instance are you?
Script 1's Start runs.
Script 2's Start does not run
Attack is called on Script 2. -> Error
im sure its the instace
lemme check
guys im more than sorry i swear 😭
i named the variables in a similar i got confused
thank you so much my bad!
Hi could you help me with unity 2d game.. I want to make a pause menu on all scenes but its no react on "ESC" or if the pause menu show the button making a blank background XD
i make prefabricate pausemanager where i added a script with dont destroy gameobject
{
public static bool gameIsPaused = false;
public GameObject pauseMenuUI;
public static PauseMenu instance;
private void Start()
{
instance = this;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if(gameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
public void Resume()
{
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
gameIsPaused = false;
}
void Pause()
{
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
gameIsPaused = true;
}
public void LoadMainMenu()
{
// SceneManager.LoadScene("MainMenu");
SceneManager.LoadScene(0);
Time.timeScale = 1f;
}
public void QuitGame()
{
Debug.Log("Quitting Game...");
Application.Quit();
}
}
https://learn.microsoft.com/en-us/dotnet/api/system.type.getfields?view=net-8.0
I think? but this is getting reflection territory I usually dont touch often :p
why not just group them in structs/arrays
Better plan:
public Dictionary<String, Move> movesByName;
Instead of all of those
ah yes dictionary 
i just need it for an editor script
what does the last part mean? I dont understand can you send a screenshot or video of issue
apparently you can achieve it with reflection
Put them in a collection.
yes but that's very slow
There are much better ways
its an editor window thing, so its only gonna run once
I guess for editor script it's different
If this thing is serialized though - you don't need to reflect
Unity already does the reflection. Can you use the SerializedObject api?
i need to use ASsetObject in the framework im using. it inherits from scriptableobject
then you can use SerializedObject for it
oh wait but isnt it going to iterate over all the inherited classes too though?
not sure what you mean by that
i've got a really stupid beginner problem
so i'm trying to make my stupid capsule jump with this code :
public class playerMovement : MonoBehaviour
{
public Rigidbody rb;
public Transform ptransform;
[SerializeField] float xspeed = 1f;
[SerializeField] float zspeed = 1f;
[SerializeField] float jumpforce = 1f;
private void FixedUpdate()
{
rb.velocity = (Input.GetAxis("Vertical") * xspeed * ptransform.forward.normalized) + (ptransform.right.normalized * Input.GetAxis("Horizontal") * zspeed);
rb.AddForce(0f, jumpforce * Input.GetAxis("Jump"), 0f);
}
}
the jump works alright i guess but the problem is that when it falls, it falls really slowly, i get what the problem is, setting the velocity to whatever that thing the y velocity 0 every update, so gravity doesn't do it's thing properly, but i really don't know how to get around it i could use some help on that
Craft a Vector3 that uses the existing y velocity and your new desired horizontal velocity
and use that as the new velocity
Store that input bit in a Vector3, then set that vector's Y value to the current velocity, then set velocity to that vector
what's the significance of Unity's Object, Component, Behavior, MonoBehavior, and ModelPlug to each other?
No idea what "ModelPlug" is
oh maybe that pertains to something more specific
Is it possible to color a sprite in an only one color?
The first 4 are hierarchically related. MonoBehaviour inherits from Behaviour, which inherits from Component, etc.
Never heard of the last one though.
And the main question... is a bit vague. IDK how to answer it.
ya ignore that. it's a custom class for attaching objects together
i see a lot of MonoBehavior being used, but the higher hierarchy classes are unclear to me
Component is anything that can be attached to a GameObject. Including Unity'sd built in components. Anything showing in the inspector is a Component
Behaviour is a subclass of component that has an enabled property
MonoBehaviour is a component that is written in C#
Object is the base class for every managed Unity object, including all of the above and more
Check out https://docs.unity3d.com/ScriptReference/MonoBehaviour.html, then once you read it, at the top of the page click where it says "Inherits from: Behaviour" and it'll take you to the parent class. Repeat and you'll se what these are and their differences
alright i'll read that
trying to get the property type but im getting these errors
what errors?
sorry its not an error, but the types don't match so it wont work
whats PPtr
not sure what you mean, also this is a code channel
What are you trying to get
getting this error for full typename.
same for poth
both
its a pointer apparently?
What is Move?
ok this must be related to some special handling uNity does for UnityEngine.Object reference fields..
Maybe if you do:
property.objectReferenceValue.GetType()``` ?
i (chatGPT) figured it out, they used some reflection or whatever idk
it works now though! so thats what matters
i dont like using AI but for editor scripts i dotn really midn
Well what does GetFieldType do
private Type GetFieldType(SerializedProperty property)
{
// Get the type of the property from the SerializedObject
// We use reflection to get the type of the field in the MoveList
var moveListType = selectedMoveList.GetType();
var fieldInfo = moveListType.GetField(property.name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
return fieldInfo?.FieldType;
}
I see
yeah reflection on the enclosing type
Which kinda defeats the purpose of using SerializedObject etc but whatever
so Object exists for Unity to acknowledge a given object in the inspector?
honestly it does what i want it to so its fine
even if its dirty and i didnt make it myself 😅
The inspector is just a small piece.
i'm guessing the rest pertains to low level business between C# and C++?
And the rest of the API that deals with them...
Object.Instantiate
Object.Destroy
JsonUtility
everything here https://docs.unity3d.com/ScriptReference/Object.html
how can you serialise a dictionary?
Have you googled it or checked Unity discussions? This is a very common question with very weell established answers
can you put dictionaries in a scriptable object?
i have tried, but i have no way to check if its working or not
they're just regular classes, nothing special about them
because it doesnt show up
you can use 2 structs to iterate through it or add something and do .count
unity cannot serialize dictionaries, you'll need to use a custom solution if you want a dictionary to be visible in the inspector
Yes
Again if you want to serialize a dictionary there are many answers for that
and they will work on a ScriptableObject
and in any case - wdym by "there's no way to check if it's working or not"
The inspector is just the inspector
things still exist if they're not in the inspector
I can't use the serialisable dictionary because the framework im using wont allow it in its assembly
You don't need to put it in the framework's assembly
put it in your code
don't modify the framework
okay i'll tryy that
you should almost never be modifying the libraries and packages you're using
I have a dumb problem, I'm using this code to procedurally animate my character and so far it works and looks normal, but I want the legs to move over to where they're supposed to be instead of snapping over like how this code makes them do. Tried using rightleg.translate(Vector2.right) but that just moves the bone downwards instead of to the right, and also i dont know how to add my stepdistance variable to that
Translate works in local space by default
You could just Vector3.MoveTowards to move it over time
For example, for each foot you could have an empty object (or a predefined Vector3) that marks the resting position of that foot
Then you can do leftLeg.localPosition = Vector3.MoveTowards(leftLeg.localPosition, leftLegRest.localPosition, Time.deltaTime * someSpeedMultiplier)
Got it, thank you
can sp,e
Configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I am trying to config my vscode to unity, I followed the website, downloaded the package but it doesnt seem to work
downloaded the package ?
yes
remove this one, make sure you select the correct vsc version in external tools
close vsc and regen project files after
it says cant remove bc other installed package or features depends on it
Inside dependencies, it says used by Engineering
remove it
what does the engineering package do
it installs all those packages for each IDE
if it removes the visual studio editor one too add that one vs package again
Hello everybody, please help me, how to make an optimize code of text update? I also have a data loading system, where dictionary or static variables are can't be used. I think I need delete all this code... It looks so bad...
What is the problem with it?
I do not know how to combine the code. I used to have a container that my text display worked well with. But after adding a new system for loading and saving data, I had problems with this script, since the container can no longer be used, and the script itself, where my currencies are stored, cannot act as a container
MonoBehaviour scripts should not have a constructor
pretty sure unity/vs should warn you about that
use awake instead
Tell me what is the «constructor»?
did you not write your own code?
the function that runs on object creation.
MonoBehaviours or UnityEngine.Object derived objects are handled by unity already hence Awake for initialization purposes
tried multiple times, shows this message
did you install the .net SDK then restart your computer?
how can i check if the collision for ontriggerenter2d is in a certain layermask
https://unity.huh.how/bitmasks#checking-if-a-mask
but you typically wouldn't need to do that if you just set up your layer based collision properly
k thanks
hey so i want to make game difficulty for my game and im guessing enums might work but i havent really used enums before do they only provide a list or can i set a enum to one of the choices?
An enum itself is a type, just like a class or a struct. An instance of your enum type would be of one of the defined values.
so how exactly would i use it to store what difficulty the game is currently at?
ah nvm i think i see
For future reference, it's a good idea to check the docs. They even have some examples.
yeah i just checked them lol
PLEASE HELP MY CAMERA IS INVERTED (LEFT MOVES RIGHT, RIGHT MOVES LEFT, ETC.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
//Get mouse input
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation += mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//Rotate cam and orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
- !code
- don't multiply mouse input by deltaTime, that is wrong because mouse input is already framerate independent so doing that multiplication just makes it dependent on the framerate again and leads to inconsistent and stuttery camera controls
- if the horizontal rotation is inverted then just subtract instead of add . . .
📃 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.
How do i do that third thing (Mind you ive been following a tutorial so i am taking in about half of this info)
- instead of +
Alrighty so my vertical is now working all good, but the horizontal is still backwards..??
#💻┃unity-talk message In regards to this,
private void OnCollisionEnter(Collision collision)
{
//remove bullet
Object.Destroy(gameObject);
//deal damage
if(collision.collider.CompareTag("Hurtable"))
{
collision.gameObject.GetComponent<HealthController>().hurt(damage);
}
}
this is what I have for handling hitreg
how are you moving the bullets
rigidbody with an initial velocity, continuous collision detection
public void Fire()
{
if (lastShotTime == 0 || Time.time > (lastShotTime + (60 / fireRate))) {
Rigidbody newBullet = Instantiate(bullet, transform.GetChild(1).position, Quaternion.identity);
newBullet.GetComponent<BulletScript>().setDamage(damage);
newBullet.velocity = transform.forward * velocity;
lastShotTime = Time.time;
roundsRemaining--;
}
}
this is the code that handles that
how fast are you shooting this rigidbody
and how small is it
from what im seeing, that looks like raycast bullets (from how fast they are going)
default capsule size, and by how fast do you mean how often or velocity?
velocity
80f
That might be insanely fast, I havent really figured out how to tune it into a good value
are you calling Fire() in Update()?
put it in FixeduUpdate()
void Update()
{
if (Input.GetMouseButton(1))
{
RaycastHit hit;
Ray ray = camera.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
this.transform.LookAt(hit.point);
activeWeapon.transform.LookAt(hit.point);
aimLine.enabled = true;
aimLine.SetPosition(0, activeWeapon.transform.GetChild(1).position); //x,y and z position of the starting point of the line
aimLine.SetPosition(1, (hit.point + new Vector3(0,0,0))); //x,y and z position of the end point of the line
}
if (Input.GetMouseButton(0))
{
attack();
}
}
else
{
aimLine.enabled = false;
}
}
void attack()
{
activeWeapon.GetComponent<WeaponScript>().Fire();
}
put attack() in FixeduUpdate()
you put all rigidbody related items in there
since it is on the physics update
and it is also framerate independant
I should probably also do that with my player controller too right, since its rigid body forces
so 80f is actually more like 1000f due to Update being frame dependant
and it will change on how much or how little your framerate is
hey so for my game i want to proceduraly generate the levels so i can make it endless and the game is basically there are squares you can grapple onto to swing and every once and a while there are walls and im really not sure how i can make it so the squares and walls are generated via code.
here is a image of what a hand made tiny portion of a level for testing looks like
just instantiate them with a random Y
and X within the cameras view
yeah but how would i do that 1 endlessly and 2 how do i deal with making them because i dont want to have it like 1 is made every second because if you go to fast then some might not form but if i just have them go without a cooldown the whole screen eventually will be full of them
then you make them a bit infront of the player too, like 1-3 camera lengths
so they are always visible to the player if he goes forwards
yes but how do i make it so they generate enough but not to much
like i dont want it to just generate 1 every x amount of time
just pick an amount you want visible at all times to the player and spawn that much?
ok
I always wonder why people never acknowledge the answer, but have no trouble being redirected to another channel.
but... how do you do this without showing it in the scene???
I don't know what you're talking about. The issue is you have no object in your scene called Cannon, yet you are GameObject.Find("Cannon")....
It's not finding it, thus it's throwing an error when you try to GetComponent<Transform>() off of a non-existent object.
😭
That has nothing to do with your error
If you're following some tutorial, I suggest doing it properly?
It's telling me to write this code, delete the thing outta scene, make it a prefab and it should work
Link this tutorial
so im following this CodeMonkey guy on youtube and i get this error and i dont know why?
you are trying to use private inside of another method
you cant do that
did it used to work like that?
the tutorial either doesnt use private or make this Vector3 method outside
no
your method is inside of another method. you cannot use an access modifier for a local method (most likely unintentional) . . .
fix your formatting. look at their code and compare it to yours . . .
i did, i put it side by side and notthing is diffrent
it 100% is
screenshot the tutorial code if you can
show us their code . . .
not the same at all . . .
brackets where?
look at the open and closing braces . . .
the ones that end the Grid method
see how their constructor does not contain the GetWorldPosition method like yours does?
ohhhhhhhhhhhh
literally look at the code line-by-line . . .
don't just assume it's the same; actually check . . .
just in case, does anyone have a tutorial on Grid Making, like the kind for building placing for 2D?
is that not what you are doing?
It is, I just like to look at other ways it's done and find use the ones I thinks is better
lookup Grid component n Tilemap
From Tamara?
huh?
what nav suggested is a component in unity
dunno who "Tamara" is
I looked it up and the most prominent thing that popped up was "Tamara Makes Games" YT channel
okay
hey guys, quick (probably) question, here's a little snippet of code, line 11 is never hit, and I'm a little confused as to why it would just be skipped over, I'd really love if someone could give me some insight https://hastebin.com/share/xuzoqokupu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's inside an if statement
code isnt just skipped over, does your log show in the console?
my bad, this is assuming line 10 is hit
The other possibility is that line 10 is throwing an exception
and line 10 is fine
Then line 11 is also running
You're mistaken
Add another log after it to prove it to yourself
ah, you're right, I do have an error, I just didn't notice because when I debug from hooking Visual studio normally the error also pops in visual studio, since I can't alt tab to unity, interesting how that works
Thanks for the tip
do exactly what it says
it's telling you how to fix it right in that message.
Is there a way to check if a mesh collider fully engulfed another collider?
One way is to set up a few representative positions on the "other" object, and test to see if they're all contained in the first collider.
If they are all contained, you can say it's "fully engulfed"
it's not perfect - but a good estimate
yea, im currently doing that, just transforms that does pointoverlaps (raycast with no direction)
raycast won't work
Yes
Notes: Raycasts will not detect Colliders for which the Raycast origin is inside the Collider
oh I see
Also in 2D it's better to use this anyway:https://docs.unity3d.com/ScriptReference/Collider2D.OverlapPoint.html
Dont know that one
But yeah for 3D to check for a point overlap you would do this:
bool PointOverlapsCollider(Collider c, Vector3 point) {
Vector3 closestPoint = c.ClosestPoint(point);
return closestPoint == point;
}```
This takes advantage of the fact that ClosestPoint will return the same point we input if it's inside the collider
I'm a bit confused on manipulating translations in relative space through code. I'm trying to make a sliding door, this is the code I've got.
private bool sensorActive = false;
[SerializeField] private GameObject leftDoor;
[SerializeField] private GameObject rightDoor;
private Vector3 leftDoorTarget;
private Vector3 rightDoorTarget;
public float openSpeed = 2f;
// Start is called before the first frame update
void Start()
{
leftDoorTarget = leftDoor.transform.position;
rightDoorTarget = rightDoor.transform.position;
}
// Update is called once per frame
void Update()
{
leftDoor.transform.position = Vector3.Lerp(leftDoor.transform.position, leftDoorTarget, Time.deltaTime * openSpeed);
rightDoor.transform.position = Vector3.Lerp(rightDoor.transform.position, rightDoorTarget, Time.deltaTime * openSpeed);
}
void openDoor()
{
leftDoorTarget = leftDoor.transform.position + new Vector3(0, 0, -2);
rightDoorTarget = rightDoor.transform.position + new Vector3(0, 0, 2);
}
void closeDoor()
{
leftDoorTarget = leftDoor.transform.position + new Vector3(0, 0, 2);
rightDoorTarget = rightDoor.transform.position + new Vector3(0, 0, -2);
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")) {
sensorActive = true;
openDoor();
}
}
private void OnTriggerExit(Collider other)
{
if(other.CompareTag("Player"))
{
sensorActive = false;
closeDoor();
}
}
That seems to translate it on the global Z axis though. I've been looking at the docs on TransformDirection but I dont understand how it gets used
local Z axis should be the correct direction to open in always since its relative to the parent, if I understand that correctly
This code is not moving anything
It's assigning a value to some variables you have
And it's using world space positions to do so
whoops, forgot some context
You should show the rest of the code
Your code is doing everything in world space
If you want to move objects relative to their parents you would use localPosition instead of position
ah! thats what I was missing
yup, went to that and it works perfectly
I was looking at all sorts of transform methods and stuff. What a simple solution. Thanks for the help
one thing you could do is just make empty child game objects that act as points for your doors to move to. Just for the simplicity of being able to visualize it in inspector, plus not having to rely on the hardcoded values that you have for the vectors (or experimenting with values in inspector)
Thats a good idea. I just did something similar for the close position because I found that it didn't fully close if I entered and exited the trigger repeatedly too quickly
I dont understand how SmoothDamp works, when i set speed to 100 its very slow, but when i set speed to 0.01f its really fast
hello, i have a issues, and somebody help me saying to put the script on game-object, but i put it
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I guess, using a custom material with render queue being above should do the trick?
is there some way to still have these in my code? - they are just for a debug log, to visualize output from my code...
when i "Ctrl + s" i get this:
Maybe try to use the unicode equivalent?
Created 2 standard material , set mesh mat's render queue to 2000 and sprite mat's render queue to 2500 and tried 1500 too, nothing happened :/
do i just put it in a string like fx "\2810" ??
would that work?
you really should just leave that as-is and save as unicode (specifically utf-8)
that wont break anything in my project, if i say yes in the popup window?
C# compiler generally likes UTF-8-encoded source files, so saving as UTF-8 would be fine.
resave this file as Unicode in order to maintain your data
Just "Unicode" is ambiguous, could mean UTF-8, UTF-16, etc.
Sometimes platforms can cry about it too, when you switch between win and mac or something, but if you are workin on your own anyways, you can just convert them
Line endings are a different matter
Wont they be introduced with the conversion? If not, then never mind my comment
Encoding issue is orthogonal to platform's line ending preference
so after reinstalling my editor I still have the same errors:
this isn't really related to your code, so not exactly a code question. but make sure all of your installed packages are up to date, and if the issue persists after updating packages then you should close the project, delete the Library folder from within the project, then launch the project again
oh okay, thanks
I have this weird issue with sprite scrolling. This script works perfectly fine, besides the Awake function. In it, it's supposed to set a random initial value to the scroll of any axis where it's intended, as in set in the public imageScrollSpeed variable. The value changes to what it should, even while incrementing it, but the offset is not applied, only the small changes in the Scroll function. Why is this happening?
Class
Did you debug log your imagescrollspeed.x and .y to know its not 0? As its public, did you maybe overwrite it in the inspector?
0,1 will always be 0
not sure if thats what you want, probably not
I tried on 0-100 earlier
wait
I'm stupid, this only returns integers, so I can't see it working
my bad yall
and an int would also make it so it only returns 0, so yeah try using floats
I am importing 3 textures. Since I am doing this, pressing the play button takes much longer and is stuck on "Importing assets" (like 15-20 seconds each time)
Does anyone know what the reason for this might be?
do you guys know a solution to this unity tutorial, i have done all the fixes but the spin script is not working the bomb and the coin are orbiting around something, the same script is working fine on baloon though
really cant tell whats going on tbh
What are directions?

exactly what I need