#💻┃code-beginner
1 messages · Page 724 of 1
havent gotten around to trying that but sounds cool..
lots of ideas rattling around
i always wanted to try rainbow 6 siege like destruction now i know how
another example of half finished unity implementation.
Like is there rational behind why they didnt do it?
or did they just say fuckit ship it people definitely wont want to do this
probably? I don't know the technicals to give you a reason
generally you should have a better system in place anyway like proper Dependency Injection chain
wait thats entities ?
I'm sure there is a thread somewhere dicussing but I dont feel like googling tbh
google AI thing says this
Scene files are designed to be self-contained units. If an object in Scene A directly referenced an object in Scene B, and Scene B was not loaded, the reference would become null, leading to potential NullReferenceException errors. Unity cannot guarantee that all scenes containing referenced objects will be loaded simultaneously or in a specific order.
Serialization Challenges:
.
Saving and loading these cross-scene references reliably would be complex. When a scene is saved, it needs to store information about its own objects. Storing references to objects in other scenes would require a more intricate system to track and resolve these dependencies, especially if scenes are modified or renamed.
no clue how accurate it got this info
Could be wrong but idk a better way to do this personally. I Have a scene that is always loaded, with a "VehicleManager" class attached to one of the objects. I created an editor script that is just a scriptablewizard that takes in a mesh and some other data and creates a car prefab and some scriptable objects, assigns an ID and then generates a class so for example
public class VehicleList
{
public const int corvette = 1; // where 1 is the assigned ID;
}
It then places a reference to the prefab i just created into a dictionary<int, GameObject> where the key is the assigned ID. This allows me to call
vehicleManager.CreateVehicle(VehicleList.corvette); and vehicle manager will just do a simple dictionary lookup by key.
the vehiclemanager lives in the scene that is always loaded so its not destroyed and clear the dictionary.
I mean obviously i am not rewriting all this due to this issue im just going to chuck DontDestroyOnLoad in start and chuck it in the main scene but damn
sounds reasonable i guess but just a little annoying to say the least.
how do I rotate an object using scripts?
I have transform.eulerAngles.y = 0;
shouldn't this work?
not at all , you're not allowed to modify the property here
if you want to properly rotate consider using
.rotation = Quaternion.euler
or
.Rotate()
so transform.Rotate() = 0 would work?
whyy would it work ? this is a compile error.
look up the documentation and use the methods properly
guessing ain't something you should do with code. it needs to be functional
Any suggestions on how I can improve this?
does someone know how to help me
dont crosspost
i don't understand you i am new
keep your question in 1 channel.
oh sorry
Bro how can we use behaviour tree
I want to do this since I don't want this to ever be modified from outside, but I'd want it to display properly on the inspector and not with the camelCase, can I do that?
Make it not camelcase
Can you clarify what you're asking cause im not sure of your problem
I mean, I could, but then it just looks messy on the code instead lol
By naming convention here just make uppercase here and that would be fine
public getters are usually by pascal case anyway
I just want to make that field not modificable from outside, but this has the side effect of looking like this:
you could use the readonly attribute
It's not making the first one capitalized for some reason
It's messing my head lol
so you do want it camelCase or what
How is it written in your code?
if you want it camelCase you need to modify how it's displayed with a custom inspector script because all exposed variables on the inspector will be pascalcase
I want it to show as all the other fields show, with the camelCase transcribed to show in full split capitalized words
I thought unity always auto capitalises field names
"myTestName" would be "My Test Name" wouldn't it?
Ok, so that would be with an editor tool or what?
what you can do is use snake case
that will go against unity's ability to capitalize
WaCkYcAsE
but that also means means public variables will also have to start with an underscore to override it
Any developer that can help in creating rp game please dm
Good day, is it possible to find a mentor to receive some tasks and gain more experience in development? Or perhaps to work in a team with more experienced developers?
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
is ↓ bugged in unity 2022ver or something?
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
auto detecting didn't work (i can see the debug object but not the permission request)
#if UNITY_ANDROID
// Ask permission once
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
DebugObject.SetActive(true);
#endif
it just won't pop up the permission request, I even tried to make the button for it, the button itself is working and running the coroutine (i can see the debug object) but it just won't pop up the request and i've to put a text box there to ask the user do it manually like a 🐒
public void OnButtonClick()
{
StartCoroutine(RequestWebCamPermission());
}
private IEnumerator RequestWebCamPermission()
{
DebugObject_working.SetActive(true);
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
}
I think if the user has already chosen it wont let you re ask? It may not be unitys fault
no it's flesh install
Request permission, check after if its granted and if not show some message box informing the user that its required.
DId you add the permission to your android manifest yet?
i believe i did
my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
the user can allow it manually via going to the phone's setting/app/(app name)
when using android logcat do you get any errors when you attempt this permission request?
(perhaps it needs camera2/camerax and it will mention this?)
the only warning i see is mentioning the phone time is in future and the app icon compress stuffs (i'm too lazy to set it)
edit: nvm that's not related, that's just the gameobject that uses the cam
hmm sus
Btw this example uses a different api to request permission for android? https://docs.unity3d.com/ScriptReference/WebCamTexture.html
i really dont know what makes the app thought that happened, bro is seeing things
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
Debug.Log("Webcam permission granted");
// Add code here for what to do if permission is granted
}
else
{
Debug.Log("Webcam permission denied");
// Add code here for what to do if permission is denied
}
Random question. I just spent like 5 hours trying to figure out a bug. I had code i KNOW used to work as i have source control on it. All of a sudden my code would throw an error that i was unable to understand or figure out why it was happening. I started walking back through my source code and after about a 100 commits and a months worth of time i saw i had added an onclick() to a button which i also had execute in code by having the button hooked to code directly. Long story short is how did my code function for a month like this then all of a sudden stop. I had source control, i didnt upgrade unity, i didnt change packages. I am really baffled but glad i figured it out.
NO WAY IT ACTUALLY WORKED 💀 THANKS BRO
the code for unity 2022 (the one i'm on rn) didn't work but the code for unity 6 worked
what can i say
does anyone know any good videos that can teach me the basics of C# game dev or could someone check if the video I found covers the correct topics?
there are resources pinned in this channel
hey so like how do wallruns work in unity?
like what do you need to do to implement it?
more specifically how do you know if the object the player is touching actually is wall runnable?
kinda vague but the answer is "you check with how you assigned such data"

hit surface -> does it have my special component? -> check properties -> ??? -> profit
oh that's not too bad
how do you actually check if the players touching the wall though?
the same way you'd do a ground check
there's most definitely going to be tutorials online for wallrunning
so just like a sideways ground check?
Anyone?
I figured it out
what's lean mechanics
Let's say you're behind a wall. So you lean to peek through the wall
No
It was a template by Unity but then later some of the code I have entered it by watching a yt tutorial
oh, nice
you need to state what the problem is and what you need help with.
Read 👇 !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 #🌱┃start-here
Are you a moderator in this server, just asking
Please don't direct me to these weird websites. You've done this too many times to me already and they aren't helpful
He's not, idk why he acts like one 💀
it's not a weird website, it's information to help you get help.
Ever since i added the new code from the yt tutorial, I get these weird errors
list of mods on the right they have orange-y names
see, do you no think it would be useful to share what those errors are and with which lines of code...?
Already shared above man
where's the error
This
Most of the code came from a Unity template by default, but the lean codes are from the yt tutorial
First Person Shooter
and the error is.......?
Wdym?
hey may i ask you a question??
What's up?
can you help me build a player movement code (i have been struggling with it..i have recreated the code 8 times and it still doesnt work)
there are plenty of resources you can follow at your own pace to do player movement
i tried all of them
im only left with this option now
Not even the unity one? https://assetstore.unity.com/packages/essentials/starter-assets-character-controllers-urp-267961
If its not suitable then you may want a more basic movement controller that takes input and translates your player.
add it to your account and use the package manager in your project (Changed to "my assets")
then you can import it. the visual of this asset are for URP only
Hi everyone,
Just joined the server and I am not really an active Discord user. Is this the place the ask questions? I dont see any channels specifically for help or voice chats that's why I'm asking.
ask questions in the relevent channel
here is for code questions, #1390346776804069396 for light/graphics/shaders
id:browse for them all
character control question - am using 3rd person camera, and i have the target offset .x set to 0.45, but when I use S to run back, the camera swaps the sides of the offest creating a very jerky experience. so I tried to use this code to fix, but it is still kinda happend, them my code fixes it, but it is very jerky now...
if (moveInput.y < 0)
{
cameraComposer.TargetOffset.x = -0.45f;
}
else if (moveInput.y > 0)
{
cameraComposer.TargetOffset.x = 0.45f;
}
most of them are help channels so they aren't specifically designated
@grand snow could you help with this?
lerp or smooth between them
don't ping random people for help
Then who do I ask?
I got ignored for more than 10 mins
Yea people are free to help if they want
I did 💀
ok, I was hoping there was another solution to the offset issue, but I'll try that
UNDEFINED BEHAVIOUR BABYY
the most info you gave was "help with lean mechanics"
you never said what issues you were having or what part you needed help for
vague questions will yield vague responses
oh i kind of misread. but it does sound like you'd want lerp/smoothing on.. however you're doing the camera offset thing
My code was mostly already written by a Unity template for the FPS game. Then i wanted to add a lean mechanic, so I followed a yt tutorial. But now I'm getting errors
ok, and what are said errors
Hold up lemme check...
you werent supposed to do that , you will have to read the template and make modifications on your own post consideration
you're instatiating a private class
but idk how to code
or a private object
ya, its an offset issue that keeps making the camera seems to swap the camera offset when the character turns and runs back using S
remove the public from the line it tells you.
add an extra } where it makes sense to - so your brackets are in pairs
that is not what the error says
gotta learn , c# is an easier language , learn it it will help massively in the long run
do you control how the offset is calculated?
I was just setting it once at 0.45 so it is to the right of my character, looking over the sholder. so I don't normally change it
ya
is it turning around immediately?
basically
then that would make the camera turn immediately too
perhaps slerp/smooth the rotation
ya
the character movement is ok, it is the camera jumps to the left side of my character. if I can simply stop it from doing that, it would be great
I want the cross hairs to stay on the right
perhaps slerp/smooth the rotation
basically like the game Valheim
I already know how to screenshot. Am not in the perfect state to ss rn tho
doesn't really matter
photos or videos of a screen are near the worst ways to share info
I didn't understand
tell me what you didn't understand.
I didn't understand what you said exactly
I'm new to Unity
this isn't unity-specific
Also uhh
this is.. quite nearly english
My scripts aren't opening
do you have an ide installed
Did i do something to you? I'd really like to know. Why do you keep going on my case and being rude?
this is nothing personal against you, im not actively trying to be rude
but really, what carwash said is plain english
Ide?
now that's how you ask for clarification
an ide (integrated development environment) is the app you write code in
usually vscode, vs, or rider for unity
I'm using Visual Studio
could you clarify on this?
what did you do exactly (double clicked a script in unity? double clicked a file in file explorer?)
did you get any pop ups or error messages
someone please help me..rob gave me a starter asset adn i downloaded it adn now it turns out the camera is stuck in a place that doesn't show anything..the player is moving but the camera is just stuck there
you have compile errors, you have to fix those before these can make sense
(these being said compile errors)
How exactly do I fix those? When I try to right click to open the script, they're not working
hm, not sure what's up with that, but that's a secondary issue
open the scripts in your ide or via file explorer for now, probably
it tells you the file and the line where the error is
the (408, 9) means line 408, column 9
Nvm I give up man
I hardly understand half the stuff everyone is saying
Im just gonna make a new project from scratch
that.. isn't gonna help if you don't learn it eventually
if you don't understand a specific word or phrase, then ask about it lol
What should I change in the script now?
something tells me you have no idea what this project is or what you are doing...
why are you fixing such an error?
the 2 lines giving errors, fix them as carwash said above
Exactly 😭
Yo i've been trying this for a while and i still can't get it so if anyone can spot the issue that would be sick. I've got this modifier for my game which allows the player to shoot from both sides of them but for some reason the bullet still spawns from the shield rather than behind the player. The raycast on the second side shows that the position is placed behind the player whenever I press shoot but bullet still doesnt spawn there.
What public is it mentioning abt tho?
share !code properly please
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
the one on line 408
Where's 408?
oh mb im new
did you open the file in visual studio
there should be line numbers
i don't see any
turn them on in settings
there'll be a search bar
(no spaces between the backticks and the cs)
alr
also make sure it's on the same line - also you can edit messages
Ehem uhh I think I found the issue
float distFromPlayer = 0.75f;
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Gets the position of the mouse
mousePos.z = 0f; // Making sure that Z doesnt mess up the calculations/spawning
Vector3 direction = (player.transform.position - mousePos).normalized; //Direction of the mouse to the player
Vector3 mirroredPosition = player.transform.position + (direction * distFromPlayer); //Player position plus the direction opposite of player to mouse
mirrorPos = mirroredPosition;
Quaternion mirroredRotation = Quaternion.Euler(0, 0, Shield.transform.rotation.eulerAngles.z + 180);
GameObject mirroredBullet = Instantiate(BulletPrefab, mirroredPosition, mirroredRotation);
mirroredBullet.GetComponent<Rigidbody2D>().AddForce(-Shield.transform.up * shootForce, ForceMode2D.Impulse);
Debug.DrawLine(player.transform.position, mirrorPos, Color.cyan, 1f);
😭
i meant the cs and the backticks
it still needs a newline after
also you can edit messages
from this, you have stray spaces
ahh is this it?
cool
show the actual error please
fix the other compile error first
470?
Line 470?
Wait nvm there's nothing there
Uh what compile error?
have you tried logging mirroredPosition and mirroredRotation to compare with the non-mirrored version?
that's the issue
it's expecting a }
{} need to go in pairs, right now you have some { that isn't paired
It already has one
you have to add } somewhere to make sure they're paired
go find the one that isn't paired
next issue:
My ray cast from my camera hits my character. I was told I can put the player object in a different layer and the ray can ignore it, how to I make a ray ignore a layer?
pass a layermask to the raycast
since charachter conteroller doesnt have a rigid body i cant give it a certain amount of force in a direction right ?
you can set the layermask from the inspector if you serialize it
yeah, you would have to keep track of that yourself
oh F
I got more errors 💀
actually, instead of using the layer, could I use set the ray to ignore the Tag (set to Player)
sounds like you put it in the wrong place
no, tags aren't part of the physics system
layers will make this easier
you put it in the wrong place
The bracket?
yes
For now i just place it as a public variable and they are different
like those x values are both opposite sides of the player in this case when a bullet is shot
you have a stray { on line 300
also, literally everything from line 186 onwards is inside Update
Your visual studio isn't setup to work with Unity. If you do this, it will make finding and fixing errors a hell of a lot easier.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
I'm never getting Unity's help ever again
I clicked on the Red underlined text and told Unity to auto adjust. Big mistake 💀
huh?
😂
"auto adjust" -> what?
the unity extension?
The bracket on line 300 is unnecessary?
why do you think it's necessary
Fair point
What do I do abt the update part?
make them not be in update
Should I just delete void Update()?
no definitely not
What?
void Update()
{
- void OtherMethod()
- {
- /* ... */
- }
}
+ void OtherMethod()
+ {
+ /* ... */
+ }
void Update() is the method , if you delete that the chunk of code below it will be an error and your code won't do anything
What's void othermethod?
your.. other methods..
game dev is hard, you have to be able think and extrapolate things from the information provided
My brain is legitimately fried
🤯
"OtherMethod" is obviously just an example used because Chris doesn't knkow your other methods and isn't going to go and find out
then take a break
you need to, in order,
- rest
- learn c# basics
- learn unity basics
you asked if you should delete the update method
Idk how to code tho. How would I know what my other method is?
Man, Unity help screwed my script big time 💀
because method signatures have the same structure. You can look through your code, without understanding it and see, from pattern recognition, where the methods are.
You're fighting an uphill battle.
Your VS isn't configured and you have no idea about the very basics of C#. Do yourself a favour and look at the links in the beginner resouces section of the pinned messages, and do/read them
I got it working, thanks!
we still have no idea what this "unity help" is
What is recommended logic for rotating a player via current mouse positioning in 3d space?
Right now I'm using RaycastNonAlloc on a configurable timer (currently running 1/10th of a second). It feels like using this is a bit redundant due to the infinite possibilities of ScreenPointToRay though.
Is there a better, more efficient way I can do this?
I have a list of VehicleInstances. This list represents all the vehicles that the player owns. VehicleInstance is a scriptable object. The vehicleinstances that are being stored in the list represent what vehicles the player owns and references other scriptableobjects depending on what parts have been installed on the car. How would I serialize that list of VehicleInstances to json and then restore an instance to the same object when the games reloaded? Can I just call ToJson and FromJson and be done or?
For serializing references to assets you need to use some kind of identifier scheme that you can reload later.
It's similar to referencing a sound clip or a texture. You could theoretically serialize all the data directly but most likely what you intend is to serialize a reference to the asset
You can use the Addressables package for this
Or roll your own
if I ToJson a scriptable object will it save the fields that are serialized in the inspector? then I can just load/save the custom values from the json and use ScriptableObject.CreateInstance?
Answered
You could do that but it seems unlikely that's what you want
well the scriptable objects are created at runtime too. IE the car has a base tune, player can edit properties like ride height and camber, and to prevent other instances of the car from being effected it creates a new instance of base tune scriptableobject and then user can modify the values in game.
So I would kinda have to serialize the data itself i think
Then I would argue ScriptableObjects are the wrong tool here.
You might want a ScriptableObject as the "base data" but you're immediately turning that into a runtime object that can mutate
In these cases I use a setup like:
- A SO base data object
- a serializable runtime and storage time POCO/DTO object
The so is just there to create the runtime object more or less
There's no reason to deal with the SO overhead for the object that mutates at runtime and gets serialized
To make sure I understand correctly, use a scriptable object for the base tune also create a struct with the same fields as the so. In the code that uses the SO currently edit it so it can reference a SO and then assign the values from the fields in the SO and then assing the users custom data from a json file?
That sounds like a lot. Is the overhead of scriptable objects that much?
No just have to SO produce the runtime object itself
This would all be during your boot up and loading process
can someone help me with my problum
The gameplay scripts would only interact with the runtime data
you dont have to type this in multiple channels, even after someone told you to just ask the question
we cant help if you dont tell us the problem
this is my problum
So are you suggesting something like this?
using UnityEngine;
//[CreateAssetMenu(fileName = "NewSuspensionData", menuName = "Vehicle Physics/Suspension Data", order = 1)]
//[CreateAssetMenu(menuName = "VehiclePhysics/Suspension Data")]
public class RuntimeSuspensionData
{
public float antiRollbarStiffness;
[Header("Hit Detection - Inputs")]
public LayerMask layerMask;
[Header("Suspension - Inputs")]
public float restLength = 0.33f; // 35cm rest
public float travel = 0.15f; // 15cm usable compression
public float minLength => restLength - travel;
public float maxLength => restLength + travel;
public float springStiffness = 55000;
public float damperStiffness = 5000;
}
public class SuspensionData : ScriptableObject
{
public RuntimeSuspensionData data;
private void Awake()
{
data = new RuntimeSuspensionData();
}
}
and then the runtime scripts would use a reference RuntimeSuspensionData
and mb i did not understand what he ment
@hexed terrace @naive pawn may I add you both? Yall have been really helpful today
try removing the collider and putting it back
and if that doesnt work then continue this topic in #💻┃unity-talk because its not related to code
Do anybody know a course and a project for learning Unity under a week
It has been 3 days and I have build a basic project by watching a video in the YouTube.
It's just a simple flappy bird game, at the end of the video, the Creator challenge us to add game start screen and other challenge that I can't really understand
Not in Awake but more or less
Basically the SO is only for design time
When would you do it then?
When you save youre game and load it you're only dealing with the runtime object
In a function you call manually
alright
alright awesome! Thank you for your advice. I like this design a lot better
Ill use assetbundles for things like GameObject and sprite and then store the path to the asset bundle in the scriptable object and a reference to the gameobject in the runtime portion.
You can't learn (all of) Unity in a week. It's perfectly normal that you're not ready to make things independently after 3 days. Follow an actual structured course, not Youtube videos, e.g. !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I get the point, thanks for replying and yeah I also know about the Unity learn,
Can you tell what concepts should I know to get better grip at things,
What mistakes should I avoid and what courses are the best
You're not going to learn the engine in under a week. Stop following youtube tutorials on how to make specific stuff and go watch this first.
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
First the Essentials pathway and then Junior Programmer. They'll include the concepts you need to know
Okay two of you taught one thing for sure,
Avoid YouTube 😂 as much as I can 💀
99% of youtube tutorials are just "Watch me code this thing" with very vague explination of what is actually going on.
Yeah I immediately realized this after making something by watching a tutorial in YouTube,
I felt like I just copy and paste the thing by watching someone else doing the big thing,
It doesn't teach me the most of the scripting part but I do now understand the fundamental of the Unity game engine.
To clear my doubts I joined this server and started asking you all,
And it really helps me to clear my doubts thanks for guiding me.
Agreed 💯
Code that thing without a clear explanation
why OnTriggerEnter is called multiple times on single trigger?
Could be the speed at which the object is moving
It used to be, and probably still is, an awful lot of YT vids were from beginners who'd learnt a thing (often done in a bad way) and then thinking they know what they're doing and produce a vid showing the same poor ways
0.64 per second on z-axis, currently
You all are so smart in ts Im not gonna lie
Yeah there are a lot of videos that teach code that won't build or work in builds. Which suggests they haven't actually ever gotten that far themselves
A good youtube video is going to spend more time explaining the core concept of what you're coding and will have charts and visual representations of whats going on without much time being spent on how to actually implement it.
For Example: https://youtu.be/MrIAw980iYg?t=1618
Wassim Alhajomar's talk at BSC 2025, distilling all his vehicle simulation knowledge for game developers.
Accompanying article: https://wassimulator.com/blog/programming/programming_vehicles_in_games.html
Wassim's links:
BSC links:
Add logs and see what's actually happening, maybe its multiple child colliders on an object.
The speed doesnt affect it here
I only have single collider(with isTrigger) on a single object, so basically I have player with collider and rigidbody, floor with collider and the target object with collider(set to istrigger), adding logging it prints same object multiple times
What are you logging specifically?
Theres definitely an issue in your setup somewhere, or maybe you're expecting different results from what is really supposed to happen
private void OnTriggerEnter(Collider collider)
{
GameObject obj = collider.gameObject;
// if (curTrigger == obj) return;
// else curTrigger = obj;
Debug.Log(obj);
GameObject newObj = Instantiate(obj, trayTransform);
newObj.transform.position = itemPlacePos[trayCurRow++][trayCurCol++];
}```
is this script on both the player and the floor? i see you have is trigger selected on both of them
forgot to mention, this script only runs on player and the only collider with istrigger is the target
is the collider already intersecting with the trigger when you enter into play mode or enable the object the collider resides on?
Thanks you so much for sharing the tutorial 🙏
got to go, be right back
I'm not sure of your exact setup, but I do suggest looking at this
https://unity.huh.how/physics-messages/trigger-matrix-3d
Physics messages for OnTriggerEnter arent only limited to other colliders with isTrigger, depending on the setup. Not sure if thats your issue but I do also have to go. Otherwise it could be beneficial if you setup another scene with minimal objects (2 cubes) and test how trigger messages work.
Another thing is I would add logic so this code doesnt just instantiate anything it touches. Like use layers, tags, or a script on the other object to denote its valid to be instantiated via this logic
back
why they are not limited to isTrigger?
you can have one be a trigger and the other not a trigger, and both will get the trigger message
If thats a limitation you want on your side, you can check if the other collider has isTrigger set to true
rather than that, I am now checking if the object I am detecting is the right one
I think that half solves my problem
thanks I will figure out the rest
Guys, quick chat, I'm using the kinematic character controller and I noticed that when I'm standing still on a slope, its speed never resets, and I wanted to know how I can fix this, sorry for the inconvenience.
Hey, where would I learn the coding of games (movement etc..)? I'm not interested in making the maps or anything lol 😅
Is there a channel or am I in the right place here 😄
this isn't the place.
you can do it here#1180170818983051344
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also the resources posted in pinned
cheers nav
helo anyone able to help me out?
i have like multiple things i gotta do for my project but not sure how to implement them
!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 #🌱┃start-here
I've been working on a 3D Boxing game and the part I've been stuck on his making the glove not go through the head or body. I though of trying to make it so as soon as it collides with the head or the body the punch pulls back but obviously this issue makes it pull back in a sluggish unrealistic way.. What would be the best approach to make the glove not phase through the opponent?
You would most likely need some physics casts to determine the exact point that it collides. Is it currently just an animation plus physics message?
Yeah so the animation plays then once it collides the punch retracts
I might be better off doing it with a raycast though if I had to guess?
Not a raycast specifically, even a sphere cast would be fine. Though I'm not sure if this the approach you want
It does honestly look like the animation is just slow
Yeah
It's only slow pulling back when it collides. When it has no collision it's perfectly fine
Is there a way to make game objects inside of my player be flipped every time the player does without them staying in the same position?
wdym by "flipped" and wdym by "without them staying in the smae position"? Also how are you "flipping" your character
So because I have a 2D game in my player script I have a part where for example my default character position is to face right and I made it so when I look left and walk left the player sprite gets flipped to look left. But since I have game objects inside my player for some reason when my character looks left the game objects stay looking in the default direction (right)
You didn't really answer any of the questions I asked
- How are you flipping the player? Are you using the SpriteRenderer's "flip x/flip y" property? Are you rotating the Transform on the Y axis? Are you inverting the x axis scale?
I use the SpriteRenderer's flip x
well there's your problem
that doesn't affect anything except how the renderer renders the sprite
if you want to automatically have all the child objects and everything else flip, use a different approach. For example rotate the whole object 180 degrees on the y axis
for some reason
The reason is you're not doing anything that would cause them to flip
Alright I will try this and let you know if it works
I think you're going to have to make your own physics by reading the normal of what ever is below your character
So how would I go about overlaying dynamic text over a 3d object's materials? I saw something about using a RenderTexture, but surely there has to be a simpler way
I can only get this to execute if both game objects have rigid bodies, I have tried turning on the Is Trigger on the colliders, but nothing.
any ideas?
void OnCollisionEnter(Collision collision)
Of course it won't work if they're triggers. OnCollisionEnter is for physical collisions. What are you trying to do?
The expected interactions are listed here: https://docs.unity3d.com/6000.0/Documentation/Manual/collider-types-interaction.html @strange jackal
trying to get a sword to hit an enemy
In what kind of game? Usually you would just do a direct physics query for that sort of thing.
OnTriggerEnter is probably what you want
It won't exactly look pretty, but it'll get the job done
It's worth noting that, depending on what you're trying to do, it may not be as simple as just that. This is a starting point, though
ontrigger is working, thanks
Just an ask, but you wouldn't happen to have the hitbox just covering the sword and are expecting the animation to handle everything, are you? I made that mistake once.
it seems to be working... when I attack the animation moves the sword through the object and triggers it. I had the OnCollision working, but it had to have a rigid body, which has physics
I am useing a mesh collider on the sword
If you keep testing you might find that there are some hits that definitely SHOULD register, but aren't
I'll keep testing, but do you have some other suggestion?
The way Unity's animator works and how fast hit frames tend to be, there's a good chance you might find some enemies where one frame has the sword just before hitting the enemy and the next just after with nothing registering in between. Almost like your enemy used King Crimson
The cheapest solution is to just extend the hitbox so that it will be able to cover any potential frames missed, but there are probably better long-term solutions
ok, thanks!
the direct physics query as praetor suggested. if your animation moves fast, then its possible fixedupdate isnt running during the time that the sword actually overlaps with the enemy
What is this "direct physics query" you speak of? I'm trying to remember the problem I had in more detail and remember it's something that would occur the closer the enemy was to the edge of the player's hit range
a direct physics query ?
https://docs.unity3d.com/ScriptReference/Physics.html
physics overlap box/sphere/capsule are physics queries
a box would make the most sense in this case
ok, I'll be back in about 45 minutes, off to pick up my son from work
Oh THAT. That's why I just made the hitbox a little bigger in the back.
its nothing relatedto the enemies distance to the player, though that may cause the issue to happen more. the real issue is your sword isnt moving via physics but it's really just checking if anythings overlapping the sword 50 times per second using OnTriggerEnter or OnCollisionEnter. An animation is running once per frame, usually and hopefully more than 50 times per second
so the swords location is being updated more than physics is being checked
Right. It happens more because the margin for error is much greater and this was the only way I thought of to solve it at the time
Any idea why this is not loading the thing when I am basically coping the asset's path??
https://docs.unity3d.com/ScriptReference/Resources.Load.html
Note that the path is case insensitive and must not contain a file extension
...
The path is relative to any folder named Resources inside the Assets folder of your project
You added a file extension . . .
Yeah, it wasn't working without that either
my message included more than just the file extension
the docs describe it quite clearly
for example loading a GameObject at Assets / Guns / Resources / Shotgun.prefab would only require Shotgun as the path
I see, it looks directly on the resources folder
Was just about to say, you don't include "Assets" or "Resources" . . .
yea you're also limited to everything being in the resources folder, if you want it accessible by Resource.Load
there is also a ScriptableSingleton, though ive never used it. Maybe itll work for your case
If an object in scene is a prefab, can I get the reference to the prefab directly from the object itself?
no
hello, is it possible to just put the box collider on the "grid" component so that it'll automatically apply to all the tiles underneath it? or is there a much more efficient way to do this?
can you still use git/github with unity? or does it have to be the new unity version control
You can use whatever you want
If you mean in the editor, outside of play-mode, sure PrefabUtility is the place to start. But this is not the channel for such questions
You can have multiple "Resources" folders and it searches them all.
PrefabUtility is editor only so not usable for gameplay code.
It was kinda the idea. I want my items to be stored into a list/dictionary database. This is done by clicking on the big button once all the values are set to add it into the database, which stores only the id and the prefab. The thing is I wanted this to, in the case I somehow forget later and click the button on an isntantiated object rather than on the prefab, it would just search for the prefab of that item and add it instead
I also wanted it to be able to ask the database for its id, but that's kinda redundant cause basically the database already ask the object for its id when adding it anyways, so there is no point and I am just dumb lol
Is this an edit time automation?
If so yes you can use PrefabUtility to find the prefab asset an instance is linked to so you can then perform this operation
e.g.
string prefabAssetPath;
prefabAssetPath = AssetDatabase.GetAssetPath(gameObject);
if(string.IsNullOrEmpty(prefabAssetPath))
{
//Check if this is an instance in a prefab stage
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null && prefabStage.prefabContentsRoot == gameObject)
{
prefabAssetPath = prefabStage.assetPath;
}
else
{
//Get prefab asset path from nearest instance root
prefabAssetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject);
}
}
(prefab stage has to be accounted for specially because thanks unity)
What is even a prefabStage?
Is what you're looking for the tile map collider 2d https://docs.unity3d.com/6000.2/Documentation/Manual/tilemaps/work-with-tilemaps/tilemap-collider-2d-reference.html
I recently watched unity's video on game architecture with scriptable objects so I tried making an input system paired with simple movement but when moving the player it seems like the OnMove only gets called once even when the key is held, meaning I'd have to mash the key to get my player moving in a straight line. Is using a scriptable object a good idea for this or nah?
Those are two separate questions. The movement issue has nothing to do with SOs
I see, so whats the problem with the movement?
Look up how to read continuous input in the new input system, or ask in #🖱️┃input-system
ive decided to use godot
😆
im trying to export my new unity build on mobile and i cant update my sdk platform tools. i get the same errror every time
Error building Player: Win32Exception: ApplicationName='powershell', CommandLine='-ExecutionPolicy Bypass -File "C:/Program Files/Unity/Hub/Editor/6000.2.2f1/Editor/Data/PlaybackEngines/AndroidPlayer\Tools\RunElevatedCommand.ps1" -ArgumentList Ignored "C:\Program Files\Unity\Hub\Editor\6000.2.2f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\cmdline-tools\16.0\bin\sdkmanager.bat" "C:\Program Files\Unity\Hub\Editor\6000.2.2f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK" ""cmdline-tools;16.0" "platform-tools" "build-tools;34.0.0"" "C:\Users\admin\Doppler\Temp\AndroidSDKTool"', CurrentDirectory='', Native error= The system cannot find the file specified.
Anyone know a fix or any sort of suggestions, been trying to fix it for a week now
try uninstalling and reinstalling the android build module
how would i uninstall just the android build module (sorry, new to unity)
unity hub should let you right?
Is it withing here?
Hey, I'm interested in making a 2.5D pixelated game on unity however i'm struggle to find any tutorials on making such a game. Anyone know where i can look for these tutorials?
No different than 2D really. You can still use spriterenders on a 3D scene
hey what would be the correct way to calculate the uv coordinates for my 2d mesh used for displaying background of my softbody system? my x and y coordinates are between (-1, -1) and (1, 1). this is what it looks like right now
Does anyone know any good YouTubers to learn C# from—especially ones that go into abilities like flying? If not Anyone will do.
Thnx
This was from a few days ago right? Does the uv need to remain "square" regardless of shape?
i dont know does it? i mean its always more or less a square but its getting squished. also the system should work for a sphere or other shapes too. would it help to send my code?
in both cases it should work to judge the bottom left bound as 0,0 and the top right as 1,1
then use this to figure out the uv for a vert
ones that go into abilities like flying
that's not part of c#
there are pinned resources in this channel
okay that makes sense but how would i do that?
if you know the bottom left bound, subtract from the vert position
Then divide by the bounds size to make it be from 0 to 1.
you can make a Bounds object and use Encapsulate() to make it fit all verts or calculate the min and max yourself.
okay ill look into it later when i have more time again thank you
how do i change a scale of an gameObject in a code?
thanks
tried reinstalling but still doesnt work, know any other suggestions?
These are all my external tools path if that helps.
Is there maybe a setting i could've accidentally turned on that causes this error or is this purely an installation issue
can't you just use screencoords offset by your objects position
nothing really's in screenspace but mouse cursor..
it all needs converted to either world space or viewport space (if UI)
I know you have to accept the SDK license at least once so it may be that? Check editor logs if it's mentioned
thank you for the suggestion, where would i find editor logs
!logs
check above
thank you
For some reason Auto comment doesn't work for me
unfortunately looking at the errors i didn't find anything different. Is there a way too check if you accepted the SDK license or a way to re accept it?
https://discussions.unity.com/t/problem-with-sdk-platform-licenses-update/941510
you can see if you have licenses in VERSIONHERE\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\licenses
if you use android studio to manage the sdk if can be easier as you can accept the license via that
wait what's sdk
android sdk. tis mentioned in the message
ok thank you
Why does this script crash my entire pc https://pastebin.com/gTP1WjyG ? I don't have any error messages because it just closes every program on my pc and doesn't show anything. I have tried restarting my pc and reinstalling my packages.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
idk about crash entire pc
but x < height
doesn't look correct here...
line 59
why does this happen? will unistall and reinstall fix it?
that package is no longer used. see the instructions for configuring vs code below 👇 !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
thanks✨
It works now, although I guess I should have expected that a single letter would break my script... Thank you for your help
ok i have looked at my code for 2 mins and i fixed to lines now it works. the formula converting the -1 to 1 coords to 0 to 1 coords was correct but i had to cast a value into a float so it doesnt get divided into an int, also i added an extra uv coordinate for the center point which wasnt listed before as it was outside of the for loop managing verts and uvs before.now it works perfectly fine
also a big thanks to you because no one has helped me as much with this topic as you. i learned a lot and would have never been able to do all that with out your help
eyy nice job! and if using literals you can do 1f to ensure you get float/float
i still have one question though, what would be the best to stop them intersecting? can i mmoify points of a polgon collider or something lke that?
thanks! what do mean exactly? my formula was (x+1)/2 before, i just changed it to (x+1)/2f
wherever you needed to cast to float, your positions should all be float anyway
so like (x+1f)/2f?
yeah the licenses folder/file doesnt exist at all, that probably is the problem thanks
if x is a float then it will be float operations anyway but often best to use float literals with float stuff
oh okay
This Grid Layout Group for desktop items isn't playing well with drag and drop re-arranging. I'm using sibling indexing and anchor positions while accounting for the layout group grid.padding, grid.cellSize, and grid.spacing properties.
Snap to grid cell works perfectly, but only for the last item in the layout group.
Any desktop item dragged before it will instead select and drag the last item.
It must be the layout group re-organising itself right?
All cells are being recognised correctly, so the Math is correct. It's to do with OnEndDrag and my PlaceItem function surely.
I tried temporarily removing it from the layout group upon dragging and then re-placing it after dropping, but it does not fix the root issue.
What is the simplest way for dragging and dropping my Desktop Items so that they align with the grid layout group cell space of 12 rows and 5 columns while having the desktop items independent of each other? (I can post my DesktopItem and DesktopGrid code if you're fine with looking through it for me.)
Do it yourself is the simplest answer. You can round the position to some grid
Yeah was curious whether there are easier ways to just be like "hey grid layout what is the position for all cells, even those which are currently empty?".
The whole cell thing is working fine as it is though, so this part is okay. It's just the OnEndDrag and PlaceItem functions I'm sure.
I realise after some debugging that it actually does recognise the dragging of other items in the group, but it'll only actually select and move the most recent item.
Has anybody used Vivox and tried to leave all channels and log out before the application quits?
I'm trying to do this for when you exit playmode in the editor, but I can't figue it out 🧐
I would love to hear how this is supposed to be done if anyone knows
If gridlayout is the problem you can try your luck at using a combination or horizontal and vertical
gridlayout is just garbage in general and doesnt resize like the other layouts correctly
more of an issue for different resolution ratios
Yeah I'm thinking about this all too much. The grid layout group helps with both keeping columns and rows for my desktop items, and while providing responsive design. Like, in future, I'll have a button where players can toggle to new "desktop" pages to hold more items/programs, so the grid layout seems important here.
Really want it to be as flexible and as responsive to different screen sizes as possible.
It's just one issue which surely cannot be more difficult than the drag and drop snap-to-grid torture that I had endured (lmao).
It'll be solved - just frustrated at the moment and took some short breaks too xD
sorry for bothering again, I've been searching for a while but where would i find the license agreement on adroid studio
https://developer.android.com/tools/sdkmanager#accept-licenses
try this in the SDK folder
If using android studio it asks when you download an sdk in the UI so after that you can just change unity to use that instead
Hey! For anyone that uses UI toolkit, do you have any idea how I can change the text/background color of a tab?
aye! perfect example of "keep at it" until u get a good result
pretty impressive progression i must say
Thanks bro had one last problem i found in the mesh generator for the background, was an easy fix tho. Now the next thing to do is making it automatic!
Hello everyone, I'm a beginner and I started my 3D game yesterday. When I reopened my project, it said that my URP is too old, and now none of my objects can be seen in the scene and the materials do not load.
Thanks bro i appreciate that. That is definitely the hardest project ive ever done but i wont give up until i can really call it a game
select something like your player and press F to make it refocus the scene view incase its just zommed weird
here it is
its in unlit mode rn too: https://docs.unity3d.com/6000.2/Documentation/Manual/ViewModes.html
continue asking about this elsewhere #1391720450752516147
alr thx
hey yall, I'm starting out learning unity by doing chess following Etredal's youtube series on it, but instead with the new unity input system. I've followed chonk's youtube detect clicks guide, made an InputHandler script and object and can verify a click through the debug board.
How do I have the piece itself know that I've clicked on it and do stuff with that? The only tutorials I can find use a single object that is designated as player, instead of multiple pieces in an array that a player owns
if this question is better in input system please let me know
its hard to say more without code being shared but if you can click on many objects and have some data on each instance then you are half there already
Perhaps each piece has an event that is invoked when its clicked so some central manager can react to each piece?
Does this tutorial not go into this part though?
Created me a Strict Error Handling System
here's the source if anyone's interested 😆
https://hastebin.skyra.pw/enagapavek.csharp
you must now create a "Lenient Error Handling System"
good luck 🫡
the tutorial utilizes OnMouseUp to tell the pieces they're being clicked, which I presume I need to replace. I also haven't done anything with events except for in my InputHandler, I don't know if I should add more. First image shows that all pieces are within one object/script, if that helps at all. Second image is the InputHandler
Oh so you already locate the clicked gameobject so you can get a component of your creation and tell it do so something
e.g. gameobject.GetComponent<ChessPiece>().OnClick()
using components is a core concept of unity
Too bad this tutorial looks a bit shit
(using the gameobject name to then assign a sprite using a switch case is pretty shit design)
do you know of a better tutorial for a board game?
I dont but do they not do anymore?
Doing tutorials is a good way to learn but at some point you want to start doing things yourself (else you will be in tutorial hell as its known)
I was going to use the chess implementation to make my own board game. My problem is every single tutorial for the new input system that I see is platformers with one moveable character when I want to be able to place and move pieces
tutorials are always a good way to expose urself to new ideas/ new systems/ new components
but always need to be supplemented w/ ur own research to learn about the core concepts and adapt them to your own use-cases
input is just a small part and tbh you can easily swap one for the other
anyway i can tell this tutorial is gonna teach you some bad habits
^ very much so.. inputs are a considerable piece of the puzzle for all games..
once u figure out the input system ur using either new or the old.. you can pretty much adapt that as u like as well..
plus alot of table-top games are mostly gonna be based on Mouse-Input
A person who can actually code and use unity who made chess: https://www.youtube.com/watch?v=U4ogK0MIzqk
My attempt at creating a little chess playing program!
Think you can beat it? Give it a go over here: https://sebastian.itch.io/chess-ai
Support my work (and get early access to new videos and source code) on Patreon or Nebula
Source Code:
- GitHub:...
its not a tutorial but shows his thinking and some code for how things get created
start small.. -> grid -> then input -> selection
hardest part in my opinion would be the state-machine
"when" are you allowed to select a tile/grid
"what" happens, "then" what.. etc
In my rigidbody-controlled player, I have a if-statement in a function called in Update() that looks like this:
float cameraSpeedLimit = 0.2f * m_CurrentSpeed;
if ((m_KatamariRigidbody.linearVelocity.magnitude < cameraSpeedLimit) && m_IsTouchingSomething)
{
...
}
In short, as long as the player isn't moving above a certain speed and they're touching a surface, the if-statement's code is executed
It works well, but before I make the player move, the first statement always returns false, despite the fact that my player's speed is 0 (and I have a constantly-updating debug variable set to rb.linearVelocity.magnitude that corroborates this)
Normally I would assume that it meant the linear velocity wasn't assigned yet or something, but the player starts in the air and falls down to the ground, so I don't think that's it
Does anyone know why this is happening?
I'd like to learn unity, I have some prior programming knowledge but not C#, what are some good courses which are free / cheap?
velocity has to build up over time even if it "starts" in the air
and the velocity may not change for a few frames till its time for the next physics update
not sure why you arent using FixedUpdate
this is cool but them even just generating the board and pieces is super overwhelming, especially since I'm new to unity and have no idea how he's doing things
!learn is most often recommended
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
will this teach me everything I need to know?
yes..
ok thanks
yea I get it is. understanding more how to use unity and also c# programming in general will help
unity learn resources is a good place they have lots of stuff
https://www.youtube.com/playlist?list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw this is my personally recommendation
like a crash-course
thanks, but which one should I start with?
unity learn or this
unity - learn is hands-on.. text/vid courses.. its slower but lets u experience it hands-on step by step..
the video just goes over the basics, code, the editor, concepts of programming..
two different things really.. you'll probably end up doing a little of both.. (if u want)
but if u want one that will cover everything its unity learn...
but theres multiple pathways.. and it'll take quite a bit of time to do em all
unity learn is Unity's official stuff
do u think watching the youtube course first to even see if unity is for me and then watchin unity learn to know more about different fields is a good approach?
you'll most likely need to
do unity learn stuff
experiment urself inside the engine
watch some YT videos
check out the Unity Documentation
read Unity Discussion Threads/ Stackoverflow posts
ask questions and learn from people here
rinse and repeat
using as many sources as possible..
ya, the videos are short and sweet...
if u watch the first couple.. you'll already be getting an idea of whats to come
nothing wrong wth jumping around either..
burn-out can occur even whilst learning... soo may be benificial to switch it up
but also we all learn differently..
ok thanks that was really helpful
the first few are enough to judge for urself
I appreciate it
Will a non-async function still wait for an async function?
public void Start()
{
print(Time.time);
SignIn();
print(Time.time); // Will this be later?
}
public async void SignIn()
{
// example
}
no
https://gamedevbeginner.com/ one little extra source..
i find myself posting content from this guy alot when explaining
certain concepts.. may be nice to have it on standby as an auxillary source
you have to await it to delay execution of things after
Can I set start to be asynchronous?
yes but its recommended to use UniTask or Awaitable instead of Task
lol.. username made me chuckle
unitask/awaitable offer ways to wait within the unity update cycle correctly + other things
Sorry, I should have said
This if-statement's contents are listeners for player input events (specifically, entering different camera modes) - nothing happens unless the player presses a button
I've only tried to press the button after the player has landed, so I doubt the problem is that I'm pressing the button frame 1 before there's any velocity
Can you provide guidance based on that?
put a breakpoint and debug this properly using a debugger
then you can see what exactly happens when you trigger input
Help please``` External Code Editor application path does not exist (C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe)! Please select a different application
UnityEditor.DefaultExternalCodeEditor:OpenProject (string,int,int)
Unity.CodeEditor.CodeEditor:OnOpenAsset (int,int,int)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Any reccomendations for learning player input events? I want to do many things with mouse and button clicks.
I graduated college with a minor in game design and development. I still want to continue to learn coding C#! What's the best route?
Provide more context with your question. The error simply says that vs2022 is not installed
!learn and then reading docs, other people projects, tutorials, etc...
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Old post but no need to be sorry my friend. You are never a burden. Infact, many of us love helping each other ❤️
How can we make our unity game multiplayer?
code
By clicking the multiplayer button in the project settings. Once pressed it will add multiplayer to your game, no coding at all...
And don't forget that it would make your game a "WoW killer"
if ur on unity6 i recommend u to use netcode
Which one do you guys think is better for learning unity? https://www.youtube.com/watch?v=AmGSEH7QcDg https://www.youtube.com/playlist?list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw
💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
❤ Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🎮 Play the game on Steam! https://cmonkey.co...
It wont stop on one course or one video like 1 year into game dev and i still find a lot of stuff i have to learn... then i suggest you to start with the code Monkey video to get general information about coding and then you could start by getting into more and more tutorials but be aware don't copy and paste what you are learning but instead learn it in depth to not fall into tutorial hell.
If anyone got another opinion am glad to hear it out.
👋 Unity dev here – I do bug fixes, custom scripts & multiplayer (Mirror/Photon).
we don't really endorse DM support here
Yall r mega minds
well, do you know basics of c# yet? my honest recommendation would be to learn c# before using the unity apis
if you understand basics of programming or are coming from a different language however, no need
Learn C# as is without unity, learning with shit tutorials wont do you much good
I need help, I'm __instantiating __an object called wallPrefab, my prefab has a BoxColllider2D and a ShadowCaster2D. I'm setting all my objects parent as an object with CompositeShadowCaster2D, but when trying it, my Light2D don't cast any shadows, it's very bright and not dark at all... what can I do? (my ShadowCaster2D is already set to my BoxCollider2D in my prefab)
GameObject map_obj = new GameObject("Map");
GameObject shadowParent = new GameObject("Shadows");
shadowParent.transform.SetParent(map_obj.transform);
CompositeShadowCaster2D composite = shadowParent.AddComponent<CompositeShadowCaster2D>();
foreach (Boundary wall in map.walls)
{
GameObject wall_obj = Instantiate(wallPrefab);
wall_obj.transform.SetParent(shadowParent.transform);
wall_obj.transform.localPosition = new Vector2(wall.pos.x, wall.pos.y);
wall_obj.transform.localScale = new Vector2(wall.size.x, wall.size.y);
}```
Trying to do the "Tanks!" tutorial. When I get to the step of adding a level to the scene the levels are all just pink shapes on pink backgrounds like some texture or color information is missing. Any ideas on how I goofed this up?
Pink means shader error. Usually means that the materials are using a shader that is not compatible with your project's render pipeline
It would be just like me to miss a step where I was supposed to change the render pipline. Thanks. I'll check for that.
most old things still use the Standard shader which is non functional in URP or HDRP
newer things often use URP or have a URP version too
Just installed it, when I run it it says 'Must Fix All Compiler Errors'
The instructions call for the project to use the Universal 3D which I did. So I guess it's just non-functional? I'll find a different tutorial.
I fixed it
I don't know if you have tried this, but when you upgrade to URP you need to select all the materials and go to Edit -> Rendering -> Materials -> Convert Selected Built in Materials to URP
The "Convert..." is greyed out for me.
screenshot what ur seeing
This is the tutorial I was trying: https://learn.unity.com/course/tanks-make-a-battle-game-for-web-and-mobile?version=6.0
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
code channel 😬
The general problem is when I import the assets for the tutorial I get this sort of pink rendering of assets. Since I only installed Unity 3 days ago, I'm mostly clueless about what this means.
as mentioned.. this means your current materials shaders don't match compatibility with the current selected pipeline of your projects
Check what shader it has, the drop-down below the material's name in the inspector
Checked a few and they say "Universal Render Pipeline/Lit".
then your project is not set to URP
you can can look under Project Settings -> Graphics and double check
Thank you! That was it. I had no idea I needed to set that. I just selected "Universal 3D" when creating the project and thought that was enough.
usually you don't.. this is a new Universal 3D template.. typically comes assigned..
with a few presets in the project folder
for dragging UI objects out of the canvas, how can I make it so that the object won't disappear when I drag it outside of the canvas viewing port?
Like I want it to be on the screen when I move it out still
so even if I remove it from the canvas it won't work?
☝️
darn
My bad. It was the only channel labeled "beginner" which I definitely am. I guess maybe "unity-talk" would have been better.
but the very first word is code 😄
Yes, #💻┃unity-talk would have been better
I figured it out, thank you Carwash that hint was good
Hey, I need some help for making animation. I drew a player punching sprite sheet for 5 different costumes. I wanna add customization to my game so I need to animate 5 different costumes and their 3 parts. But idk how to use animation layers. Also, do I need to add more conditions for each part like (bool)char1headPunch, (bool)char2headPunch.....
this seems more of an animation question than code.
I have this feature where the player can pick up objects but when I pick up objects it doesn't follow the player properly when moving around / looking around. any ideas? https://paste.ofcode.org/irxXgMLQXHeYHk9Ru4nYXj
try turning interpolation off?
Oh shit nice one thanks! I though interpolation basically makes it smoother when the object moves around
Why does it do "That" when its on?
I'm guessing cause its being forced to move via transform / parenting so it doesn't like that
particularly kinematic
sorry, I'm a complete beginner and I don't quite know where to put this, but why isn't the main camera showing??
i searched everywhere and can't find an answer still
showing what? the sky? did you change any settings on it?
the UI itself
I can't get past the first tutorial cause I don't know if I have a camera or an empty object
the camera is there... its just set to render solid color instead of skybox
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
unless you somehow removed the skybox material in the Lighting tab
would be a good idea to start..
If in the inspector it has a camera component then its fine.
The gizmo icon may not be showing as the scene cam is too far away (press F to focus on it)
and it doesnt help much if you just shjow the camera view.. the settings are more important
I pressed f and the gizmo didn't show up
try this
(somehow you turned them off)
but its a small thing to worry about, the inspector told you what you needed to know
That makes a lot more sense, I think it starts off with the gizmo bar and everything else tuned off unless you turn it on in the overlay menu
ps your settings are on orthographic...
ah ok then its okay
3d view orthographic as i understzand is good for 2d things..^^
2d -< 3d games^^
or it gives 3d a 2d look^^
simple said
please could someone help a namespace i know is correct and is the same in other scripts is saying the namespace doesnt exist
yeah i know english is not my native language probably i used the wrong words^^
just trying out chaingeing makes it simpler to understand^^
check spelling? also make sure if its in another assembly definition that yours references it. If you dont know what that is then thats probably not the case.
I have copied and pasted the exact words
well if thats the case and its not in a different assembly then there is no other reason
unless namespace was part of a package you don't have
hmm yea what does "other scripts" mean
agh nevermind i figured the reason one of the scripts was in the editor folder
if you just copied and pasted .. probably you dont need the amespace just delete the line... and the { } brackets at start and end
easy fix!
if its just 1 script doesnt matter
Would the use of subroutines for resolving card game logic(when a card asks for a target or requires a player decision) be a good idea?
unless concurrent stuff can happen as far as these decisons i think i would just control that flow with a really simple state machine
Can't speak to whether or not it's a good idea, but that's what I do for target selection in my JRPG system
Can some one help me pla
I want to creat game rp online for every jops police army ems all but i dont know how to make
This channel is for code questions.
This server is not for large vague questions like that.
!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 #🌱┃start-here
I'm a beginner trying to implement a scene management system. My game is going to have a large number of scenes. As I am coding it now, I have my scenes call the scenemanager and tell it to go to the next scene. Is this ok? The other option I see is having some flag that says when the scene is "done" and having the scenemanager check for that constantly and handling calling the next scene. Seems more complicated but maybe better design practices? Is there a standard practice for this? I watched 5 or 6 youtube videos and they seemed like they had different approaches and were more complicated than I was hoping for. Any thoughts would be apprecaited.
It's never standard practice/ good to constantly be checking for some event to happen.
Your first idea is the simplest way
I am having this small issue where when I try to go and pick up an object I have to press a few times to pick it up for some reason its like the ray isn't detecting it at all. Any ideas? https://paste.ofcode.org/Fb6bt6RmW4JqBeuJNR9Pyy
does anyone have good video tutorials on how to code in unity?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you
yes, don't nest ur Inputs inside the raycast
right now your WasPerformedThisFrame() check is inside the raycast, so it only fires if you’re both hitting something and pressing the button that exact frame
thast why u have to keep spamming the button (until u get a perfectly aligned situation)
you should instead use a boolean... or assign the object to a variable..
and for ur input u can just check if ur raycast has assigned an object
if it is then u do ur interaction
it'd be like me putting if(Input.GetKeyDown) inside an OnTriggerEnter
the only possible way that would ever work is if i press the Key at the exact same frame we entire the trigger..
instead we'd want to change a variable when we enter the trigger.. and remove it when we leave the trigger
and then have the Input work independently of that (just checking if the variable was assigned)
how long did it take you guys to learn how to code? i wanna start learning but i dont know how long itll take or if i have to time
obviously it might take me longer or quicker than other people but it can give me an estimated time
// Check input
if (Input.GetKeyDown(KeyCode.E))
{
if (currentTarget != null)
{
currentTarget.Toggle();
}
}```
for example my input is running in update ^ ... it doesn't *have* to be sync'd to the raycast
the currentTarget is either assigned or it isn't
or like
```cs
private Rigidbody cachedInteractable;
void Update()
{
if (Physics.Raycast(_camera.transform.position, _camera.transform.forward, out RaycastHit hit, maxDistance))
{
if (hit.collider.CompareTag("Interactive"))
cachedInteractable = hit.collider.attachedRigidbody;
else
cachedInteractable = null;
}
else
{
cachedInteractable = null;
}
if (interactAction.action.WasPerformedThisFrame())
{
if (cachedInteractable != null)
Debug.Log("Interacted with: " + cachedInteractable.name);
}
}```
the raycast did that for me... (so when i go get my input it doesn't care about the raycast at all)
it took me a couple months or so before i felt i could venture out on my own..
then i could just look up things as i needed to.. (checking documentation and whatnot)
im 4-5 years in and still learning
okay thanks, i think ill start learning soon
How do you actually "learn" the coding from videos i just watched and recreated a flappy bird game and just know what 2 lines do
rinse and repeat..
if u watch another tutorial.. u might know what 4 lines do..
and if u watch another.. u might know what 8 lines do..
You don't. You learn by doing, looking up things you don't understand, and making an effort to experiment and get an intuitive sense of what each line does
but basically u need structured practice..
pick a goal... practice that goal..
learn from that practice
Thanks man
if it was as easy as just watching a video
i'd have a black-belt in karate
be a professional race-car driver
and so-on lol
watching videos are good at exposing urself to new ideas and concepts..
"Today I will do X, how will I figure it out"
but u never want to leave it at that...
use what u heard or seen in the video.. and go look up the things urself..
And like train your brain for problem solving
If anyone is familiar with UniTask, can someone tell me why this method executes all of the tasks immediately, rather than doing them in sequence and waiting on each one before starting the next?
private async UniTask DoTaskList(List<UniTask> uniTasks)
{
for (int index = 0; index < uniTasks.Count; index++)
{
await uniTasks[index];
}
}
Watching a video can help you learn, but the point is to use the video as a tool to solve a problem you have identified and defined.
There is a difference between "Hm... I don't quite understand the description of the cloth component, I think I need to see this in action to know how the settings affect the visuals" and "Making DOOM ETERNAL in Unity! (Part 417)"
The "tasks" are already running, you are simply awaiting them later in sequence
You would need to call + await them in sequence instead
make sense?
So what would be the correct way to gather a list of tasks without running them, and then iterate over them and await them in a for loop?
private async UniTask Shrink(Image image)
{
Debug.Log("Shrinking " + image.gameObject.name);
float timer = 0f;
float duration = UnityEngine.Random.Range(1f, 2f);
while (timer < duration)
{
await UniTask.Yield();
timer += Time.deltaTime;
image.rectTransform.localScale = Vector3.Lerp(new Vector3(2, 2, 2), new Vector3(1, 1, 1), timer / duration);
}
Debug.Log("Shrinked " + image.gameObject.name);
}
I made these for testing
then you can invoke and await each in sequence
Ahh, list<func<unitask>>, that's what I needed
So the solution is to have a list of function references instead of Task objects
List<Func<UniTask>> taskList = new List<Func<UniTask>>();
Not sure how to add a method to this list though, as befoire I was doing
taskList.Add(Stretch(image0));
thats calling the function and adding the returned object to the list
private async UniTask AsyncThing()
{
}
taskList.Add(AsyncThing);
add the function itself
for things with args you need a lamda to wrap the call
taskList.Add(async () => {
await Shrink(image);
});```
Just now stuck on how to await an item in that list of func unitask
you will invoke the Func and await it
await tasks[i]();
Action and Func are pre made delegates that let us have references to functions
therefore we can invoke them and await them if they return a task
Success! Thank you! Was trying to get it to run multiple lists of tasks concurrently (do A, B, and then C on object 0, while simultaneously doing A, B, and then C on object 1, and then continuing when all tasks are done on both objects)
Better design can let you execute and await things with more control
e.g.
List<UniTask> tasks = new():
tasks.Add(ThingA());
tasks.Add(ThingB());
//Waits for all tasks in the list to complete
await UniTask.WhenAll(tasks);
await ThingC();
you can also do await UniTask.WhenAll(A(), B()); if you dont need a collection
Unfortunately I do need a collection, but I can use WhenAll on the methods that processes a collection to get the right result
you can check the unitask readme for more info on what other things they offer
but most things that exist with Task also do in UniTask
Guys, what's the best controller for creating a fast paced game? Like Ultrakill, Doom
there is no best
figure out what you need and what you want it to handle and what you want to control
Well, you've a choice between the Character Controller or Rigidbody controller. For Doom you probably don't need rigidbodies so Character Controller is a good start, otherwise Doom controller isn't that hard to recreate yourself.
Quake controller is a bit more fluid though and not the easiest to recreate. I'd look around for projects that have attempted a controller for it
Can somebody teach me the basics of Unity Vr game creating?
Is there any way I can get Vector2.Distance to recognize the distance between the player and a transform that's not listed in the variable list. Cuz Im tryna make a system where you can pick up items, but not tryna make 100 different if statements based on every single different item
Vector2.Distance just does some math on 2 Vector2s
it's irrelevant to what you're asking
you need to get references to stuff you want to access
Rn I have a system where you can only pick stuff up based on the distance between the player and the object
if you have a ton of items you want to get the distance to, perhaps have them all register into a central list you can iterate through instead of a serialized list
no. also don't crosspost
https://learn.unity.com/course/create-with-vr
you could also use triggers or casts/overlap checks to avoid needing a list altogether
Well, for what you're making, you attach a script to the thing you want to pick up and put in
void OnTriggerEnter(Collider other){}
Then inside the function you put what ever you want to happen when the two colliders intersect
now's a great time to learn then, because these are really useful tools
first though you should probably design out the behavior you want to have
Although the item's collider has to be a trigger for this to work (It's a toggle in what ever collider component you have for you item)
These are going on my list of stuff to learn after the current game jam ends
not necessarily
As I recall, either the player or the item also needs a rigidbody for the physics system to work at all
I want it to be based on playerinput and not collision since you can only have 1 item "equipped" at a time
for something like this with triggers, you would have a larger trigger volume on the player so the item doesn't have to be inside you for it to work
the item could also be a trigger but that's a separate thing
that's unrelated
this is about detecting items to begin with, presenting the option to equip them
ok
If you want to be more accurate, you should only allow the player to pickup the item if they're close enough and the player is looking at it . . .
public TileIndex TileFromObject(GameObject piece)
{
TileIndex tile = null;
foreach(GameObject t in tileMap)
{
TileIndex tempTile = t.GetComponent<TileIndex>();
if(tempTile.Piece?.gameObject == piece)
{
tile = tempTile;
}
}
return tile;
}
if the piece has been destroyed, and my normal program flow is interrupted (which usually sets .Piece to null), the reference is 'missing' in the inspector. But it still causes a reference error whereas null does not. How do I guard against this?
You can't use null propagation: ?. or ?? with a GameObject bc Unity overrides their equality check . . .
Oh, I confused the piece parameter with the Piece field, but the same thing applies; if Piece is a Unity object, you can't use the null propagation or null coalescing operator . . .
Piece is a TileIndex class
Also, you don't check if tempTile is null before accessing it . . .
I can be reasonably assured that all the objects in tilemap have tileindex components
no need
Oh, so the Piece object on tempTile is the issue . . .
sure, if Piece is null or a valid GameObject reference everything works fine, but when I click a bugged tile in the inspector it says "missing" in the field.
it's still related to GameObject because it only bugs out when a GameObject is destroyed and Piece = null wasn't called
Okay. What do you mean by bugged tile?
I read a little bit about fake nulls and the == override but didn't really understand it.
The Unity website seems to be missing code in its explanations.
well it's a chess game so each tile has a reference to the piece and well I'm sorry but I just checked and it's a ChessPiece class which is also mine but it extends monobehaviour
a gameobject with a chesspiece class will be destroyed and that makes the Piece reference say missing instead of null
but really I just need to know what to do instead of what I was doing. I don't know how to check for 'missing'
fake null?
maybe include links next time so its not so hard to help
try a different browser.. (looks like the code embeds aren't working for you)
link
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Before destroying it, you can set Piece to null . . .
I might be braindead
I can't believe I didn't think of that, but a more robust method would be nice too..
You'd have to create a method to do that. There's no way Unity would know the relationship between a GameObject and a MonoBehaviour class to assign a specific field null . . .
If I have public Wheel: WheelBase and wheel base inherits from monobehavior will start be called in both classes? and what order will they be called in?
Should FixedDeltaTime be factored into this? (Moves a 2D ship left to right).
Just toss it in fixed update and you're fine
Is it possible when you have a tiled background to move the tiled BG in the Y but not physically move it, instead kind of scroll it while it also "regenerates" so it's acting like it's a ribbon that's just turning. Basically a background of star tiles that slide down. If that makes any sense. I don't want to physically move the tiles because it's only slightly larger than the camera.
So I have enough of these little canvas objects in the scene that I'm pretty sure are tanking performance. Is there any way I can do that occlusion culling thing I've heard so much about with them to increase performance? Will such a thing even work to increase performance if it's even possible at all?
The first thing to do would be to remove the "pretty" from "pretty sure" by confirming with the profiler what the problem actually is
There's absolutely nothing else it could be. It only started happening once I started generating more of them
Yes but there's more to objects than just rendering. For UI objects rendering is very rarely the bottleneck or the rendering problems are caused by something else like excessive text updates
Does it count as text updating if I have these canvas objects rotating every frame?
Not in that sense but that means you do have scripts on them (or scripts acting on them) so that might just as well be the source of the performance issues
So how would I solve this problem? I need those scripts there
Use the profiler
I did. It doesn't even want to run
Or rather it's struggling really hard
And the data I get from it is stuff I can't make sense of
Then ask about that first, there's no point in trying to solve a problem when you don't even know what the problem is
I do know what the problem is. There's a bunch of objects with scripts on them in the scene and it's causing my performance to tank
Ok but I can't help with that if all you can tell is "bunch of objects with scripts on them"
What ever it is it's so bad that I can't even really use the profiler
But you still get data from it? If you really can't use it because it's too slow then remove some of the objects until it's usable
If you can tell me what this means beyond anything I've already said then I'd like to know
ScriptRunBehaviourUpdate is what runs the Update methods. And you can see that rendering only takes 8.35ms so it's not the problem (and therefore the answer to the original question is that occlusion culling would not help.)
So I would just remove any code from the update function? Because that's not helping either
The screenshot shows only a small part of the output but what's there you could consider if all the UI elements really need to react to input
What?
Tried to follow a guide on using particles to make stars and the person cut off half the code on the website. Oof.
hello
i have a very peculiar issue
//bar.tick is false.
public void Left()
{
if (bar.tick)
--curr;
dl.cont = true; //this works
}
public void Right()
{
if (bar.tick)
++curr;
dl.cont = true; //this fails, but only on one particular sentence
}
bar.tick is false when you call Right(). That means ++curr; doesn’t execute, so nothing appears to happen, but dl.cont = true; still runs
yeah so what I mean is
despite the two functions being LITERALLY THE SAME THING
for some reason Left() works perfectly fine but Right() doesn't
where do you calling these methods ?
in buttons
show full code
public IEnumerator createDialogue(Speak speak)
{
charbg.gameObject.SetActive(true);
dialogue.transform.parent.gameObject.SetActive(true);
character.text = speak.name;
character.rectTransform.anchoredPosition = new Vector2(0, 0);
charbg.anchoredPosition = new Vector2((-speak.side) * 120, 220);
charbg.anchorMax = new Vector2(speak.side / 2 + 0.5f, 0);
charbg.anchorMin = new Vector2(speak.side / 2 + 0.5f, 0);
dialogue.text = "";
bool special = false;
highlight = "";
type = "None";
for (int i = 0; i < speak.text.Length; ++i)
{
if (speak.text[i] == '|')
{
special = true;
dialogue.text += "<color=green>";
type = "Evidence";
}
else if (speak.text[i] == '#')
{
special = true;
dialogue.text += "<color=orange>";
type = "Question";
}
else if (speak.text[i] == '@')
{
special = true;
dialogue.text += "<color=#00ffff>";
type = "Agree";
}
else if (speak.text[i] == '\\')
{
special = false;
dialogue.text += "</color>";
}
else
{
if (special)
{
highlight += speak.text[i];
}
dialogue.text += speak.text[i];
}
if (!cont)
yield return new WaitForSeconds(GameManager.delay);
}
while (!cont)
{
yield return null;
}
cont = false;
foreach (Evidence evi in speak.reveal)
{
rooms[evi.room].Add(evi);
}
foreach (var kvp in speak.unlock)
{
if (characters[kvp.Key].limit < kvp.Value) characters[kvp.Key].limit = kvp.Value;
}
FindObjectOfType<RoomMenu>().refresh = true;
yield return null;
}
dl.cont points to cont here
it's not full code lol
too long for discord
anyway this is the only code that reads from dl.cont
oh
wait
the only reason the left button worked is because it was overlapping a different trigger
my bad
For future reference, post large !code using these links instead of within the chat . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 have an issue with my ui where i can hover on two things at once my scrolling using a gamepad and then hovering using a mouse.
Have you tried debug logs
or a debugger
i need help fixing a weird bug
so im making a first person shooter, and i put the guns in a way that would appear good for the camera that renders the weapons (second image) it also looks fine in the editor (show in the first image) but when i try to test it in game the guns always appear far away from the player (shown in the third picture) and i don't know how to fix it, i tried changing the code but it didn't work, the gun in game spawns far away from the player and it moves along with it, i dont know whats going on, can anyone help?
share some !code and better screenshots why is the second so shitty
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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's the correct way of doing this?
selectable.OnPointerEnter += OnHover();
you subscribe the function instead of the returned value of the function when called:
selectable.OnPointerEnter += OnHover;
notice how () is absent because we dont want to call it?
yeah but Cannot assign to 'OnPointerEnter' because it is a 'method group'
then wtf are you trying to do
if OnPointerEnter is a method then this isnt possible
did you think it was an event?
you've basically come to ask us this
"what's the correct way of doing this"
2 = a + b
we have no idea about any context here
i just want to play a sound effect when i hover over something using a script.
then lets step back. what type is selectable?
If this is UGUI or UITK both have easy ways to respond to cursor events such as pointer enter
UGUI, and selectable is Selectable.
Implement this interface in a MonoBehaviour to respond to pointer enter https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IPointerEnterHandler.html
you can also use the EventTrigger component to do this but it may eat the event for the whole object so I do not recommend it.
will that work if the script is not specificly on the selectable?
no it has to be on it to respond to events on THAT object.
Try EventTrigger (you can set up a listener in code), may fuck up other things on that object who listen to this same event!!!
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-EventTrigger.html
Dont say I didnt warn you
This is the weapons manager script , he takes care of the weapons in the game
Hello, i'm trying to make enemy and got stuck with a problem. When i'm calling method from context menu my object jump too eager at first moment, almost like teleporting and only later it look like normal jump toward target. How can i make it more smooth
private void Ram()
{
Debug.LogWarning("Reminder: targeted player is hardcoded");
var direction = Mathf.Sign(player.transform.position.x - _rb.position.x);
ramPower.x *= direction;
Debug.Log(ramPower);
_rb.AddForce(ramPower, ForceMode2D.Force);
}
Also for some reason it require a lot more power compared to player to make a move (Vector2 (300, 200) vs Vector2 (15, 7)). I know that player movement is in Update() but i still feel like it's not a normal behavior
nvm, i've used wrong forceMode
I dont see anything in here that helps. Make sure whatever your "weapon holder" is is actually positioned well. You need to account for the camera near clip plane which is where the camera begins to render. You can see this in the camera gizmo in scene view.
I don't know if someone could help me with a behavior tree, I'm making a boss, the player has to place 4 fragments in their 4 corresponding altars and I want that when placing a fragment, 25% of the boss's life is removed. How could I make the behavior tree?
Each fragment will also be linked to an elemental power of the boss. If I place the fire fragment on its corresponding altar, I want the boss to not only lose 25% of his life but also not be able to use the fire ability. I don't know if it's too complex. Maybe I should make it simpler
can I change transform.position to a fixed value somehow? I need the z coordinate to be 0
it's not gonna change on its own
you can assign whatever values you want to it and it'll stay like that unless something else modifies it
I have an object that I rotate by 90 degrees, but then it seems to clip through the background so I have to reset the z to 0 I think
go give https://xyproblem.info a read
you shouldve started with the actual issue
make sure your pivot is set appropriately
are you working in 2d or 3d
have you tried just using separate sorting layers for the background and the foreground then lol
how are you determining it to be clipping?
is it half cut off or something
I dont know how to describe it, let me try and record a video
You can set it to whatever you want
I have a player rigidbody in the shape of a sphere that I want to rotate in the air when the player jumps or falls
I experimented with setting the angular velocity directly (since normally the player keeps its old angular velocity when jumping or falling, which tends to be 0 or too small), but I found that when the player hit the ground with the added angular velocity, it bounced in the direction of its rotation instead of just up and down
Does anyone know of a way I could rotate the player in midair without causing it to bounce in the direction of its rotation when it hits the ground?
that yellow diamond is the placeholder shape I'm using for now. See how it sometimes appears, sometimes doesn't and sometimes disappears? I think that means it's clipping
looks like it stopped doing that for some reason
"Destroying assets is not permitted to avoid data loss" uh
what are you destroying
are you trying to destroy a prefab ?
Because "Destroying an asset" means "Deleting a file"
Thought I was destroying instantiated object
You probably don't want to destroy an asset file
show
For some reason my input suddenly stopped working in my game. I tried reverting to an older working commit but the input doesn't work there either. I tried opening another game and the input works there. Then I tried creating a new scene in my broken input game with just a plain UI button and the button doesn't work. I created a new scene repeating the exact same steps in my other game and the button works there. What could be the problem........?
what do you mean by Input? like UI inputfield or keyboard presses?
my game is just controlled by the mouse, in my new scene test I just tried to detect a mouse over and that wasn't detected
which input system is your project using
I haven't did anything with the new input.. so I think the old one
did you check console window for errors when pressing inputs or anything ?
0 errors, 0 warnings
how are you detecting the mouse anyway ?
My game does have a "Input System UI Input Module" attached to the event system which I think is the new UI but in my game settings I have it set to use both input systems so I don't think if something broke there it would matter. I also have that module in my other working game and compared the settings for it and they are the same.
I use the event system UI thing..
In a new scene I just create canvas (which creates an event system game object) -> create button -> enable raycast on the image -> change the highlight color to yellow to make very clear its working or not. That works in my old game but not my new one.
I also tested if( Input.GetKeyDown(KeyCode.Mouse0) ) which is detecting clicks so my mouse is working...... but I don't use that for anything
so just talking about UI / canvas interactions not working ?
UI isn't working but I also use the event system on my sprite with Physics 2d raycaster to detect clicks that also isn't working
wait... I just switched to device simulator and my clicks are working there.. they just aren't working under "game"
is there a good way to move a 2d object forward a set amount independent of time?
How do I set the rotation Y of a transform?
`this is very wrong
You are dealing with quaternions
The y part of a quaternion has nothing to do with the y axis of rotation
I'm trying to set the Y rotation of the player to the Y rotation of the camera when moving
use transform.Rotate(new Vector3(0f, rotationValue, 0f));
you probably want this:
// Get a "flattened" forward vector for the camera's look direction
Vector3 flatForward = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up);
transform.rotation = Quaternion.LookRotation(flatForward, Vector3.up);```