#💻┃code-beginner
1 messages · Page 575 of 1
If i have a collider referenced in a script as so:
[SerializeField] private SphereCollider _grabTrigger;
How can i check for OnTriggerEnter on _grabTrigger, rather than the collider of the object the script is attached to?
put a script on the object that has the Sphere collider on it with OnTriggerEnter
you can have that script call this one
or fire an event
or whatever
Alright, thanks
i've done a simple trigger zone script, that used to work perfectly playing the right music at the right places. But then I've removed the music and left an empty placeholder to avoid errors, so I put the music back and reconfigured everything as it was before, and its not working
using UnityEngine.Events;
using System.Collections;
public class ZoneTrigger : MonoBehaviour
{
[SerializeField] private GameObject musica;
bool TaTocando = false;
void OnTriggerEnter2D(Collider2D collider){
if(TaTocando == false){
TaTocando = true;
musica.GetComponent<AudioSource>().Play();
}
}
void OnTriggerExit2D(Collider2D collider){
TaTocando = false;
musica.GetComponent<AudioSource>().Stop();
}
}
- Put a Debug Log in
OnTriggerEnter2Dbefore the if. See if the collision is registering. - Change
musicato be of typeAudioSourceand get rid of the GetComponents
actually my problem is that all musics are playing at the same time when I play the game, but I'll do these both
oh I realized my autistic brain forgot to deactivate Play on Awake, sry for wasting ur time
but tysm for those tips btw, mainly the second
So i recently started to make an project, its an indie game and i am also signed in IT school where i am learning C language and just a question. With which language should i make games?
if you're using unity then you'll use c#
Yes
depends what engine you're using
well, you'll be using c# then. like boxfriend said
Alright
The game is like about car building life simulator things like that, mainly about a car, like it has mechanisms of each part, condition of each part
I am worried about suspension i dunno how to do that
start by learning the basics of the engine before diving in and creating something
why cant i apply .drag to a rigid body? unity said i had to use lineardamping instead but nothing works. Its supposed to apply to my character and slow them down. Are .drag and .lineardamping the same?
yes, it's literally just a rename
are you using unity 6? (i think they just changed the naming of a few variables in the rigidbody, in unity 6)
Hi, I'm making a 2d turn based game.
I need to have enemy information (lv, hp, atk, def, sprite, animation controller alive, etc.) somehow stored. I need to show the user the base information (base atk, def, animation, etc.) in the menu, and also show in battle (e.g. atk may be different than base atk based on buffs). What's the best way to store this data? Prefabs, scriptable objects, json?
I can provide more info if needed
imo learning everything from a car's mechanics would be more difficult than programming the game itself lol
I am into car mechanics and i know how it works. Like i am not making the mechanics hyper realistic
i think you should take a look at classes and dominate 100% of it to make data at this level
maybe structs? seems like the simplest answer to me. although, im not 100% sure
For example the mechanics from My summer car indie game if you ever heard of it
Your idea is really interesting. Could have a lot of minigames such as racing, contests, or just weird stuff at the streets like gta. The car mechanics stuff would even be somehow educative
Pretty much, my theme about the game is have one main car and you gotta rebuild it from strach literally from suspension to engine assembly whole
But not too much realistic
there's smth similar to that in mobile but with pc instead of car
I think the name is PC Simulator 2
And when you fix the car and start driving the conditions of parts will wear down which requires maintenance of car
you could try it to get inspiration
Yeah i played it before
First of all
I need to get the car into game
The model how i am gonna get it i don't know.
yeah prepare to struggle a lot with modeling the pieces from the car lol
what im doing rn is saving money to hire a 2d artist as I suck at it
I will just get the car and engine and if i get it working i will model it piece by piece
I can send you an example of what i mean
In dms if you want
dont worry i got it
Idk if links are allowed here
my game is a 2d RPG with story and stuff
I will send an example of what i want
Street Rod meets Surgeon Simulator meets Puzzle meets Suomipelit
A game I am working on, a true car simulator. You will build your car from ground starting from bare chassis/frame. You need to properly attach all the car parts in correct order, tune the engine so it runs, and do other maintenance work before you c...
This is what i meant
the story is about 2 orphan brothers that were adopted by a man with weird behaviour and want to know what happened with their parents
( a game from an driffent dev)
This was 11 years ago
That was made in unity
My summer car
Great game from indie dev
So yeah i need to do similiar to that
But driffent car
Now I don't know how i am gonna import the sounds of idle rpm, and sounds of rpm as u give gas
you can buy in the internet or download some free stuff, or hire someone to do the sounds, or do it by yourself
I already found sounds for temporary car
And 3d model of it
Now I dont know how i am actually gonna get the engine running
idk, just study more about unity 3d physics or smth
Seems i will spend a lot of time im this server
Is there a method so i can create multiple clones\copy of my game object
GameObject.Instantiate
Or is it Transform.Instantiate?
One of the 2.
thanks
It's actually UnityEngine.Object.Instantiate but both GameObject and Transform inherit from Object so anything works
ok
If you have a monobehaviour then you can just call Instantiate because MB is also an Object
instantiate + for/foreach loop (or a while loop if you're feeling funky)
why its not working? error (5,43) and (5,65) does not implement interface member
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
public class pressclick1 : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public GameObject HoverPanel;
public void onPointerEnter(PointerEventData eventData)
{
HoverPanel.SetActive(true);
}
public void onPointerExit(PointerEventData eventData)
{
HoverPanel.SetActive(false);
}
}
unity 6 i using
Capitalization mistakes
You don't really even have to manually type in the method names. When you add an interface like , IPointerEnterHandler, you can use your IDE to auto create the needed methods
i've never used IPointerHandler before. is there any reason to use that instead of just using OnMouseEnter(and the other mouse functions)
OnMouseEnter works only with colliders IIRC
It's how you write event code for UGUI.
OnMouse functions also don't work with the new input system so they're generally to be avoided
oh right, completely forgot about that
damn, i've never really worked with UI before (i will have to soon though, for a recent project
)
atleast i know where to start now lol
public void PlayGame() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
ok thx
im getting this error now @west radish Assets\MainMenu.cs(8,9): error CS0103: The name 'SceneManager' does not exist in the current context
Use your IDE to import the namespace
how
doesnt do that for me
can you just show me what to do if i press a button it takes me into the game
Screenshot your IDE
so what happens when you click the lightbulb?
Also that colour scheme is atrocious—maybe it's actually unconfigured still?
use expression body for method
its a theme i have
It's weird to see the references listed but have no error underlining
can you just show me how to do this: press a button and takes me into the game
You need to fix your IDE before continuing
pretty sure vs code does that by default
!vscode
should've gone through this yesterday when you were instructed to: #💻┃unity-talk message
It's the references that are throwing me off. Gah now it's even more difficult to know whether something's unconfigured
my unity is already linked to vs code
if that were the case then you'd be able to use the quick actions to add the correct using directive
also just cause its opening it up, doesn't mean its "linked to unity"
i followed the directions
i set it up as my external editor
if you don't have this
its not configured
That's not the only step
then what else am i missing
follow all of the instructions
yes
Did you also open the link and did you also read the whole page
Or did you just look at it
It has about ~5 steps
followed instructions on the entire page
okay do this, close VSCode, go to Unity Preferences -> External Tools, click Regen Project files button. Double click script from unity once more, wait a few mins till it loads
check Output tab for any errors
theres no regen project files button
then you didn't do ALL the steps
Show the package you installed in unity
nvm
yea thats what it shows
ok so do the rest as instructed
still gives me this:
Assets\MainMenu.cs(8,9): error CS0103: The name 'SceneManager' does not exist in the current context
fix that error first, IDE doesnt configure well with compile errors
and do you see the error in vs code?
nope
congrats! you've not configured vs code!
comment it out for now, fix IDE first
ok but i dont even know what to fix
i set it up as external tool
mate, I been telling you
close VSCode and do the regen thing,
Its either gonna work or show you .NET SDK error
"comment it out" means add a // at the start of the line to disable it
i know that
also yeah make sure no compile error
what is it supposed to do when i press regen
nothing visually you will see. Make sure VSCode was closed now open script again
should be loading bar at bottom
ok i opened it
should i uncomment it out
it gave me the error when i uncommented it
which error
i got a .NET error tho in my vs code
ok there you go
the .net core sdk cannot be located
I told you was either going to work or give .net sdk error
so download it now
restart PC after install , and do the regen thing again
maybe 9 works too but idk yet
i just install it and run the .exe without doing anything else right?
yeah just install it, then restart pc (this is important)
use default folders if possible
ok
wait but i need to comment out and close VScode and then i do regen and then open VScode and uncomment
if you mean comment out the current line that gives error yes, you should not be trying to configure IDE with a compile errors.
Restart, open unity Preferences, Regen, open script again, wait till bottom bar hopefully says "Assembly CSharp"
i started seeing the error in vscode now
Nice, try the light bulb now
its telling me to add Debugger Display
thats weird you tried doing Quick Fix ?
quick fix tells me to add Unity scene management
it removes the error when i do scene management
yea
wait but even when i press one of my buttons it doesn't take me to the main virtual environment
like the main scene
i think my script is maybe incorrect
well now we can look at script issue lol.
idk the setup tho , I just got here when i smelled unconfigured VSC
i created a Button TMP and im trying to attach the script in the field on the On Click
and is the script on a gameobject ?
See anything in the console after you click the button?
nvm im attaching the Gameobject which has the script
make sure you drag that one, not the one from the Project view
ok but my cursor is getting locked again for some reason
i did it
even tho i put cursor lock on None
are you certain that line of code is running?
did you put visible to true?
check if that function runs at all first
check that with log, n make sure you don't have something else overriding it again
some character controllers put it in the Update method with a check
i cant check if the function works because I can't press the button
because my mouse just disappears when i click the button
im pretty sure the problem is the visible not on true
well it has to be both VISIBLE and unlocked/confined
i found the Cursor.lockState one
i found a bunch of Cursor.visible
Cursor.visible = !lockState;
you sould ideally only handle this stuff in 1 class only
that can work sure
maybe you can do Cursor.visible = Cursor.CursorLockMode!= CursorLockMode.hidden also
but looks like you got variable for it anyway
i found a Cursor.visible = true;
and Cursor.visible = false;
private void ToggleSettings()
{
if (_panelCanvasGroup.alpha == 0)
{
ToggleSettingsPanel(true);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else
{
ToggleSettingsPanel(false);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
ok well try not to spread that function all over the place
handle it in 1 class so you avoid confusion / unexpected values
so there will be a void Cursor?
no like a singleton class or something that just has Cursor locking and unlocking function
some type of GameSettings script or something
is it not this:
private static void LockCursor(bool lockState)
{
Cursor.lockState = lockState ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockState;
}
sure
what do i do then
this?
this i meant
delete all the functions in scripts that have cursor settings besides this function
the one you got is fine
now you just call this function when you have to
i dont think i can do that
theres a bunch of Cursor
you dont want that though..
keep it in 1 script so you don't confuse the values
just the ones that do =
but then wont i have to reassign everything again
whats there to reassign? cursor is a static
so like for example this:
void Start()
{
Cursor.lockState = CursorLockMode.None;
}
i just delete this as a whole?
yes ofcourse why would you need this to automatically just change the lockstate and not even touch visibility ?
now you have that function you can call LockCursor
guys am i allowed to send videos here?
Here is the game i made
if you want to showcase work it goes in #1180170818983051344
oh ok
how about this:
if (Cursor.lockState != CursorLockMode.Locked) return;
no you don't touch that because its a BOOL check not assignment, some logic needs it then you dont remove that
but i wanted to ask what should i try and learn next
and if this is good
i am using unity for maybe 2 weeks now
add more features or do another project thats easy enough
for former, probably best ask #archived-game-design
what about this whole thing
private void ToggleSettings()
{
if (_panelCanvasGroup.alpha == 0)
{
ToggleSettingsPanel(true);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else
{
ToggleSettingsPanel(false);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
/// <summary>
/// Toggle the settings panel on or off
/// </summary>
public void ToggleSettingsPanel(bool value)
{
if (value)
{
// Fade in the settings panel
ActivatePanel();
FadeInSettingsPanel();
// Check if the alpha of the appearance canvas is at its maximum
const float MAX_ALPHA = 1;
if (_uiAppearanceSettings.GetCurrentActiveAppearance().GetCanvasGroup().alpha >= MAX_ALPHA)
// If true, fade out the current appearance canvas
_uiAppearanceSettings.FadeOutCurrentAppearance();
// Set the cursor lock state to none
Cursor.lockState = CursorLockMode.None;
}
else
{
// Fade out the settings panel
_fadeCanvas.OnCurrentFadeCompleted += DeactivatePanel;
FadeOutSettingsPanel();
// Check if there is an active Convai NPC
if (ConvaiNPCManager.Instance.GetActiveConvaiNPC() != null)
// If true, fade in the current appearance canvas
_uiAppearanceSettings.FadeInCurrentAppearance();
// Set the cursor lock state to locked
Cursor.lockState = CursorLockMode.Locked;
// Save values when the settings panel is closed
UISaveLoadSystem.Instance.SaveValues();
}
}
please use links for large code
ok thanks for advice <#
❤️
like I said anything that has assignment must GO
so just delete the entire void thing
you see how its spread out too many places setting it
so this entire thing goes to trash:
private void ToggleSettings()
{
if (_panelCanvasGroup.alpha == 0)
{
ToggleSettingsPanel(true);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else
{
ToggleSettingsPanel(false);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
What is a good way to go about dealing damage to a specific clone of an Instantiated prefab? Is there an easy way to make a game object identify itself?
how about this:
public void ToggleSettingsPanel(bool value)
{
if (value)
{
// Fade in the settings panel
ActivatePanel();
FadeInSettingsPanel();
// Check if the alpha of the appearance canvas is at its maximum
const float MAX_ALPHA = 1;
if (_uiAppearanceSettings.GetCurrentActiveAppearance().GetCanvasGroup().alpha >= MAX_ALPHA)
// If true, fade out the current appearance canvas
_uiAppearanceSettings.FadeOutCurrentAppearance();
// Set the cursor lock state to none
Cursor.lockState = CursorLockMode.None;
}
else
{
// Fade out the settings panel
_fadeCanvas.OnCurrentFadeCompleted += DeactivatePanel;
FadeOutSettingsPanel();
// Check if there is an active Convai NPC
if (ConvaiNPCManager.Instance.GetActiveConvaiNPC() != null)
// If true, fade in the current appearance canvas
_uiAppearanceSettings.FadeInCurrentAppearance();
// Set the cursor lock state to locked
Cursor.lockState = CursorLockMode.Locked;
like I said besides the first static function you shown, anywhere that has = must be removed, notify LOCK or UNLOCK either use Events to invoke or Call the static function there directly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
ok i deleted everything needed
now what do i do
theres just this left
{
Cursor.lockState = lockState ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockState;
}```
What about it
so whenever you need it locked/unlocked call this function
i need to unlock the cursor
so i can click the buttons
so call the function
So call that function to toggle lock state
going to have to kinda use common sense here lol
you literally made this function for lock/unlock. What else did you think you needed to do
i dont have it
unlock it
its locked rn
how do i unlock
take a guess
Well, you made a function that flips the lock state
have you called a function before no ?
CursorLockMode.Unlocked?
no
no you're not touching the ENUM directly anymore..
Why did you show us this code if you're not gonna use it
your code is literally full of functions everywhere.
i probably have called a function but just dont know whats the term for it
ok lol now you know
to call static function you must precede the function with the Class name it belongs to
since statics belong to classes and not instances (object created from class)
do i need to do this?
what do i change in this code
{
Cursor.lockState = lockState ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockState;
you don't touch that anymore
you just CALL(USE) the function now when you need to lock and unlock
the name is misleading, its more like toggle
ok so I want to unlock the cursor now what would i do
What isn't working about it
why would you need to change it
call the function and call it with the appropriate bool
It's not really a toggle
You provide it the lockstate you want to have
Perhaps you guys misread this part Cursor.visible = !lockState
more of a setter than traditional flip/toggle yes
Assets\Convai\Scripts\Runtime\UI\SettingsPanel\UISettingsPanel.cs(51,59): error CS0103: The name 'ToggleSettings' does not exist in the current context
Ah, fair
What is ToggleSettings
ok ok 2 state cursor setter
literally no context here. What is on line 51
show code
What is ToggleSettings
ok so its working now?
i pressed the button but it just brings me back to the position im standing in
how do i make it so that the main menu disappears
ill watch a video
make it do that lol wdym how . You're the one with the code, we did not write it
you should create an event
what kind of video?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
make a static event you can Invoke from the LockCursor function
any script that needs to know, can listen to this function
basically theres this. When i press the button, i want the menu to disappear so i can go inside the environment
eg activating UI panels n shit
yes you need to Tell it to do that. Either Set Active to false called directly (method) or event once again
event is the cleanest
how do i find where i need to do that
thats up to you to create.. thats what development is, youre creating the system..
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no i mean like i need to create it inside the script?
if you had an event, then you can easily "react" from other scripts, EG a script that deals with Panels
it needs to be on A script, its up to you how you organize it.. Ideally you should learn how to sepearte them into different managers..
UIManager, etc.
you have to try to make 1 script do specific things..
UIManager only deals with Panels, UI menus etc.
this way you know where to find something eeasily
so i have to create a new script
this works but then you need to create many scripts when you can have 1 deal with just UI
can u just make me the script
for this only
like pressing the button closes the menu
You've said this like twelve times already
Do you actually intend on learning anything or letting us make your project for you one script at a time
me writing you the script wont teach you anything just as you not learned anything so far hence why you're stuck
you're skipping rock on water through different systems with no exp and expect everything to just work, not realistic
hello can someone explain to me why i cant see the newsoft in the package manager or the asset store how do i download it
you need to type the package name directly
com.unity.nuget.newtonsoft-json
add by name
don't ask me why Unity didnt add those startup / quick setup instructions in docs
ok thank you that worked what a round about way of doing things. is their any think else i need worry about
dependences and or quirks ?
na
i dont need to delete json utility's
nah
ok thank you very much
they belong in different namespaces / assemblies they dont even see each other
ok thanks
what does this error mean:
Scene with build index: 6 couldn't be loaded because it has not been added to the build settings.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene (int)
MainMenu:PlayGame () (at Assets/MainMenu.cs:9)
UnityEngine.EventSystems.EventSystem:Update ()
did you bother reading it?
yes
and what was not clear?
i need to do something with build settings
i think its telling me to add a scene
so that it can go there when i press a button?
yes, you're trying to load the scene at index 6 but there isn't one there
what do i do in build settings
if you plan on going to a scene , it needs to be in the Build
add the scene
ok i added it
build?
or build and run
it just needs to be added to switch scenes in Editor
you dont have to build now, only if you want to test it without unity
it still gives me the error even tho i added the MMSE scene
cause you don't have a scene at index 6
how do i put mmse at 6
why do you want to put at 6 lol just use 5 in the script.
i dont even know where unity got 6 from
you literally wrote it in the SceneManager Load function..
is it cuz i did buildIndex + 1
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
should i just delete the + 1
are you trying to reload the same scene or the next scene?
same scene
bro im literally pressing the button and its not taking me to the scene
i watched a video and for him it just took him into the scene when he pressed Play
It means the scene with build index 6 couldn't be loaded, because it has not been added to the build settings.
To add a scene to the build settings use the menu File-> Build Settings
did you check console for messages ? did put log just incase ?
it took me to the same scene but it didn't get rid of the panel
took me to the scene i wanted
why doesn't it get rid of the panel
the scene already starts with panel on or you have statics not resetting
What code have you written that hides the panel
none
Then why would you expect the panel to be hidden
i just have this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public void PlayGame() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
- !code. You've been told this already.
- this reloads the current scene. Is the scene reloading?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
yea when i press a button it takes me back to the same place as i was when i pressed Play
that doesn't answer the question of Why would you expect panel to hide if there is no code set to do so.
idk
Okay, so the code is working exactly as expected
im dumb
it's reloading the scene
yes
Then what's the problem
just need to figure out the code to hide the panel
would it be gameObject.SetActive(false)
break down the problem into smaller ones
gameObject may or may not be correct, we don't know where you plan on using this
but thats the function to hide gameobjects
hows this look
A tool for sharing your source code with the world!
MainMenu is the game object btw with the panel and buttons
its bad
what to fix
MainMenu is a script
not a gameobject
A Component
then use the function to disable gameobjects
What even is this
Why do you have a function whose entire purpose is to throw an exception
how
lol they just used the quick actions to add that instead of spelling the method name correctly
imma pick up on this tomorrow i gotta sleep
I am aware, but I'm trying to ask leading questions to convince them to learn why they are doing what they are doing
As I have tried for several days now
Someday it'll work
i mean, they refuse to just go learn the basics. i doubt they'll learn anything from this
"just this one time"
can u say inappropriate stuff in this server
or nah
just rly wanna say something
ive been wanting to say it for rly long
check the #📖┃code-of-conduct if you're confused. Try your luck
Go for it. Either it's allowed and you're fine, or it's not allowed and then you won't be on this server to have us do your homework for you. Win-win
yea i doubt its allowed
its js something rly funny
its a joke
that u may or may not find funny
i can dm u with ur permission
anyone want me to dm them
i know @rich adder wants it
I doubt anybody does
whats the difference between a Ray and a Raycast? is there a use case I should be using for each? Im trying to move the player based on screen input and not sure if there's a difference between the 2
Ray is a math concept, just an infinite line with direction, RayCast is a physics cast using that line for example as direction
the Ray struct just holds data, particularly a starting point and direction. a Raycast is a physics query that takes data like origin, direction, distance, etc to query the current state of the physics engine to find out if there is a collider in the path desired
hey i have this script wich technically works fine, but for an strange reason Unity says somethings odd, i mean, it works, but it advises me that a part of the script is empty, what this means?
using UnityEngine;
public class rifle_bullet_script : MonoBehaviour
{
public int riflebulletdamage = 5;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void OnTriggerEnter2D(Collider2D collision)
{
EnemyBase enemy = collision.GetComponent<EnemyBase>();
if (enemy);
{
enemy.TakeDamage(riflebulletdamage);
Destroy(gameObject);
}
}
}
if (enemy);
it advises me that a part of the script is empty
wdym by this
semi colons denote seperation of code, but you're going into a statement here
i already posted the advise
oh, ok
thx, it always bugged my brain that...advise? i mean cuz, the script still works, its just like a...recommendation?
no the script will not work properly if the object doesn't have that component
it's only working because the component is there
you're getting lucky
o h
it will be an error if GetComponent returns null
basically your if statement is not doing anything at all
Hmm. Does (enemy) not imply EnemyBase is a bool?
I wasn’t aware that you could do it like that
It can be implicitly converted to a bool
All UnityEngine.Object - derived types can
It works the same as if (enemy != null)
Yeah that’s how I usually do it
is there a way to change like the actual unity icons you can set within the scene in script? like these things
Tmyk
anything you can do in editor usually has an Editor function for it yes
so through this? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Editor.html ill look into it, thanks
This seems to cover drawing custom icons in OnDrawGizmos
oh no i meant like if i have it already set to the green diamond icon, later during runtime being able to set it to a different icon
that one I think you need reflection for
oh nicce
To find that, I just went to the editor source reference (https://github.com/Unity-Technologies/UnityCsReference/tree/ac359b9f2cf4048acb91530f81ca5d78966aeec7/Editor)
And searched for "Select Icon" 🤷♂️
oh that is perfect! thank you.
nice. for some reason google brought me to this weird forum post
.GetMethod("SetIconForObject",
couldnt find it just from searching online, didnt know that existed
Maybe it was internal back then so you had to use reflection
That's 11 years old
glad they added it then 😅
Looking for a quick chat with someone who uses blender
I don’t want all my problems solved I just want a push in the right direction so I can continue to make this stupid idea I have
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
This is going to be harder than I thought
Wait for the coding part can you tell a 3d model what color to be?
Like make this entire object this color through code?
You can set the color on the material, if the material supports such a thing, sure
This is my first time using 3d so I’m trying to break it down into the most logical way for what I’m trying to accomplish
I think I know what to do, I guess I’ll keep trying till I get the result I’m looking for
What are you trying to do
I’m trying to rotate an object with 3 sides
A triangle?
That would be 3 different animations or can I use code to go through the frames of animation
You're honestly all over the place with your questions
A tetrahedron
I suggest focusing on one thing at a time
What does Blender and colors have to do with rotating an object?
In what way do you want to rotate the thing?
And why does its shape matter to the way you want to rotate it?
left and right aren't meaningful descriptions of a rotation
something like "clockwise around the world y axis" would be a meaningful way to describe a rotation, for example
3 colors I wanna rotate between
Now I can't tell if you're talking about physical rotation, or changing colors
Do color all 3 faces in blender then animate 3 diffrent animations or can I use 1 animation and cycle through frames with code?
Can I dm you a photo of the thing
I don’t want my idea taken
I got the code to work for the basic part I just need the artwork to match up
I guess it doesn’t matter what I do, you can make something work multiple ways I just wanted to know the best way about doing it
The hardest part about being a beginner is being lost in the sauce
You haven't actually explained clearly what you want to do yet
This is the number one thing I feel beginners struggle with - just stating in a clear sentence what they are trying to accomplish
Imagine a tetrahedron split into 2 I wanna rotate the top that has 3 colors with a button and rotate the bottom that also has 3 colors with a different bottom, one color at a time can be used
I don't understand the color part at all, other than the fact that the different faces of the object have different colors
Sounds like you would just have two different objects
and rotate them independently
you can rotate an object by setting the rotation on its Transform, or its localRotation, or by calling Rotate on it
the exact code depends on the exact nature of how you want to rotate the thing, and when
So no need to animate in blender I can do all that with code?
You can do anything in code
3d rotation is animation
I don't understand what you mean by that
I just assumed wrong
Yes it sounds like you have some weird assumptions about things
It’s okay you did great and answered my question I appreciate your time sorry for the riddles
Hi, question from someone new to C# (and honestly OOP) in general. I'm trying to make a simple program where players can draw lines between nodes on the screen. The images should clarify what I mean to some extent. My issue is that I don't know how where I should write what the player is doing. I can kind of imagine dividing it into three classes, but then where do I program the actual state machine? A separate class?
If you are not familiar with basic structure of coding, you might wanna look into some tutorials/books first. You already mentioned specific keywords you can look up, as this would be the start of a very long conversation teaching you basics you can read about yourself 🙂
I googled it
Couldn't find anything
Obviously I could dive deep into the rabbit hole, but that's not very motivating if my only goal is to find where I should put the state machine right?
Sounds like you are fighting with more than just "where to put the statemachine". thats no offense but you seem to be overwhelmed already by "what the player is doing". So I suggest going to some unity tutorials from !learn and figure out, how things are done more commonly and go from there
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'm asking a very simple question.
Okay, state machine in a separate class? For the whole game flow, yes, separate class. Simple answer
Thanks. That's all I need. Could have saved me the AI helpdesk automated response.
Is it possible to have only one static class script in one scene?
Singleton you mean?
thanks I'll look into it
An easy way is singletons as twentacle mentioned: https://unity.huh.how/references/singletons
It seems that singletons can be accessed anywhere, including across scenes. But I need static class for a single scene
As in a single static instance for each scene?
Same thing, but generally you should make a provider that handles providing instances. Ask the provider for an instance, and it checks if it made an instance for that scene before
Should also make sure to invalidate instances when the scene gets unloaded
This applies in general. You should always have a single provider providing instances
Thanks!
Whats the difference between Time.fixedDeltaTime and Time.DeltaTime?
is there a list of the basics that I can check and learn? I cant find a list at anywhere and I'd want to have defined what I need to learn (dont need a specific order tho)
You can run through !learn and there are other beginner tutorials pinned to this channel as well
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
seems really interesting, ty
One is fixed the other is not 🤷♂️
Does any of you know if lists .AddRange() can have for more than two conditions?
I want to merge these two
units.AddRange(unitPool.GetComponentsInChildren<MovementBehaviourTroop>().Where(units => !(units.movementStates.currentState == MovementState.Dead)));
units.AddRange(unitPool.GetComponentsInChildren<MovementBehaviourTroop>().Where(unit => !units.Contains(unit)));
First one checks that nobody with the state MovementState.Dead is added to the list, the second one makes sure the same object doesn't get added twice.
I can't seem to get the syntax right to merge them
why not just use foreach?
Becasue I run this
public void UpdateList()
{
units.RemoveAll(unit => (unit.movementStates.currentState == MovementState.Dead));
units.AddRange(unitPool.GetComponentsInChildren<MovementBehaviourTroop>().Where(unit => !units.Contains(unit)));
}```
To update a list, and removing an object from a list that is being iterated in a foreach loop will throw errors
what happens if I use a constructor in a monobehaviour?
public class TestPlayer : MonoBehaviour {
public string name;
public static TestPlayer Instance { get; private set; }
public TestPlayer() {
Instance = this;
}
}
Log your onenable method and see 😉
doesn't that exclude the duplicates on both collections (includes only one)? That might or might not be desirable but worth knowing
The constructor is likely to get called during both runtime and outside due to the fact that the class instantiation (and thus constructor call) doesn't only happen at runtime (in most cases).
I can't think of a single reason why you'd ever use the constructor with a monobehaviour.
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };
IEnumerable<int> union = ints1.Union(ints2);
foreach (int num in union)
{
Console.Write("{0} ", num);
}
/*
This code produces the following output:
5 3 9 7 8 6 4 1 0
*/
``` this example from the docs says, it includes duplicates but keeps only one
Wasnt that the question here? Exclude if it already contains?
Yeah, that's what I thought. Likely uses some sort of hashtable to achieve that so might not be optimal way to combine collections if the duplicates are non issue to begin with. If the duplicates must be excluded, then it makes sense
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat?view=net-9.0
Note that this combines the two lists. If you want to avoid duplicates, you will have to use an aggregate or make the items distinct between each other in some way
So Union merges and removed duplicates 😄 confused
The real answer would be to just apply a proper filter before you add the units
I never heard of Union. If it does that then that's a better approach, yes
I could honestly just try a for loop
Since it can work with a dynamic size as opposed to foreach
I would make an IEnumerable method that returns the units you want to add to the list, and put all of it in there
I don't understand this code though. You add units not matching the state and then you just add the rest anyway? What's the point?
If the point is to order based on that state then just use OrderBy
Linq will be your friend one day 😄
Union is one of the set operations (and sets don't allow duplicates to begin with right?)
I want to remove objects with certain conditions, and update the list (check if other elements check the criteria) but without duplicating the ones not in the list, since AddRange will create duplicates
Both AddRange and Where is LINQ afaik
AddRange is a List method. Where is a LINQ method
Also found an answer. I can literally just use &&
😄 Okay, you do you
I think you are trying to fix the wrong issue, though
Perhaps you should look into equality in your classes, and make sure adding duplicate classes is not possible in general
If your List is not allowed to have duplicates, use a Hashmap. Also override equality checks on classes so you can accurately compare against other classes to ensure it's not the same
public void conditionalSort(List<object> objects)
{
foreach (Object obj in objects)
{
if(obj.name == "CoolName")
{
objects.Remove(obj);
}
}
}
haven't read chat so i may be missing something. but, wouldn't something like this work?
you would just have to change the if to whatever you need
Yeah. I'm also removing objects, which is not a good in a foreach loop
oh right, good point.
You can also compare things with union, just saying 😉
public void conditionalSort(List<object> objects)
{
List<object> objectsTemp = new();
foreach (Object obj in objects)
{
if(obj.name == "CoolName")
{
objectsTemp.Add(obj);
}
}
objects = objectsTemp;
}
could use a temporary list to fix that
then use union to remove any duplicates
please tell me you don't think this is a good idea
that is precisely how you're intended to use LINQ, so it seems at least tolerable
Your first anonymous function's argument is named units, not unit
This is preventing you from accessing units inside of the anonymous function
I mean the approach is generally fine, but they should just add proper distinction between the objects instead of implementing some obscure filtering system
It does feel more than a little weird to reference units whilst in the middle of units.AddRange, though
Not to mention Hashtables would be much faster over a list
At least, from the context these collections are always unique
If not then you can't do this
a HashSet would make uniqueness checking faster, yes, at the cost of not having an order
I might change a lot on the run
which is probably fine here
This is just a practice project to better myself and trying stuff out
Mainly familiarizing myself with List<T>
unit is the item, units is the List
that line of code is making me upset
Okay
😛
https://hastebin.com/share/ququwexoyu.java
Hi. I managed to do this. Rotate my camera on X and player Y because thats how my playerController handles mouse movement. My issue is that, when slerping, the camera does not looks at the target precisely. It is as if with offset. Just like in the picture. Doesnt it have to look directly at the center of the cube?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's so long
unitPool.GetComponentsInChildren<MovementBehaviourTroop>() is also alarming me a bit
I think I've asked questions 2 or 3 times in here and it's generally disencouraging
Sorry, I shouldn't be jabbing at people immediately
The rest of the logic seems fine now -- you're filtering out all units that are already in the list, removing all units that are dead, and then adding all of the results to the list
for readability, I would never do it. I was just funnily showing, that there are so many ways you could achieve the same outcome and it depends on the questioning persons needs.
I like that there are many ways to approach it. I appreciate the help. I know I make a lot of spaghetti, but as for my question, I was genuinely just curious if it was possible to add multiple conditions in .Where(), as a part of troubleshooting updating a list where objects don't get added multiple times to the same list
I could jump on to a different solution. I want to understand the roadblock first. Why it does what it does
and yes, you can write an arbitrarily complex predicate
You just can't throw two or more predicates into the Where function
As in what I just did?
reminds me of mysql queries, which I hated either, when they got longer and longer 😄 But for debugging and filtering, why not as long as you clean up code afterwards
A "predicate" is a function that takes an item and returns a bool.
You can make that function very complicated
bool NumberPredicate(int x) {
if (x == 3)
return false;
if (x == 6)
return true;
return x % 2 == 1;
}
var sequence = numbers.Where(NumberPredicate);
I'm unclear what you were trying to do that resulted in a syntax error
Did I say it threw an error?
I can't seem to get the syntax right to merge them
I presumed you had tried to do something and gotten a compiler error.
I didn't understand the syntax of the language well enough to make one line of code do what those two lines of code both meant to do
ah, okay, that makes sense
The line I have now, as terrible as it may look, works as intended
Note that you can write a local function like I did here, instead of using an anonymous function
This can be a good idea for longer conditions.
NumberPredicate does not exist outside of the function that it's declared inside of
I will eventually try out different ways to do different things
But sitting down to work with and manipulate Lists specifically kinda defeats the purpose of me using ways that don't use lists
So I understand the need to respond to my question by asking me why I don't use a different approach
Hash sets could actually be inappropriate here, too.
I would expect newly-selected units to appear at the end of a list, rather than appearing at random places amongst the existing units
(which is what you'd probably observe with a hash set)
I had planned to incorporate hashsets into this practice project by assigning objects uniquie IDs, but I know I will get disencouraged by having too many balls in the air at the same time. I'm still a beginner
You don't have to do anything special to make that possible.
I was about to say that any reference type can be used in a hashset, since they all have a default hashcode implementation, but it looks like you can just stick any struct type you want in, too
But yes, no need to juggle too many plates
You should focus on writing code that is easy to understand, even if it's a little more verbose than it could be
(and a little less efficient)
Especially when you're a beginner, gamedev can feel like bailing water out of a sinking ship: the project inevitably gets more and more complicated until you're unable to make any forward progress
so, best to keep the complexity low!
Could this be because my playerCamera object is sitting on my player as child with an offset?
targetRotation is a world-space rotation, whilst initialRotation is a local-space rotation
If you want to convert it to a local-space rotation for the player camera, you can do...
Quaternion.Inverse(playerCamera.parent.rotation) * targetRotation
Also, I'm not a huge fan of this...
//playerCamera angles
targetEuler.y = initialRotation.eulerAngles.y;
targetEuler.z = initialRotation.eulerAngles.z;
Fussing with components of euler angles tends to cause surprises
Euler angles can abruptly flip by 90 or 180 degrees
I would suggest just flattening the direction you're trying to look in
Vector3 direction = // ...
direction = Vector3.ProjectOnPlane(direction, Vector3.up);
in this case you could've also just done direction.y = 0;
If the player's body can get tilted to the side, then you'd want to use Vector3.ProjectOnPlane(direction, playerController.transform.up)
which would work for any orientation
I am trying to create a log in system using playfab and get this error and dont know how to fix it
how you you handle two-player controller input using the old input system? I'm making a two player fighting game, and i want it so that one controller controls one character (obviously lol) but I can't figure out how to get Unity to tell the difference between the two controllers or which mapping is correct for the second player
I am following a tutiroal and they dont seem to have that error despite me following everything
Seems like you are missing the OnError method somewhere or calling it on something that does not have it. But as long as you dont show the script, noone can help you. We dont know the tutorial and certainly wont watch it to help you there, so give some effort in your description including !code to help us help you
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
When I tried to set them to 0 by hand it indeed flips the rotation I do not inted to. But I thought making sure they are restored would not cause an issue. It works fine as well. Just that I'm slightly missing the lookTarget's center now
Is there a way to disable mouse collision on a gameobject? I have some text over a button and it's making me unable to click the button
You can uncheck "Raycast Target" on the text component. It's in the "Extra Settings" section
Tysm will try that
I try to do that for anything that isn't supposed to be interactive
#💻┃code-beginner message this is your main problem right now
you are calculating a world-space rotation
All right. I will look into it. Thanks.
Unchecked and it's still blocking clicks
okay, add a Canvas Group and uncheck "Blocks Raycasts"
I couldn't remember if turning off Raycast Target was sufficient or not
i got this method in my LobbyManager
Add it in the text? If so then I added it and still not letting clicks through
On the same object as the text, yes
In that case, there must be something else getting in the way
and in my other script i need to listen to it or subscribe
to still have the LobbyEnter_t
and be able to use it
how do i do that?
If you are using the old input manager (so, you aren't explicitly using the new input system), you can look at the EventSystem's inspector to see what the mouse is currently hovering over
you'll see that info in the preview pane at the bottom
which might be collapsed
HandleLobbyJoinSuccess is a method.
you're trying to treat it like it's a UnityEvent or something
oh yeah shit
Perhaps you meant to subscribe to LobbyManagerEvents.LobbyJoinSuccess ?
But that takes no arguments
Don't think theres anything
Oh wait seems like the text is not blocking clicks but its the actual text box
Its a tmp text
You'll need to show us what you're doing (ideally in #📲┃ui-ux , since this is not a code problem)
I converted it as you said still looking at it with slight offset like this.
I don't really know what I'm looking at here
Ah sorry. The block on the ground is my lookTarget. And you can see my crosshair. When the slerp is done shouldnt I be looking at the center?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is how the code looks now
so you're rotating both the player's body (around the Y axis) and the player's camera (around its X axis)?
Yes
Thats how my mouseLook works.
I wanted it to look natural thats why I did it that way
This can be a bit tricky. You have to decompose a rotation into two different pieces.
Vector3 flattened = Vector3.ProjectOnPlane(entity.transform.forward, Vector3.up);
yaw = Vector3.SignedAngle(Vector3.forward, flattened, Vector3.up);
Vector3 rotated = Quaternion.AngleAxis(-yaw, Vector3.up) * entity.transform.forward;
pitch = Vector3.SignedAngle(Vector3.forward, rotated, Vector3.right);
Here's how I did that in my game.
also playerCamera is sitting at my player object with x 0.25 and y 0.75
I first find the yaw.
so its with an offset
Then I use that to adjust the forward vector so that I can figure out how much up-and-down angle it has
I fixed it, turns out im stupid I forgot my main script holder is an empty game object with a text box and it had collisions on
Quaternion turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
Quaternion lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);
here's how I compute the rotations later on
If you want a local rotation for the camera, lookRot would not have turnRot multiplied into it
I really do not like manipulating individual euler angles, and this approach avoids that entirely
the X offset is odd -- that means the camera is off to the right
unless everything is rotated weirdly and local +X is actually the direction you are facing
Wait why is it .25 on the x. Damn
Okay after resetting it to 0 it looks fine now
It was sitting wrong at my player
I'll still take a look at how you've done it in your game. Gotta study signed angle and project on plane first though. Now my main issue is to clamp the axis so i dont turn 180 degrees upwards.
Thanks a lot for the help!
The Vector3 methods are very useful. I almost never have to do any triginometry.
Yes I already have my upper and lower look limit decided on my playerControls. But clamping it seems tricky to me while slerping!
When I try to use the same values it does weird stuff 😄 but again I havent taken a look into it completely yet!
Yeah I love methods! Gotta understand them first though. Also math is not my strong suit. Dealing with 3 numbers (vectors) is kind of complicating things for me haha.
hello, so i want to add lights to my 2d urp project but whenever I add a point light or spotlight, it doesnt affect the scene. the only thing that affects the scene is my global light. Am I doing something wrong?
You need to use 2D lights
point lights and spotlights are 3D lights
Also this is a #archived-lighting question not code
Hello, does anyone know how I can reset the camera view in "Scene" ? :c
click the white cube by the gizmos
those anyone know why i cant move the email and password to the input fields in the inspector?
Input Field is the legacy UI component
most likely mismatch of types
you'd want TMP_InputField
wym
eg TMP vs legacy Text/Input
round peg, square hole
so what would i change it to
do i change these?
correct
those produce errors tho
fixed it thanks #
Hey all, I'm running into an issue where only sometimes the jump modifier second case is triggered (the one where it cuts the jump short if the key is released)
https://paste.mod.gg/qoantzeyuykz/0
A tool for sharing your source code with the world!
Apparently I'm supposed to be using the new input manager methods but it's a little confusing. I am still using the new input manager for most of the stuff but
After upgrading to Unity 6 and Visual Studio 2022 recently, VS has started adding namespaces to scripts automatically. But the namespaces aren't even necessary (they are greyed out seeing how they are unsued). Causes a bunch of errors when I remove some unneeded packages from my proj.
Is this a feature or a bug?
Hi, I am using the this script to generate fonts at runtime.
It works fine, except for the fact I can't figure out how to include special symbols etc.
When I am using the Font Asset Creator, I can simply select Extended ASCII(or something else), and it will work fine.
However, the function for creating fonts doesn't appear to be having any parameters(such as CharacterSet), so I don't know what to do.
Thanks in advance!
Tmp can dynamically add at runtime anyway
It's likely adding the namespace when you choose a type from the IntelliSense suggestions. If you realize it's actually not the type you want and erase it, the using directive will still be there, now unused.
This can happen even if you only write your using directives manually. I would suggest you find the shortcut to remove unused directives and memorize it.
huh?
OK thanks, that must be it. Don't remember it happening with VS 2019, so there must be a setting somewhere
Undoing instead of erasing accidental suggestions should also get rid of the using
you're checking GetKeyUp in FixedUpdate which runs at fixed intervals (fixed frame rate). this is bad as it will miss inputs that happen in-between calls (the fixed time FixedUpdate is called). the documentation also suggests to call this method in Update . . .
oh
I'm confused about what the issue is. Do you want to load a font at runtime?
Or are you still configuring it in editor?
they're generating fonts at runtime but it doesn't include special characters. they want to figure how to do that . . .
when generating the font from the editor, there is an option for this. i believe they want to have that ability during runtime . . .
I want to load a system font, it works fine but it's missing symbols, here's the same command shown w terminal and unity font
oh, I see -- the script uses TMP_FontAsset.CreateFontAsset to generate the asset
the rest is just there to help you find a font by name
Can you verify this font file actually has it?
I can tell you that making a font asset within unity with that same font works fine
And often fonts can have many versions for different weights and stuff
I am generating the font from Courier Prime Code during runtime too
there's a TryAddCharacters in the TMP_FontAsset class, maybe that's useful?
It should work either way
that's interesting, will take a look
in the meantime, I also found this
https://docs.unity3d.com/ScriptReference/Font.CreateDynamicFontFromOSFont.html
it could make my current implementation cross platform+simplify the workflow
But is that tmp?
I am generating the tmp asset from a font asset
I swear tmp fonts could source from the os already if you set it too
Yea but the function above is for the old text
I mean idk, it could work, just gotta figure this part out
You can't mix the old text/font with text mesh pro stuff, 99% sure.
hmm, I looked into this and it has a string param, I am not sure how I'd add all the extended ascii characters etc. that way
I’d guess you just shove in a bunch of characters
but do you really need to specify the characters? can't you use the dynamic generation as rob suggested?
I also found this option AtlasPopulationMode, and it has something called DynamicOS, could that be what rob was referring to in the msg I replied to?
I can, I just need characters to work, don't care what way as long as it doesn't tank the performance too much
I've used dynamic fonts and that function just add some ahead of time. It still adds characters not present later.
If they never show then let's presume the font doesn't have em
ok, let me try to generate the font asset with that and see if it works
In edit mode the texture in the font will update so you can see what it has added
Something about my game's resolution is off. In windowed mode the game looks good, but in full screen the edges are jagged
Another thing is that to take a pic of the jagged graphics I had to take a pic with my phone, because if I take a screenshot it looks like in the windowed version
Maybe it has something to do with the monitor resolution settings?
not a code question, and this just looks like aliasing
Maybe something about how unity handle the resolution? Because I don't get why the aliasing wouldn't work on full screen
no, i mean the effect you are seeing is called aliasing. you need to use some sort of anti aliasing if you don't have it enabled to prevent that
I don't get why the anti-aliasing wouldn't work on full screen*
have you even confirmed if AA is enabled?
Yes
If I take a screenshot of the game in full screen, the screenshot is not jagged even tho the gameplay is
Ok, so I've been trying to get the AtlasPopulationMode to work but I couldn't.
It would just tell me that it couldn't resolve the atlasPopulationMode:, so I tried to look at the api for the latest tmp version(since I'm using unity 6), and that led me to this function being outdated and saying that I should use this instead, but that gave me the exact same error and it's not even compatible with the TMP_FontAsset from what I can tell so I am lost to say the least.
Any clues as to what I'm supposed to do?
Also, should I make a thread to stop spamming the main chat?
Tmp dynamic font
https://paste.mod.gg/bennowykbduz/0
Not sure why but whever i move i get some crazy values for my y veloicity
A tool for sharing your source code with the world!
those are incredibly small values, it's just in scientific notation. those values are so small they are effectively 0
interesting
do you mind taking a look at this
if (Mathf.Abs(rb.linearVelocityY) < jumpPeakThreshold && Mathf.Abs(rb.linearVelocityY) > Mathf.Epsilon)
{
Debug.Log("float a bit...");
Debug.Log(rb.linearVelocityY);
setGravityScale(gravityScale * gravityHangTimeMult);
}
why
i wanted it to kinda have a little float near the apex of the jump
but it seems to always run even if im just on the ground
check your conditions and also consider checking if you are also grounded
grounded is a good idea
if it happens while you're grounded, then check and make sure you're not . . .
also, no reason to calculate the absolute value of the same variable twice. cache and reuse it . . .
another note: your methods are both camelCase and PascalCase, which is confusing when reading the code. i'd stay consistent with one style. prefer PascalCase, especially, since all your methods except for 2 are not
you commented these are used for getters and setters. this is what properties are used for
// Old code
void setGravityScale(float value)
{
rb.gravityScale = value;
}
float getGravityScale()
{
return rb.gravityScale;
}
// New code
public float GravityScale
{
get => rb.gravityScale;
set => rb.gravityScale = value;
}
you can do the same to create the IsJumping property . . .
do you even need GravityScale there
you could just use rb.gravityScale
the original wasn't exposing it to outside classes or anything
i just thought it'd be nicer to reference it using getter and setter
for readability honestly
are you from java
i kinda code all
It is reasonable if your user doesn't have a reference to the rigidbody
i did my first 2 years in java tho lol
if that's the case, then use the property but make it private instead
Properties were created to free us from the tyranny of writing accessor methods
(but yes, use a property)
i guess that's true
getters/setters in that way is kind of java-specific
lol u got me
(maybe c++ too? i didn't really get that far)
alright i'll just access it using the property
the concept still holds, it's just written/used differently
i was only showing that using a property is better and easier to do, especially for readability and to save time. they can easily make it private, if needed . . .
i really hate the PascalCase
but if you don't actually need to expose rb.gravityScale, i'd recommend just using that directly
especially for methods it ticks me off so hard
I came from a Java background too and had the same feeling, but eventually got used to it. Now the Java way looks weird to me.
sure will refactor
well get used to it because it's the standard in c#. public properties, methods, and types are all PascalCase (public fields too, but ideally you'd use a property rather than a public field)
😔
it's just unity decided not to follow the standard for properties in their engine code for whatever reason
thats why im using it, but... I'll always look down on it lol
anyways thanks all for help
you'll get used to it
it helps with uniformity with built-in methods
if you're familiar with something else, not being comfortable with the new pattern is pretty normal
but you aren't working alone alone here, you have to work with the standard library, unity's library, and any other 3rd party libs you might use
once you do get used to it, the uniformity will help in the long run
also be prepared to get stuck with it if you go use something else after using unity
haha. since i learned coding with C# it makes more sense to me. i like differentiating methods, properties, and events from variables . . .
this does not bode well as my job uses spring boot haha
especially, when looking through dot notation, you can see what should only be exposed for you to access . . .
well different languages have different structures
for example, in languages where functions are first-class citizens (eg c, js, py), it might make less sense to distinguish variables and functions
all i can say is, good luck lmao
I have made a DDOL singleton for my settingsmenu, so that it can be used in more than one scene. The issue arises when I change back to the scene where the object originally is from. How do I solve the issues with this?
The issue
what issue exactly?
a took a look at C++ and people use a few different styles (standards) for their coding. i guess it's different between the old and the new style . . . 🤷♀️
Consider having the menu check if an instance already exists and destroying itself if that happens
Alternatively, use [RuntimeInitializeOnLoadMethod] to instantiate a menu prefab as the game starts
your DDOL should have a check that removes itself if an instance of it(self) already exists . . .
(you can pull the menu prefab out of a Resources folder)
So. I don't exactly know what is causing the issue. But when go back to the original scene were the DDOL singelton pattern is on I can't press the options menu to open the settings. The settingscanvas is a gameobject being a DDOL singleton. The settingscanvas is supposed to have be activated/deactivated on button press.
Oh, I know what you're doing
so the canvas lives in scene A
something else in that scene has a reference to the canavs
This is fine until you exit scene A and then return later
The object in the scene still references the canvas that lives in scene A
not the canvas that has been moved to the DontDestroyOnLoad scene
If that's the case -- don't store any direct references to the canvas. I presume you made it a globally-accessible singleton, so just reference it that way!
oh
I will try.
Thank you, this worked. However I noticed now that when I play the game after going back to the menu again since starting the game. the game is freezed
🤔
perhaps you are forgetting to reset your timescale
e.g. if you set it to 0 when pausing
because you hadn't run into the problem before 😛
you'll want to start thinking about state that can survive from one play session to the next
anything static is a prime suspect
hi guys i have a question, when i am making a movement script should i use character contoller?
Is this a viable method to solve it? if so should I do timescale = 1 before or after loading the scene
i mean everything is working fine without it but i see that people is using it often
hm, yeah, there are two ways of doing it
one: whoever set it to 0 should set it back to 1 before they give up control
two: whoever needs it to be 1 should set it to 1 when they take control
oh, wait maybe I should set it in Main menu when I press plau
The second one is a better idea, IMO
It's proactive: I need this to be correct, so I will make it correct
rather than trying to catch every place you could forget to reset the timescale
You could also consider having a singleton game controller that constantly decides the timescale
the order of these two operations does not matter (assuming you are referring to within the same method) as the scene isn't actually loaded immediately upon calling LoadScene, it's queued to load in the next frame
ah ok
good to know
ah, and that would be DDOL too or just a singeton pattern?
