#💻┃code-beginner
1 messages · Page 324 of 1
i'll have to give it a try then, cant hurt, problem is baseballs are meant to bounce of players that only have trigger collisions
u can achieve that with some layers.. (collision matrix)
and some physics materials.. (material for the ground/diff for the player)
- custom stuff applied to that to get it to feel right
i'll try it, problem is the players are basically using the exact same system...
so i'll have to rewrite that too
thank goodness i only have to change 2 scripts
praise the lord for inheritance
if players bounce off the floor they use the same system 😭
i guess i could make it so rigidbody is enabled and disabled when the player is stunned or something
how can i make gravity stronger?
the weight appears to be a lot lighter after i changed it to rigidbody movement
ive got a problem in this script where the WaitAtPt() IEnumerator is being called when he comes from another state into Patrol - ive tried resetting the path and stuff but i dont know why its being called
isPatrolling gets set to true if canPatrol is true
Perhaps the path isn't ready yet
SetDestination can return before it actually figures out a path.
Increase the mass of the rigidbody
but acceleration due to gravity is constant :p
does mass make u fall faster?
that'll just make everything else weaker
i was gonna say
i just manually increased gravity
in the project settings
works like a charm
if gravity feels too weak, your objects might be too large
this usually indicates that you are affecting how gravity works with your code or that everything is at a much larger scale than it should be
everything is at a 1 scale, im just increasing the gravity scale to make things feel more arcadey
things arent that big in my game
then show your code because it may be messing with how gravity is affecting that object
its fine, until now i was using a custom physics system that i made which multiplied gravity by 4 so naturally things feel a lot lighter after switching off that system
it finds a path as soon as the agent goes into the patrol state, but that coroutine is being immediately ran. the point isnt the agents position btw its a set one across the map
I mean instantly -- it doesn't matter if it finds a path one frame later or a hundred
I know that it can take longer for a very distant destination
especially if it can only get close to the destination
so im tryna find the distance between a gameobject and an array of different gameobjects then store it in an array. is there a way to not go through and put a separate line for each value that needs to be stored?
Maybe describe what you're attempting to do better.
yeah im not really sure
Why do you need to acquire/store this list of distances? For what purpose?
https://gdl.space/qenaguqiso.cpp
hello i really dont understand the problem with my code basicly if i touch a trigger i should start a timer and the text get enabled for a few sec and then just go to setactiv(false) what can be the problem ?
im trying to find the closest one of that list
"PlayerDistanceFromTrees[1] = Vector3.Distance (player.transform.position, trees[1].transform.position);" works but i wanna do it for all of them not just 1
alright thanks
ima go study for a bit and then come back to it
will probably make it clearer
Just iterate the collection and keep a reference of the closest object.
https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html
if you care about micro optimizations if you don't need approximations
how can i disable a rigidbody?
i know i cant directly disable one
but how can i effectively disable a rigidbody influence?
either remove the rb component or make it kinematic
Set it to kinematic and possibly disable to collider
why does it feel like the character is getting dragged around? i made rigidbody kinematic and stuff
and i disabled the collider so it shouldnt be dragging along the floor or something
as u can see when rigidbody is removed it goes back to normal
after some testing, it appears to be because i enabled interpolation
Co-variant array conversion from Galaxy[] to IGalaxy[] can cause run-time exception on write operation
Why is this warning shown?
Galaxy[] array = // ...
_gameMap = new(array); // constructor takes IGalaxy[]
umm cone someone help me why when my temer goes 0 it doesent effect if condition https://gdl.space/emilerayir.cpp
the time will never basically be 0
so how to make 0
I've noticed covariance isn't that type safe and would run into a lot of issues with casting at runtime, so it's probably just warning you that it's leaving it up to your discretion that casting will work here.
Hm I understand
loool took me an hour figure outif agent.hasPath == true works
nevermind it doesnt 💯
I Instantiated a ui Panel and i want to Destory it at some point, but when i do that it tells me cant destroy so no data gets Lost
https://hastebin.com/share/fiquboreti.csharp
how come it doesnt go back to 1st animatin and goes back to idle fast
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what are you destroying?
probably the prefab?
Destroy(instancePanel.gameObject);
instancePanel = null;
instancePanel = Instantiate(PanelPrefab, panelInstantiatePosition.position, Quaternion.identity, panelHeader);
what is instancePanel
screenshot the error
what exactly is instancePanel then? is it a prefab?
this doesnt help, show me what you assign to instancePanel what Transform
nothing
its empty
its supposed to hold the prefab so i can destroy from both functions LoadNamePanel and LoadWord...
nothing
what error is the line on? does it say
line 54, buttom one
54
Where do you assign instancePanel
instancePanel = instantiate
That runs after the error (meaning it doesn't run)
What does it start as
If it starts as null then you'd be getting a NullReferenceException, not a message about destroying an asset
well iam not
Put this log as the first line of LoadNamePanel:
Debug.Log($"LoadNamePanel instancePanel is {instancePanel}",instancePanel);
And then show what it logs before the error occurs
tomorrow, imma sleepnow
https://hastebin.com/share/fiquboreti.csharp
how come it doesnt go back to 1st animatin and goes back to idle fast\
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can't see on a quick look, but you should really be using if else where relevant to remove the potential to enter the if immediately after one you just executed
(and to avoid running that excess logic)
it kind of works now but after it loops and plays the 1st animation it goes back to idle for a second and then you can attack again but i want it to be a continuous loop and not go back to idle
cant u name the return types? so i dont have to variable.item1
instead variable.name
ok thanks
anyone know how to add footstep sound fx to any game easily im very new to unity so I have no idea
look into animation events. you can use them on your animation to call a method when the feet hit the ground . . .
my game is in first person and it is not multiplayer so I don't have animations just yet
huh? i didn't say anything about multiplayer . . .
im just saying that I dont have any animations so that wouldn't work
just play an audio source every 0.1s or something when you would have the footstep when you are walking
i could try that
then you'll have to play the audio based on the speed your character moves . . .
play around with the timing because it depends on the player speed and how fast or slow the footsteps are . . .
thanks
Are dictionaries like hash maps?
yeah . . .
gotcha, ty
im having issues with gameobject.find i have a player prefab which is instantiated and a roundsystemmanager object with script which is also instantiated in the scene i am attempting to get some values from the script but the gameobject.find is returning null?
show what your trying
Just don't use GameObject.Find
It is never a good choice.
Sometimes the type and tag varieties are ok, but still not great
not much to tell from that. also, when are both GameObjects instantiated? it's probably searching for it before it's instantiated . . .
does anyone know how to make unlockable thing using timers record
for example: it has question mark and you need to survive 20 minutes to get the thing
you survived 20 minutes and you get the thing
https://hastebin.com/share/vizewijavu.csharp (best time script)
https://hastebin.com/share/upileyinub.csharp (Timer Unlockable script)
the third image is an example of how it needs to be when you survived 20 minutes
just get the float from PlayerPrefs and check if its >= 20
like this? sorry if im asking a lot of script about timers i never made scripts with timer
yes, but 20 would probably not work, depends what BestTime is if its seconds/minutes or something else
but you can figure that out im sure
il try my best
Hello, so im a beginner, first follow a youtube tutorial, did some animations, but i have a weird error. i have 100% the same code, but unity gives me this warning, and my animations not work. I already read posts about it, some ppl say its a bug, but closing Animator, and reopen Unity and rebuild not fixed my problem. So whats wrong?
100% correct.
show the name of your paramater
not in the script probably
Yeah, make sure the animator window has the correct name.
wym?
yea, cuz i already tried with lowercase uppercase, let me fix it, but still same error
show the name of the paramater in your animator
are they both linked to the same animator?
I have a player with the script, then i have a children for the player graphics, with the animator. My whole script is this:
using UnityEngine;
using UnityEngine.AI;
public class CharacterAnimator : MonoBehaviour
{
const float locomotionAnimationSmoothTime = .1f;
NavMeshAgent agent;
Animator animator;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponentInChildren<Animator>();
}
// Update is called once per frame
void Update()
{
float speedPercent = agent.velocity.magnitude / agent.speed;
animator.SetFloat("speedPercent", speedPercent, locomotionAnimationSmoothTime, Time.deltaTime);
}
}
Debug.Log the animator and make sure they are all what you expect it to be
Maybe a possible fix deep in the video comments: Just a note for people who run into this problem. Do NOT create the PlayerAnimator script in the script folder. Make sure it is made inside of the Assets project hub. Other wise it'll throw an error that the parameter SpeedPercent does not exist.
Show us the parameter in the animator
ok move the script and see?
Aah, didn't notice it in the screenshot somehow
okay tried, not work. even recreated controller in the main asset folder
Can you double click the parameter name in the animator and make sure there are no spaces or line break characters in the end?
btw i misread the comment, i should move the script, not the animator, but tried still same error.
@teal viper no whitespace, tried ctrl+a but only the text in here
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You could try getting the list of parameters of an animator controller with an editor API and check their names:
https://docs.unity3d.com/ScriptReference/Animations.AnimatorController-parameters.html
Okay guys, as im said i am a beginner, dont be mad at me haha, this float wasnt a float, it was a layer, i didnt switched to the parameters tab.
sorry buddy but i was thinking so hard to figure this out but i don't have any idea
Ty for your help, your tips will be good in the future for debugging haha
what are you adding? the part just from PlayerPrefs... is fine?
whats the BestTime.bestTimeMinutes part for?
what are you trying to do
i added this if it would work because there's bestTimeMinutes
ok so then just do if(BestTime.bestTimeMinutes >= 20)?
it got an error
i guess this is how the part script needs to be of what i was talking about
whats the error
what
i meant this
"it got an error" - whats the error
bestTimeMinutes is not like conected or something
whats the error, screenshot it
that doesnt help me at all, screenshot the unity console where it shows what the error is
alright, so bestTimeMinutes is made as a local variable in some method which means it doesnt exist outside of where you made it
https://hastebin.com/share/odufabuvol.csharp why when the first animation plays after the loop it is delayed and sometimes goes to idle'
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
probably something to do with your animation tree setup
so i can't make gameobject enable using timer's record?
so, you need to make bestTimeMinutes not local, by making it public and creating the variable outside a method, then just doing = on the float you already have
public class A : MonoBehaviour
{
public float myFloat; //Public accessible in other scripts and stuff
private void Start()
{
float something = 5f; //Only accessible in Start and nowhere else
}
}
"something" is minutes?
its just an example
of how local and not local variables work
uh okay i guess
should probably go through a basic c# crashcourse before doing any of this
wdym what? he means what he said
i know some codes but i never tried coding with timer systems
"some codes" isn't the basics
what you mean by, "what?" they stated a clear sentence . . .
i mean just accessing another variable in a class or differences between local and member variables, etc.
your doing a simple float variable, this has nothing to do with timer systems
your struggling with a float
it's hard to help or go further because you lack the basic knowledge of C#. you can't understand the help or information they're trying to convey . . .
This is super basic. Not knowing that you can't use a local variable in another scope implies you need to go back and learn the basics
are yall trying to fight with me or what?
trying to help?
i told you waht to do and you are doing the complete opposite
its not possible to help
i just asked anyone of you to know of how to make a gameobject enable using timer record
and you have that done
you have the code written
the problem is not in this script
its in another script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is menu record
so idk if this is the problem or not
look at my exmaple
your bestTimeMinutes is local to Start
to let you know i didn't made this
but do you understand what its doing?
he did this
so what?
im telling you what to change
you dont want to do it
for some reason
i never said that
but your actions say that
If you can't understand the most extreme basics of c#, you will not be able to do this.
That statement is extremely helpful to you.
Here is more help, take this course
https://www.w3schools.com/cs/index.php
i changed it to update
that will just now make it local to Update
the problem is still the same
then what do i need to change if "start or update" is the "problem"
read the comments
Make it not local
so i need to change it to private or something
you need to access it in the other script
so it would need to be public
oh my god this is getting confusing
even it would be easier if sending the script or i don't know
You need a class member, as opposed to the local variable
https://www.w3schools.com/cs/cs_class_members.php
This describes them
im not going in there that's a waste of time
whats confusing?
and add here
float minutes;
void Start()
{
float minutes = ...
change that to
minutes = ...
}
It literally explains exactly what you need to do
It is a few words and example code
going back n forth with you teaching basics, you could learn on your own is a waste of everyones time
i didn't say anything to you
lol I can't even react emoji since I'm blocked
This is so extremely simple. I don't understand what part is stumping you, except a refusal to try
"Not going in there that's a waste of time" 
i didn't blocked
so, what have you tried code wise? is the problem fixed? is the error gone?
1 what do you mean
2 i don't know haven't tested yet
3 i don't know haven't tested yet
i told you exactly what to do here
Hi everyone. I want to learn how to code in C# for Unity. Do yall know any good resources?
check the pins in this channel
Okay thank you. Do you have any tips about coding?
use the pins or this ridiculous post . . .
#💻┃code-beginner message
make sure you have a configured IDE
learning the basics first
What does IDE mean
I would say don't worry about being perfect
Be willing to make mistakes
the code editor, !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Okay thank you
oh and google anything you don't kow 🙂
Nice!
Alright I will 👍
Thank you guys for the help
an old post i made a long time ago . . .
And still doing its job haha
could make it a Github markdown with links?
i think that's around when i started . . .
:))
true, i never thought about that. i should use Github more often . . .
il just leave
it dosen't mean leaving the server
are you giving up?
after i told you what to do
no
How long did it take you to learn?
is not because i give up
I love finding stuff like that via github, also they have lists like "collection of URP shaders" etc
a person knows how to do this type of script
you know how to do it too
because i told you how
It's literally removing one word from a line, and adding another line
That is it
Don't think it is too much. You can do it
i think is going to be the same as yours or i don't know
you should very least try to put in some effort on the help given
they literally give you code and you still refuse to try
ok
i learned quick, but that's because i really wanted to and like learning new shit, and it was easy to follow. everyone learns differently; it really depends on their drive and willingness to learn
what helped me most was typing out all the code myself and understanding each line and concept before moving to the next. i completed the links from rbwhitaker's website, then went onto the unity beginner and intermediate tutorials. after that, i was ready to follow along from youtube tutorials . . .
dang, didn't know. i've seen a few gists. i guess they're one-off code blocks or snippets?
@summer stump
Just a regular public repo usually
eg
https://github.com/sampaiodias/unity-resources
ChestNewWithAnim3 is the character?
Nope
like, i wait until IsGrounded is true, then i copy it and set to the base Y
However
Only 1 frame later it updates it
if (characterController.isGrounded) { isGrounded = true; animator.SetBool("IsGrounded", true); } else { isGrounded = false; animator.SetBool("IsGrounded", false); }
This is on void Update()
should it be on lateupdate
or something
btw this can just be
animator.SetBool("IsGrounded", characterController.isGrounded)
flaky?
yeah not very reliable, it only calculates as you move iirc
use spherecast or overlap etc
I just said it lol
meh i think im
what's an overlap
i think i'll just make it ignore first few frames...
:)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections.Generic;
using UnityEngine;
public class PlanetGravity : MonoBehaviour
{
public List<Rigidbody> objectsToAttract = new List<Rigidbody>();
public GameObject planetCenter;
public float gravityForce = 10f; // Adjust this value to control the strength of the gravity
private void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger entered");
if (other.gameObject.GetComponent<Rigidbody>() != null)
{
objectsToAttract.Add(other.gameObject.GetComponent<Rigidbody>());
}
}
private void OnTriggerExit(Collider other)
{
Debug.Log("Trigger exited");
objectsToAttract.Remove(other.gameObject.GetComponent<Rigidbody>());
}
private void FixedUpdate()
{
// Apply gravity force to each object in the list
foreach (Rigidbody body in objectsToAttract)
{
// Calculate the direction from the center of the planet to the object
Vector3 direction = (planetCenter.transform.position - body.position).normalized;
Vector3 localUp = body.transform.up;
// Apply gravitational force
body.AddForce(direction * gravityForce);
// Rotate the object to align with the gravity direction
body.rotation = Quaternion.FromToRotation(localUp, direction) * body.rotation;
}
}
}``` Hey i'm trying to make a gravity bubble like Angry Birds Space that attracts objects toward the center, It wont work, it just gets pushed off, and I dont understand and know how to get the force to be pulled toward the center, thank you
add a c# after your three ticks
and it'll use the colour formatting
reverse the b-a
your on the right track
// create a grav zone
// calculate direction from object to center
// apply force
it looks like you just have the force going the opposite direction
Moving it to lateupdate fixed it
Alright, how do i make it in the right direction (pulled toward center?)
try what navarone said - it should be that simple
think of the direction as (destination - origin) . . .
Alright so A - b
if it's going the opposite direction, i'd start off by flipping the direction . . .
do any of you know much about initializing objects via script?
What specifically
Because yes, that is a huge part of coding
Vector3 direction = (body.position - planetCenter.transform.position).normalized;```
is this correct?
when i initialize it as a parentless object it exists
when i initialize it and transform its parent - the node exists with all the same values - it just doesnt exist in game
that's pretty common . . .
just test it and see . . .
it got pushed off
using the opposite direction should not create the same effect. one way should pull while the other way pushes . . .
When you say initialize, you mean Instantiate, right?
yea sorry
in this context, what is it?
a prefab with a .fgb model and a mesh collider
Not sure what you mean by "it just doesn't exist in the game"
Instantiating it with a parent would not cause it to not exist
like - its not anywhere even though the transform values should be the same
i posted here
cs```
cs
private void FixedUpdate()
{
// Apply gravity force to each object in the list
foreach (Rigidbody body in objectsToAttract)
{
// Calculate the direction from the center of the planet to the object
Vector3 direction = (body.position - planetCenter.transform.position).normalized;
Vector3 localUp = body.transform.up;
// Apply gravitational force
body.AddForce(direction * gravityForce);
// Rotate the object to align with the gravity direction
body.rotation = Quaternion.FromToRotation(localUp, direction) * body.rotation;
}
}``` here's the code i have. I think it's either the direction or the addforce, i dont really know
again.. put c# at the top
so its legible
your making it alot harder to quickly read after having it explained repeatedly lol
alright sorry
And is it in the hierarchy?
yea - i have a screenshot since im using an in-game heirarchy viewer
cs not c#
c# works too
must be a fairly recent change because it didn't for the longest time
its worked for atleast a few years
its in the heirarchry twice
as a parentless (clone) and then on the parent
Soooo... you gonna show it?
private void FixedUpdate()
{
// Apply gravity force to each object in the list
foreach (Rigidbody body in objectsToAttract)
{
// Calculate the direction from the center of the planet to the object
Vector3 direction = (body.position - planetCenter.transform.position).normalized;
Vector3 localUp = body.transform.up;
// Apply gravitational force
body.AddForce(direction * gravityForce);
// Rotate the object to align with the gravity direction
body.rotation = Quaternion.FromToRotation(localUp, direction) * body.rotation;
}
}``` Ah there we go
look at the inline code section . . .
#💻┃code-beginner message
i already did i linked to it.. but i can post it again if you like
WTF?
Ohhh, didn't scroll down to the ss, sorry
all good!
Can we see it in the editor instead? To see the inspector as well
If possible
i didnt want to spam the same post in multiple places
Makes sense
try logout and log back in hub ?
or return / renew license?
unfortuantely i cant i dont have access to the editor since im working on setting up and document mod tools for the dev
Wait i know
I would log the non-local position it is being set to.
If the values being put in are the same, it would be in different positions
maybe i should do directionX directionY and directionZ to attract it in 3d
oh do you just want the data? i can show you both objects data though
You are setting the LOCAL position, which is the offset from the parent. Without a parent it uses the world origin. With a parent the parent is the pivot
unityexplorer is basically just like the edditor
gimme a sec
i broke it trying to change stuff around
yea i can manually transform objects in game - i tried all sorts of different things but could never get it to exist
ok so this is the object that exists
this is the object that doesnt exist
for some reason its making 2 objects when it should only make one
i can manually assign the clone object to the parent object
and it will exist
weird, i hit update and restart. seems to have fixed it . . .
which is why im assuming its a scripting error
WOOWOWOWOwOwwjdwqindndjqqdegyhbdqdiqeddieqasw
and im doing something incorrectly
It works!!!!!!!!!!!!!!
also as for the parent object its set to 0 0 0
so it shouldnt be affecting anything
atleast to my understanding?
oh hub version now messes with editor runtime ? weird..
Yeaaaahhh.. that is right.
This is odd then
im assuming the issue has to do with
why are there 2 objects?
if (sceneName == "MainGame")
{
GameObject va01system = GameObject.Find("SingleplayerGame/GameMaster/VA01");
if (va01system != null)
{
// load thomas
if (!thomasLoaded)
{
if (thomasModel == null)
{
LoggerInstance.Msg("Loaded Bundle Successfully.");
thomasModel = AssetBundle.LoadFromFile("Mods/AssetBundles/thomas");
// load thomas once
GameObject thomasPrefab = thomasModel.LoadAsset<GameObject>("Thomas the Tank Engine");
Vector3 thomasPos = new Vector3(-30488.41f, 489.5023f, 38069.4f);
// set thomas's scale
thomasPrefab.transform.localScale = new Vector3(20, 20, 20);
// set thomas's local position
thomasPrefab.transform.localPosition = thomasPos;
// test parent
thomasPrefab.transform.parent = va01system.transform;
// initialize thomas
modelInstantiator.LoadModel(thomasPrefab);
LoggerInstance.Msg("Thomas Should be waiting for you outside planet Vauldric!");
// set loaded to true
thomasLoaded = true;
}
else
{
LoggerInstance.Msg("Failed To load Bundle.");
}
}
}
}
public class modelInstantiator : MonoBehaviour
{
public static void LoadModel(GameObject model)
{
Debug.Log("Object Instantialized!");
Instantiate(model);
}
this is a post of my code again
im only instanitalizing a single object
bruh, what is this screen we are looking at?
You should avoid Find btw
i cant
theres no easy way to access the objects
i dont really have full access to source
ofc there are
if i was making the game myself for sure but - im trying to set up mod-tools for the game
do you mean the ingame editor windows?
what ever those screens are. i can't tell what's going on, lol . . .
its a mod called unityexplorer - it basically just puts the editor in the game so you can use it and play
VAO1 is the parent object im linking to
Thomas (Clone) is the parentless object that works
and Thomas is the child object that isnt working
I don't see anything jumping out at me, but it may have something to do with the base game you are modding. I see only one instantiate call.
If it was the whole method running twice, it would be the same settings.
Because it says (clone), then something must be instantiating another one FROM the model you just instantiated.
That makes me feel like it is from different code
But that doesn't answer why the first one is not working
Clone means it was instantiated from an instance in the scene already
if i dont do parent transformation the clone is the only one that exists
i was assuming that was how asset bundles work
Well, I dunno. I don't use asset bundles, so that may be it.
because i can make it so theres only one thomas and it'll be a clone
yea they're kinda weird i dont exactly know how they work other than
you can bundle up everything except scripts and load them as a file
also nothing should be affecting my script since my script runs completely seperated
i have to link-in and patch methods if i want to do stuff like that
but im not utilizing that feature
how does instantialize work without asset bundles?
not sure if this is outdated
but presumably instantiating prefabs assigns the clone
also i can do this and manually assign the object as a parent
and it works fine
i just dont understand how to do that in script
Have you tried just doing the overload for instantiate instead of setting the parent in its own line?
I would do the position AND parent in instantiate
sorry how do you actually use optional paramaters like that?
None of those are optional
You must do all the the parameters for the selected overload
I'm following a tutorial and have a question about how this code works, the only confusion I have is how can "TestingEvents_OnSpacePressed;" be accessed by the Start() function if TestingEvents_OnSpacePressed is a private void. Is it because they both reside under a public class so functions can access one another ?
Private means it cannot be accessed OUTSIDE that class
The class being public is irrelevant
so this wouldnt work?
gotcha - i'll load all the params thanks
Well, there is an overload that just takes the prefab and parent
whats the difference sorry?
Instantiate(model, parentModel.transform)
that was exactly the issue
thank you so much
ive been stuck on this for over a week 😭
out of curiousity
what way would you suggest linking to a game object that has a persistently changing name
Hi! I’m so new to unity and I’ve been having an issue with fungus ;-;
finding something by name is pretty brittle
yea i just dont know if i can really access them myself
if it was up to me id have components - or tags or something to know exaclty what they are - but thats not really in my control
or i'd have to rewrite a large chunk of code just to add it
the ship object is a parentless object
and im not really sure how to access it
like i have this
but - i dont know how to call the field
because the field exists on the object that has a changing name
i cant just call as-is
huh ? doesnt it have a component?
components are Object
not sure I follow, this seems to be some type of mod so I'm not sure 🤷♂️
Should I try to have 1 class per 1 script? Or will there be times when I'll need to have multiple classes in 1 script?
Yes, try to do 1 to 1
right but to access the component you need the gameobject first yea?
Sometimes you may want to have classes INSIDE of other classes, or small non-monobehaviour classes alongside monobehaviours, but other than that, separate them
Definitely never do two or more monobehaviours in a single script. That will cause issues
not really. You can for example specifically look for the component or inject it dynamically
you can look for components that you dont know the gameobject of? :O
why would you look for specific name?
so both of these game objects have names that change depending on what system you are in or what ship you are flying
i wasnt aware that i could get these objects in other means without storing an object refrence somewhere which isnt nessesarily something i can do easily
Hey! For some reason I cannot build this, because EditorUtility doesn't exist in the current context.
I know it can only be used inside the editor, but how should I open the explorer then in a built version?
Using API specific to the platform os.
PC
This is all googleable btw
I use this
https://assetstore.unity.com/packages/tools/gui/runtime-file-browser-113006
works well and its free
Let me try, thanks
Works!
What should I use instead of WWW ?
It works,but who knows one day if it will
the new class is UnityWebRequest
You can use this variance as well
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html
see link i sent
I texted earlier than the link ahs been sent
it shows the other way around for me, but yea regardless the example shows what to do. there is indeed no .texture
@rocky canyon hey man, just wanted to tell you how I fixed my system yesterday
I decided to use rigidbody like you suggested and by changing the unity gravity values to my system's values (4x gravity) and stuff I was able to achieve a near identical feel to my old system. To this end, I also implemented a character controller / rigidbody hybrid with my players, so that when they enter a bouncy state they deactivate the CC and enable dynamic rigidbody. I made the floor have the same bounce values as my old system as well, and it has achieved a near identical effect 😊
I didn't actually have to change much in my scripts, and just replaced my old moveVector thing with rb.velocity with most of the values and it just worked out the box
'string' does not contain a definition for 'Interact' and no accessible extension method 'Interact' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
void Update(string currentInteractable)
{
CheckInteraction();
if (Input.GetKeyDown(KeyCode.F) && currentInteractable != null)
{
if(!OpenInventory.Instance.CheckIfFull())
{
OpenInventory.Instance.AddToInventory(currentInteractable);
currentInteractable.Interact();
}
else
{
Debug.Log("inv is fulll");
}
}
}
Im trying to make a inventory for interactable objects but i get this error.
you are doing string.Interact()
what are you expecting to happen?
string.Interact() doesnt exist
i want this to return a random object from this list, or rather hashSet, or playerObjects, and get their components too, but when i use it, even tho there is one in the scene, it says null reference, am i missing something here? cant figure it out
where you create the hashsets?
btw learn how to create a custom sturct/class for grouping the data
public static HashSet<PlayerMovement> playerMovementScripts;
foreach (PlayerMovement script in FindObjectsOfType<PlayerMovement>())
{
playerMovementScripts.Add(script);
}
or is something missing
public List<int> ints;
public List<string> strings;
turn to
public struct MyStruct{
int theInt;
string theString;
}
public List<MyStruct> myStruct;
```how to use struct
```cs
public static HashSet<PlayerMovement> playerMovementScripts;<---declaration
foreach (PlayerMovement script in FindObjectsOfType<PlayerMovement>()){<-- you use it
playerMovementScripts.Add(script);
}
public List<int> ints;<---variable declaration
ints=new List<int>();<--assignment/create the instance
how to move object with the same speed using rigidbody.addforce?
and not like accumulate force
Forcemode velocitychange
but its still accumulating speed?
so i just?
you need to calculate the opposite force by yourself then add the force back, force must change the velocity
yes, you need to create the instance
ok thanks
I'm using OnTriggerStay2D and when the player presses the E key, it should show a debug.log message. But it only seems to work every few seconds. Anyone know why?
https://docs.unity3d.com/Manual/ExecutionOrder.html
note that the rate of OnTriggerStay2D fired is not the same as update, so reading input may fail
Any way to change the rate of it being fired?
What would be the best way to detect when a player presses a key while inside a trigger collider?
you should be checking for input in update, or using the new input system then store the value. Check the value in the physics message
dont try changing the physics to accomodate, it wont work either as expected
Okay, I'll check for input in Update. But how can I only check for it while the player is within the trigger?
you dont, you check for it all the time and then set a value. Check that value whenever you want
I'm not sure I get what you mean. Check for it all the time and use a bool?
actually, can you show code? are you using GetKeyDown?
Yeah
my bad ignore what i said above, its incorrect.
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html This is only true for one frame. Physics stuff doesnt run at the same rate as update, so this is why its rarely working. If you have 2 frames between a fixed update (which is very likely) then in frame 1 it can be true, in frame 2 it'll be false and fixed update never ran between these
You might be able to get away with just using GetKey instead
If you really need to use GetKeyDown here, if it matters that you're doing the logic over and over, then i would approach this differently.
toggle a bool in enter and exit to indicate the player in the zone, then check its value in update
It worked! Thank you!
Oh yeah, that's a good idea
this code does seem a little odd though, the collision doesnt seem to be checking anything. if you enter any trigger at all, then you can press E. Is this what you want?
The code is attached to an object that has a trigger collider. So it's only if you enter that specific trigger and press E
this logic will run if other things enter that trigger too, but if thats not an issue then carry on
HI, I am trying to use new input system for my fps game. But i cant find how can i use the mouse raw input. Is there a way?
how can i do something like this
public enum Interactions {
use = "Użyj", pickup = "Podnieś"
}
public Interactions interactionText;
public UnityEvent interactEvent;
looks like localization
wdym??
translate the text in your app to other languages
=>localize
btw c# enum must be integral type
nah, i want to make an interaction system with different interaction texts but i don't want to manually set them with a string, and also so that other developers wouldn't make a mistake, so i want to make an enum holding string values, where devs can pick what type of interaction string they want to use for this object, use, pickup, etc
Maybe just static strings?
what does that mean?
other developers use your enum, so they cant make mistakes on the enum name
like this?
Yes
And I would suggest writing enum items' names in English.
im making a polish game, that's why i tried doing the "dictionary" type of thing, if i change it to english it would display in english
How would the language used to call your variables affect the game interface's language?
I mean the static keyword like
static readonly string something = "whatever"
like im using it to display interaction text
ohhh
so localization
Well, you may translate it
no 😭
If you want to make your game available in multiple languages, it doesn't mean you will have to rewrite all your variables in other languages
nah, i want only polish
the language of your programming wont affect the language in your ui, you can use tab and space only to code and it still displaying english
Alright, it's up to you
so i can't do a "dictionary" enum? and have to use polish names for enum items?
You can create a dictionary with YourEnum key and string value
But it won't be serializable
static variables are pretty much what you're trying to accomplish here.
but then how would i set them in explorer? for the interactionText
Im not entirely sure what you're asking. Some code would presumably know what string it wants then get the string
name your enum be polish should work? as long as the compiler can compile it?
i think you want to display the enum name directly?
void HandleInteraction() {
RaycastHit hit;
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, interactionDistance)) {
GameObject raycastObject = hit.transform.gameObject;
Interactable interactable = raycastObject.GetComponent<Interactable>();
if (interactable && Input.GetKeyDown(interactionKey)) interactable.interactEvent.Invoke();
if (interactable) {
interactionText.text = $"[{interactionKey.ToString()}] [{interactable.interactionText}]";
}
}
else interactionText.text = "";
}
public class Interactable : MonoBehaviour {
public enum Interactions {
Użyj, Podnieś
}
public Interactions interactionText;
public UnityEvent interactEvent;
}
yea, kind of? it'd be better if the names would be in english but polish ones are okay too
I see what you mean, easiest solution is likely gonna be a dictionary of <enum, string> for ease of choosing this in inspector
and what type would i use for interactionText variable??
Well either dictionary or just a method with switch statement.
You would replace that with a method call for example which returns a string
type the translation manually and use the enum in english to retrieve the text in polish
This is one example, I'm on mobile or I'd write
https://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings
The answer saying with extension method
ts too hard, as a begginer i think i'll just stick with polish names for the enum, don't want to make one thing take a day to do
If doing a switch is too hard, consider doing c# basics first
no, like doing switch is not hard at all, it's just that im a beginner at dictionaries and stuff, i'll check them out in my next project, rn it's not that needed
The switch would be a different solution from the dictionary. It would just exist in a method like in the last link I posted, not the first answer but the one under.
why this doesnt work properly
once i press a button
the cube starts moving left
but once i stop holding a button
it wont stop moving
nvm
Trying to make a script where material shaders glitch out with the BPM, but i cant seem to get the bpm script right.
how to make make game run horizontally on mobile?
you can set that in the project settings
You can either poll the mouse input with Mouse.current, or you can create an action in your Input Action Asset with a path to the mouse delta or position (or whichever info your looking for), and then reference that with .ReadValue<T>(), where T would be the type of input, for example yourActionMap.yourActionWithMousePath.ReadValue<Vector2>() if you were reading delta or position
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/HowDoI.html#find-the-gamepad-that-the-player-is-currently-using
I am using mouse delta right now, but isnt it just measure the pixels? So in the theory this is not raw input. Can you fix if i am wrong?
Delta is the difference in position, so when you move the mouse, it will tell you how much you moved the mouse, in pixels, yes - if your mouse is at say [980, 100], and you moved it to [960, 100], your delta would be [20, 0]
I would check the values. I believe precision of the input depends on the platform/hardware APIs and is not rounded by Unity.
i'm using tilemaps for the first time, however the colission is weird. i'm using 'TileMap Collider 2D' but the collider on slopes is off. there is a gap in which the player gets stuck. does someone know how to fix it?
Oh okay, thanks!
Open image file, select it, and go to sprite editor.
In the sprite editor you see this on top left.
Whats the difference between a Vector and a normalized Vector
How would you write a z-forward directional vector in unity
Normalizing a vector makes its magnitude 1
Thx
I guess just: new Vector(0, 0, some number)
twice as large in the z direction?
for direction it means the same thing as (0, 0, 1)
however, if you're looking for distance along with direction, (0, 0, 2) gives you information such that we're looking in the z-forward direction and up to 2 units of length in that same direction
but if you're normalizing you're usually doing it on something for direction, so even if you had some vector greater than 1, it'll normalize it back into (0, 0, 1)
Ok thx
I stole some code from ChatGPT and wanted to know why it normalized the Vectore
general rule of thumb, if you're doing a calculation resulting in a direction, normalize it
Ok thx
i need help.
I tried creating texture and saving in data folder:
File.WriteAllBytes(Application.dataPath + "/test.png", bytes);
But it says that access denied
I wouldn’t reccomend doing that
Why? it works perfectly and it gives me a description in the code
Then you should've known why it normalizes the Vector
And If it doesn't give me the results im looking forI just don't use it
And it won’t always work perfectly, especially if you need multiple scripts to interact in a specific way.
It said that it normalizes the vector because it's for direction but I didn't know what it means to normalize a Vector
Which is why you shouldn’t use chat gpt code
You should know exactly what the code your using does
If the code it gives me doesn't work I just don't use it
That is true though, I try to use it as less as possible but I suck at coding so that's still quite often
Learn coding, then use unity
Don’t turn to chat gpt
The only way to not suck at coding is to learn and practice
I suck at base jumping, but if I wanted to get good at it, I’d learn how to do it, not have somebody else do it for me
Kinda ruins the entire purpose, if that makes sense
hello, does a class that extent another class also inherit the base's execution order ?
? Execution order?
in project settings
Oh sorry, I’m not sure
I don't think so, no. Execution order is stored for each script asset.
and I don't think Unity is aware that script B has a class that derives from a class in script A
Hello friends, I am new to unity and i have a question. I messed around with unity's built in Character controller and using rigid body, and the movement always felt unsatisfying in a way. The thing i want in mind is a way for the movement to accelerate at a given rate, and also decelerate at a given different rate.
To further elaborate this and what I want, When the character moves forward, there should be a few seconds for example where the character is gaining speed until they reach their maximum speed, and when the user lets go of the forward button for example the character would stop moving but not instantly (which is the thing i am trying to fix). Further examples would be Cars, imagine car on neutral, gas peddle = accelerate, leave gas = decelerate.
I am using the old input system btw
I found a solution for the acceleration that works just fine (Image 1)
I just cant find one for the deceleration.
you just need a different value when slowing down
Doesn't look like you're using Rigidbodies, but yeah just use a different acceleration value
acceleration * 3 would make you slow down three times faster than you speed up
is there any way that i could get the Start to execute in a precise order without having to add every children of my base class one by one ?
yeah, that's something I've ran into before. I've had to split up my GameManager a bit just to combat it.
why do you need a precise ordering?
In the screenshot i am currently using the character controller
Usually properties help lessen the amount of information I needed before everything is loaded in. Just bind references then execute later.
to set a variable in cascade
object A sets the variable of B
B does some operation with the variable then sets the variable of C
Do you assign references so that A can find B and B can find C?
I'd just make this explicit.
but it depends on the ordering
Instead of using Start, add a "setup" method.
A will still use Start.
It calls B's Setup
Start is pretty random and I try to avoid it
Then B calls C's Setup
oh that's smart
This is roughly how I do all of my UI setup
thank you
my settings menu starts with a list of categories/settings
the list creates all of the buttons and settings entries, then creates new lists for the categories and tells them to setup
another useful thing: if you sometimes have A call B call C ..., and sometimes just have B or C by themselves (that don't need any setup), you can do something like this
Another idea I've had is just make everything a prefab and instantiate at the start by iterating over the list but it's a pain then to work on the editor
public class B : MonoBehaviour {
private bool initialized = false;
void Start() {
if (!initialized) {
Initialize();
}
}
public void Initialize() {
initialized = true;
}
public void InitializeWithData(int whatever) {
// do something with that data
Initialize();
}
}
I used this for a component that was sometimes set up with code and was sometimes setup manually in the scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.right * 3 * Time.deltaTime);
}
}```
it is not really moving my object, anyone knows why?
wdym by that? is it moving slowly or not moving at all or what?
dont multiply it by deltaTime
not moving at all
the object is intially in the air so when I play it, it goes down and that is it, it never goes forward
get rid of deltaTime then try it and see
multiplying by deltaTime is correct here
otherwise, you will be moving at 3 meters per frame
rather than three meters per second
works now
is there a Rigidbody or CharacterController attached to the same game object?
Yes
You need to use those to move
Don't directly change the position of the transform.
Which one are you using?
I have a train which is connected but I had added the scrip and rigidbody to both but forgot on the one in the middle, how do I add the same script on it?
If you're using a Rigidbody, then either use AddForce to push it or MovePosition to directly give it a new position
or change its .velocity
what do I do agian, I am confused
Another problem now is that not the entire part of my train moves, i checked that all of the gameobjects have the script, why is one not moving?
use the Rigidbody to move instead of moving the Transform directly
Your script currently just changes the position of whatever game object it's attached to.
It doesn't care about physics at all, because it's not doing anything with a Rigidbody
Now, the rigidbodies will still do something -- you're going to be fighting with them
something like:
public class Move : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 movement = Vector3.right;
rb.MovePosition(rb.position + movement);
}
}```
Don't forget about the Time.deltaTime / Time.fixedDeltaTime.
Also consider adding the float speed
does it work? also would be better to use AddForce or set the velocity
MovePosition ignores collisions too
use velocity or AddForce
hoenstly sounds like it's working just moving too slow for you to notice
how big are these objects
no, that's when you set the position property
MovePosition attempts to actually move to the destination
Nah - it goes right into walls and needs to be depenetrated, for dynamic bodies
for kinematic bodies it moves them and collides with other things
yet:
Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.
MovePosition moves the object to the desired position in any case, even if it meens going through the wall.
yes it's intended for kinematic bodies
Ah, I see! So it hits things, but it is not hit by things.
yeah. It's intended for teleporting kinematic bodies while maintaining interpolation and hitting things
good to know...I was under the impression that it attempted an actual movement of a non-kinematic rigidbody
good example is Moving platform
guys still lost
change it to AddForce or set the velocity
how do i use addForce
look at the documentation for it
google Unity AddForce
indeed -- that cube went straight through the wall
that's actually pretty annoying. there doesn't seem to be a way to neatly move a rigidbody to a new position in a way that respects colliders
interestingly, when the rigidbody is non-kinematic, it doesn't hit other non-kinematic rigidbodies along its path
i had to make it kinematic for that to happen
Your code with the MovePosition can be rewritten with the AddForce by removing the position from the 1st parameter, as the MovePosition takes the new position, and AddForce the direction
have an interesting problem trying to first person camera controls with the new input system, trying to clamp camera rotation on the x-axis taking mouse delta as an input. any suggestions on how to appropriately clamp the main camera's rotation during update? issue im running into is that since delta is constantly refreshed, i never actually come close to approaching my clamp value per update unless i sling my mouse, so there's nothing actually limiting the global rotation of the camera
public class Example : MonoBehaviour
{
public float thrust = 1.0f;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(0, 0, thrust, ForceMode.Impulse);
}
}```
still not moving
Also deltaTime is not required in this case, still serialize the speed, as it might be not enough for you to see the changes
The force is applied just once for the z axis and is too small.
why are you using the 2nd bit of code? use the 1st one
transform.right * thrust instead of 0, 0, thrust
also increase it a bit instead of 1
using UnityEngine;
public class Move : MonoBehaviour
{
public float thrust = 5.0f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(transform.right * thrust, ForceMode.Impulse);
}
}```
you mean like this?
yeah i guess, also is the value of thrust actually not 0 in the inspector? the code doesnt matter if its 0 in the inspector
where in the insepctor is it? Can I not change it duing script? Isn't there another easier way?
no
My first code: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.right * 3 * Time.deltaTime);
}
}```
the inspector should be on the right of your screen in the Editor when you click on your gameobject in the hierarchy
The value you assign via code is the default value for the Inspector, when the script is first added
had worked before, but after I made huge changes in the scene, it doesn't anymore
you can just not use a variable? or you can set the variable in Start before you use it
still not moving
show the code
using UnityEngine;
public class Move : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(transform.right * 5, ForceMode.Impulse);
}
}
ok code should be fine, we need to see whats going on in your scene/game to know how to help
show the inspector of your train
why do you have 2 of the same script on this object?
i just realised
I am doing a flood check to check if all objects in a ship starting from the core are connected, I use the offsets from the core which are multiples of 1.28, for some reason here (-1.28,-1.28,0.00) does not equal (-1.28,-1.28,0.00) even though it does
that object is veeeery far away from the world origin
I actually have 3 lol
it's also colossal
an impulse of 5 means a 1 kilogram object will gain 5m/s of velocity
if the object is a kilometer across, that will barely be perceptible
Ship looks like this with the core being the red one, the objects are in a grid pattern having 1.28f distance between each adjacent object
you're using Equals, which has zero room for error
I would suggest using Vector3.Distance to check if you're within a small margin
here i have this code, it's for a scanner that scans a selected area so it will show where are the nearby objects, and this IEnumerator spawns, and then destroyes the dots:
private IEnumerator ScanRender(Vector3[] points)
{
List<GameObject> pointClones = new List<GameObject>();
foreach (var p in points)
{
GameObject pointClone = Instantiate(point, p, point.transform.rotation);
pointClone.transform.parent = pointsParent.transform;
pointClones.Add(pointClone);
yield return new WaitForSeconds(0.000000005f);
}
yield return new WaitForSeconds(dotLifetime);
foreach (var pointClone in pointClones)
{
Destroy(pointClone);
yield return new WaitForSeconds(0.000000005f);
}
}```
I want this process to happen really fast, so it will look satisfying but won't be annoying for the player, and the problem is that no matter how much smaller the value in "WaitForSeconds()" is, it still seems like it waits the same amount of time. does it have a limit? if it does, then how do i bypass it?
alternatively, work in grid cells instead with Vector3Int
ok will try
operator == for Vector3 has a slight fudge factor
this is what I'd go for
I am afraid I dont understand
you mean scale them down to 1 instead of the odd value of 1.28
yo, guys, im making a simple collision system for my game
I'm using Tilemap Collider 2D, Rigidbody 2D, Composite Collider 2D
is there any way to shrink down the collision hitbox more?
That's roughly the idea.
Have you ever used a Tilemap before?
When you use a Tilemap, you can ask it where in the world a specific cell is.
The resulting position depends on:
- how big each tile is
- where the Tilemap has been positioned
So, for a 3x3 grid placed at the world origin, the cell [1, 0, 0] has a world position of [3, 0, 0]
in your case, you have a 1.28x1.28 grid
It's easier to reason about which grid square the tile is in than where in the world the tile is
[1, 0, 0] is a neighbor of [0, 0, 0]
you don't care how big the tiles are or where the Tilemap is
In the game it more important where the objects are at in relation to the core which Obj.offset, but I will sure look into that when I try to optimise thanks for the suggestion
same idea -- you could store the offset as a cell position
so this object is 4 cells right and 3 cells up from the core
You can use the Grid component for this.
couldnta asked for an easier solution 🙂
https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html
This tells you where in the world a cell position is
stick a grid on the core and use it to translate back and forth
If you want to know which cell you clicked on, use https://docs.unity3d.com/ScriptReference/GridLayout.WorldToCell.html
also you were right I was just using wrong function to compare vectors
yo
im doing a unity course and its saying my code is wrong even tho i did exactly what the instructor did
can someone tell me what the problem is
missing )
you forgot a bracket at the end
you did not do exactly what the instructor did (:
omg
as a rule of thumb, you must match all ( ), { }, and [ ]
ill fix it
Note that your code editor was indicating an error at the end
and in this case, it's informative!
this is precisely the error you made
before not after;
this is not it
OH
; terminates a statement.
; is almost always last
it is unwise to put it in the middle of your statement
no problem
the fact i needed 23 minutes and outside help to fix that is astonishing
didn't the console tell you ")" expected
btw does anyone know how I can decide what layer my 2d character is on without changing the z coordinate?
I think the word you are looking for is 'painful'
it just said expected nothing more
indeed
so its like in front of the background
why can't you change the Z axis?
Layer Order
the position of the object changes the position of a different object
how
are you using Sprite Renderer ?
i think so
The semicolon had an error saying it expected a parenthesis, meaning it was expecting one BEFORE it
Where you see an error like that is always after where the suggested character should go
mb ill keep that in mind
hello, im coming back to unity after a long pause, so i forgot most of the thing i knew.
i was watching a video from sebastian lague where he was simulating fluids.
but at abt 30 sec, he typed DrawCircle(Vector2.zero, 1, Colour.lightBlue); into update.
i never saw a function like that before, and when i went to try it out, it says both the method DrawCircle() and Colour dont exist. but it works fine in the video.
im confused. is there a similar function to that that works?
this is the video: https://www.youtube.com/watch?v=rSKMYc1CQHE
Let's try to convince a bunch of particles to behave (at least somewhat) like water.
Written in C# and HLSL, and running inside the Unity engine.
Source code:
https://github.com/SebLague/Fluid-Sim
If you'd like to support me in creating more videos like this, you can do so here:
https://www.patreon.com/SebastianLague
https://ko-fi.com/sebastia...
Both of these must be third-party code
unity's Color class (not Colour) doesn't have a lightBlue property
and there is indeed no DrawCircle
system.drawing.color does tho
i didnt see anything like that in the description
SORRY my phone glitched and the message got sent like 5 times and unity muted my messages lmao 😭
hi, how know this how can I fix
Game scripts or other custom code contains OnMouse_ event handlers. Presence of such handlers might impact performance on handheld devices.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
I was just patting my own back a bit lol
ahh okay.. but yea, apparently ur system was pretty accurate to real life physics..
yeah, heres the code if u wanna have a look, its a static class that takes the current velocity as a parameter as well as other parameters and augments the value, which would get called by the character in update and stuff
is there a similar function to that or should i just create a sprite and clone it when necessary?
Why do you want to draw a circle specifically?
circles are cool
idk, they are the best representation of particles, and they are easiest to move and shi
Im trying to make a camera in my game move like the unity camera, I already managed to do the movement because it was ez, but now its time for the hard stuff: rotating. Esentially, whenever i drag my mouse, the camera's rotation should follow it, just like it does in unity. How can I do this?
ill do it using prefabs i guess
But you want to use them as particles? Isn't the default particles already a circle?
Use that
by particles i mean like atoms
or molecules
not effects'
i forgot particles have 2 meanings
use the input of the MouseX/Y to add rotation to X/Y
not that much different than fps camera without the clamp
what `is the thing called, where i have an array, but each element has multiple variables
that'd just be an array of objects
or structs
[System.Serializable]
public class MyData {
public int florp;
public string foo;
}
public List<MyData> items;
like
[
{v=10, x=4}
{v=4, x=5}
.
.
.
]```
add rotation is kind of, the hard part
because im not sure exactly how to do it to say the least
oh
whenever you have a big problem, chip away slowly, start small 🙂
its 🧀 but it works
I have a UI menu and a sprite as my cursor. I've used "Cursor.visible = false" to hide the cursor. I'm trying to find a way to create sprites that are clickable, like menu items. how can I do it?
weeeee
ayee
i keep forgetting i have no clamp..
anything with a collider can be clickable.. with the EventSystem
so you're using an image component as mouse cursor ?
Yeah
dont forget to disable the Raycast target on it or its going to block other UI elements
even 3d objects if u have a graphic raycaster component
^ yup, thast how i do my custom cursors.. tehy are image components that follow the mouse position after converting to screenspace
w/ raycast target disabled u can click thru to the element under
I have an image component as my cursor. Then my menu screen is another image and I've got a box collider on a specific part of it that should be clickable. Thing is, I click and nothing happens. What am I doing wrong?
you dont need a box collider for an image component
How can I get it so that only part of the image component is clickable? As in, it will trigger something
Thanks!
put a blank image component over the top of it
and disable the raycast target tick on that
thats the only way i can think of making just part of the image clickable
ohh interesting
i didn't know it even worked like that..
i thought it was a bounds type of thing
but default it will click on a transparent pixel right?
b/c if not i need to redo some stuff 😄
without it, uses the rect transform bounds
ohh okay good good
I'm confused. I'm made a transparent image over where I want the clickable part of the image but I guess that's not gonna work?
if you want the whole image to be clickable just put even trigger for it
The skeleton is moved on the Y axis when he wait, can you help me ?
Dont need to do that. Just use that link to set the threshold on your original image
I only want part of it to be clickable
then use the code provided
That is the whole point, did you read the docs I linked?
when he.. what?
when the coroutine is calleed
oh okay
It says "The alpha tested is retrieved from the image sprite only", but I haven't got a sprite set on my transparent box. I guess I should?
you said you had an image, that is the sprite
i doubt his image is based off of alpha..
The background image, yeah. But I've got another transparent image on top where I want it to be clickable
you can put an event system on that image component
and have access to OnClick, etc
EventTrigger component is the easiest imo.. but theres other ways too.. like using the IPointer Handler stuff
I'm not understanding your setup, I thought you were talking about a clickable image and needing to ignore parts of it
i think he has 1 big image.. with multiple parts he wants to click on
like.. normally id recommend chopping it up into seperate sprites
w/ the sprite slicing tool thing
well thats no problem.
Set the alpha of pixels of the image that can be clicked to 1
Set the alpha of the pixels that cannot be clicked to 0.9f
Set the alphahitThreshold to 0.95f
@west sonnet can you share a screenshot of the image/s ur working with?
so we have some more contex
lol.. thats sorta genius
idk why this is happening.
the enemy model keeps following my in the wrong rotation
it's sorta obvious, I've used it many, many times
but am i missing something? wouldn't setting the alpha make it sorta transparent where u cannot click..
with an alpha of 0.9 you dont see the difference
ahh, okay. 👍
this is really useful if you want to make a select circle of images like a pie chart for example
select the enemy with the move tool
and see which way the blue arrow is pointing
So reimport your model with the correct transforms
hi
how do i have random.range return a different number every time the if statement its in is called
right now it does the same number over and over
It returns a different number each time
if you're seeing the same number you're doing something wrong
shwo your code?
oh oaky
if (distanceToPlayer <= meleeRange)
{
int randomAttack = Random.Range(1, 2);
Random.Range(1, 2) will always return 1
because the upper bound is excluded in the integer version
i thought it would do one and two oops
simple
so 0,2 is correct
if you want a 50/50 chance at something do this:
bool coinFlip = Random.value > 0.5f;```
when is it best to go from capsule to real charchter, in the beginning of your game or more at the ebd
end
idk sometimes i do both
depends on your game and what's important in your game
i like having my game look nice from the start even tho its a bad idea
cause u will have new ideas which will require new art
you can work faster w/o fancy graphics
Its good to work on the art/making look nice when taking break from doing lots of the coding
is it more or less code efficient to start variables mid script
like for example the int randomAttack there
wdym by "start variables mid script"?
local variables are a good idea
Generally a variable should have the minimum scope required to do its job
that is in the middle of the script and usually my variables are b4 the start
in the methods?
I'll just reiterate this ^^
i understand
in this line of code how can I change how high I can jump? using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}