#💻┃code-beginner
1 messages · Page 565 of 1
..flex
my project isnt broken but
is this a problem?
Does it go away if you clear the console?
As long as it doesn't appear frequently enough, it should be fine. Probably an editor bug.
Maybe note what you did for it to appear next time you see it.
You didn't find anything?
i didnt actually understand how they work
and just copying makes it red lined
watch a tutorial and follow it carefully
my code is different
and idk where to put
top one is video
you mean a knockback or
sway
@echo kite Is this first person weapon sway or something?
yes
You should do something using Mathf.Sin or Mathf.Cos where while moving you have a timer variable which counts up.
Something like Weapon.transform.localPosition.x = new Vector3( Mathf.Cos( time ), 0, 0);
The idea is you utilize the undulating behavior of the sin/cosine functions to get the back and forth sway you're looking for.
In your update function you'd want to count time:
like this?
Update(){
time += Time.delaTime;
}
If you have time moving and you pass this into Mathf.Sin() you will get the undulating behavior you're looking for.
I can't see anything in that screenshot.
transform.localPosition += (Vector3)mouseAxis * weaponSwayAmount / 1000;
I don't know what weaponSwayAmount will be affected by.
Atm that's just going to add a local position offset to the weapon, but if weaponSwayAmount keeps growing you just end up with your weapon moving off in some linear direction.
This is a sine wave, it undulates from 1 to -1
When you call Mathf.Sin( time ) you can get an undulating value you can use for a swaying motion.
You can then do something like:
transform.localPosition = new Vector3( Mathf.Sin( swayTime ), 0, 0 );
This moves the weapon object back and forth on the local X axis.
You can also have a constant multiplier in there to control the sway distance.
You can then do something like:
transform.localPosition = new Vector3( Mathf.Sin( swayTime ) * _myConstantSway, 0, 0 );
In the Update() method you can accumulate time into the variable
void Update(){
swayTime += Time.deltaTime;
}
Play around with this
You should get something of use
characterController.Move(moveDirection * Time.deltaTime);
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
ApplyWeaponSway();
}
private void ApplyWeaponSway()
{
swayTime += Time.deltaTime * swayFrequency;
float swayOffset = Mathf.Sin(swayTime) * swayAmplitude;
playerCamera.transform.localPosition = initialCameraPosition + new Vector3(swayOffset, swayOffset, 0);
}
}
i tried this no errors but it doesnt work
your swayAmplitude and swayFrequency values are sensible?
playerCamera.transform.localPosition = initialCameraPosition + new Vector3(swayOffset, swayOffset, 0);
You're applying swayOffset to X and y equally. That will have the camera moving diagonally.
You'd have to have a different mathematical function running for X and Y independant of one another (only dependant on time) to get the effect you're looking for.
You'd have to describe what you mean by "doesn't work" more.
If I attach two or more CircleCollider2D to an object, how would I differenciate between them in the script?
well, how do they differ?
position? size? trigger? etc
use that to differentiate them
All triggers, different radii.
but if they need to be differentiated you probably should just not have them on the same object
and they're all for different things?
Yeah.
then you might want to just have them on separate objects, yeah
Put then in child objects and then just reference them by object name?
or if you're using messages, you could setup layer overrides on each, and then you could differentiate what to do based on which one was hit, but idk if that'd work for your usecase
i was gonna suggest letting each child handle its own trigger, but can't really say without more detail
Like an example would be an enemy that has a radius for chasing range, one for checking long range ability range, one for short range ability range
You will also know if you attach a script which uses OnTriggerEnter: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider.OnTriggerEnter.html
This will tell you what collider was involved here.
And thus you will know based on that information.
I’ll check it out
👍
I’m thinking it would be possible to add colliders as an array in the script and have them referenced by the index?
Might make it slighly less readable though?
It very much depends on your usage.
True.
You'd have to specify what you mean by "differentiating"
the collider there is the other collider, not the gameObject's collider
Simply as in, if I write a script for OnTriggerEnter, I have no idea which collider I’m using
maybe, yeah
So if that script is on the trigger object
You will know it is this trigger
That was mostly my thinking
Chris, do you agree?
Yeah, but if I have more than one trigger on the same object..
So.. using child objects for each trigger?
but there's multiple triggers on the object, or they'd need to communicate back to the parent
Root
Trigger(script)
Trigger(script)
...
i don't think the "communicate back to parent" part is super ideal
Yes I would have scripts on each object, and a script on the root
i guess it would work though
I think OnTriggerEnter would use whatever collider you put on that gameobject first most likely
No? Is there a better ideal?
no, any of the colliders being entered would trigger it
I do this sort of thing often enough
It's not specified
This would be much easier if Unity just let us rename components? ChaseTrigger and WithinRangeTrigger
i can't think of anything better 
ah i got it confused
you could subclass the colldier
oh also there's another approach if the enemies just have to track the player, just check what distance the player is from the enemy
That's effectively the same as just attaching a trigger listener script as I mentioned.
Listening for OnTriggerEnter
It’s a bit more complicated than that. It’s troops vs troops. First trigger adds each opposite unit to a list
i feel like it might receive messages from other colliders too, if those messages are just sent to the gameobject
rip
I would have a script on each trigger which just notifies the parent (a script on the parent. "Unit" script, or whatever) that it's involved in a trigger event
The parent ("Unit" or whatever) would do the tracking of add/remove based on listener calls.
This gives you the involved trigger, and the necessary trigger enter/trigger exit events.
having a manager script is a game changer
It's not a manager, but it's the root of the responsibility chain here.
The Unit wants to know what trigger events happen.
The triggers provide the specifics of each interactions.
I've done this exact sort of thing before in various circumstances.
It works well enough, soon enough you forget about the underlying implementation 😛
i mean in a way it acts as a manager
Agreed
can some one give me script for a off second script in inspector?
one line of code i need
what is an off second script
yeah no clue what you actually need
second
yes
not a code question, #💻┃unity-talk
lightSource = GetComponent<Light>(); ? what change
what change for what?
and then i know lightSource.enabled = !lightSource.enabled;
but for script
not light
i found this
but i need close in inspector script my second
scripts are components, you can enable and disable them as well
script = GetComponent("secondscript")();
```like this?
no, that's now how you call GetComponent
var myScript = GetComponent<SecondScript>()
or
var myScript = GetComponent( typeof( SomeScriptType ) )
or
var myScript = GetComponent( typeof( SomeScriptType ).Name )
or
var myScript = GetComponent( "ValidTypeName" )
ok
hi, is this the expected result?
no don't use the typeof one
it seems like some components were gone after i save and run the script
I'll send the script below
is.. what the expected result, exactly?
Expected result of what?
yeah no don't use any of these except the generic one
They're valid based on the documentation and some cases they are useful either way.
adding control to the sphere
My preference is the generic implementation
i remember i had 2 components
they're valid, but they generally are not useful, and they are definitely more fragile
now it's gone from the sphere
GetComponent<TComponentType>() <- my preference
1 is rigid body
None of them are fragile other than the string argument version
The others are all based off of type arguments
I'm not arguing for them, but they aren't fragile.
other is player input component
the generic one, is... generic, so it returns the type given
the others are not generic, and return Component
so you need to cast that
and now if you ever need to change what component you get, you won't get warned about type mismatches since there's technically no compiletime mismatch
That's fair. Anyway, I was just quoting the documentation.
typeof does not mean a type argument
that is a value argument, taking a Type
it isn't generic, it isn't the same
typeof generates the type
not really, no
It's a argument of type Type.
and that isn't a type argument
Anyway, off topic from the OP.
As Chris said the preferred method is the generic method.
But those are your methods for getting a component from the object.
the generic one is generally going to be the only useful one
if you ever need to use the others, that's a sign you've gone down the wrong path, and you have pain inbound
I think that's a different discussion.
there's not much to discuss there, that's just how it is
the player doesn't move
I've used those other methods in situations where the type is derived from an attribute and not where the generic method can be used.
prefer what you prefer.
so while not in play mode, your rigidbody and player input were there, but in play mode, they're gone?
i think they're gone since I reset the projectfile at the external tools
and yeah gone from all modes
I've remade them quickly
but still
i still cant control the player
is that what the script intended to do?
i dont have error log anymore, but it's not the proper result I think
since the player is supposed to move
have you setup your input actions
apply input data to the player?
yes?
would like to see the script?
here's the script
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm making a car for my game and it seems like w and s work too slow and probably broken. I tried modifying some values but still no result
I'm copying this tutorial: https://www.youtube.com/watch?v=CdPYlj5uZeI
CarController: https://paste.ofcode.org/32Aw6yCVr5P7PCtu6B3DsPu
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
no, i have no idea what you mean
have you set up your player input
have you assigned the player actions
here's a graph curve that I use if it's important:
This is incredibly specific to your project.
well, I copied it from youtube
I'm trying to have similar car like in the video
or I don't get what you mean
Unless someone dives into that video/code base you're going to have a hard time getting assistance.
mm indeed, how should I change the question tho? I think I typed everything correctly
I think you'd have to break it down based on the code involved.
And hope someone can see something.
also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
part of the code for moving car forward and backward
I did add the link for code
how can i make a script for when the user press either "a" or "d" to move either left or right? i cant seem to make it work
show what youve tried and how youve attempted to debug
and what exactly isnt working? are you not noticing any changes?
well the code so far that it snot comented its for the player to fly up and down and to rotate when pressing a and d
i also want the player to be able to go to the side but with all the comented code it didnt work no idea why
and how did you debug that it wasnt working
also why is update underlined?
the player isnt moving
or maybe the player is and you just cant notice it for a plethora of reasons
this is a uni project with a friend of mine and he wrote that code, i comented it because it didnt work but on the beginning of the sheet it as "private float _horizontalInput
that has nothing to do with what i said
i have no idea why is it underlined it was not writting by me
could be that
so hover over it and see whats causing it
yes, which is why you need to propely debug
its not moving
hey, is it possible to create a 3D game, which will have a phone with a 2D game?
something familiar to screenbound
yes
Anything is possible
okay, now im wondering which project type should i choose for such game
is it a normal universal 3d?
I have this code. It works just fine, except the enemies don't spawn at the position of the enemySpawn object. Why is that?
using System;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform enemySpawn;
public Collider2D playerEnemySpawn;
public GameObject player;
public Collider2D playerCollider;
public GameObject enemy;
public int numberOfMaxEnemyThatSpawns = 3;
private int spawnedEnemies = 0;
private bool hasSpawned = false;
private void Update()
{
if (Physics2D.IsTouching(playerCollider, playerEnemySpawn) && !hasSpawned)
{
Debug.Log("Spawning enemies...");
for (int i = 0; i < numberOfMaxEnemyThatSpawns; i++)
{
GameObject newEnemy = Instantiate(enemy, enemySpawn.position, enemySpawn.rotation);
newEnemy.transform.SetParent(enemySpawn);
spawnedEnemies++;
}
hasSpawned = true;
}
}
}
Why is this script called Enemy if it seems to actually be a spawner
Anyway when you do SetParent it will move the object. Why are you doing a separate SetParent call?
I thought it would move it to the position of the object
You can just do Instantiate(enemy, enemySpawn.position, enemySpawn.rotation, enemySpawn);
I will write the actual part of the enemy.
You don't need a second call
okay. thanks
Name your script better. This is an EnemySpawner
Okay, will do.
You can pick any project type, it doesn't matter. All that choice does is start the project with some packages already installed
ohh okay thanks
im struggling to find what i need to do to get this text to show my 2 Ints. i know where to put the code just not what i need
myText.text = $"Congrats you won in {moveCount} moves and {points} points";```
Didn't fix it.
using System;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public Transform enemySpawn;
public Collider2D playerEnemySpawn;
public GameObject player;
public Collider2D playerCollider;
public GameObject enemy;
public int numberOfMaxEnemyThatSpawns = 3;
private int spawnedEnemies = 0;
private bool hasSpawned = false;
private void Update()
{
if (Physics2D.IsTouching(playerCollider, playerEnemySpawn) && !hasSpawned)
{
Debug.Log("Spawning enemies...");
for (int i = 0; i < numberOfMaxEnemyThatSpawns; i++)
{
Instantiate(enemy, enemySpawn.position, enemySpawn.rotation, enemySpawn);
spawnedEnemies++;
}
hasSpawned = true;
}
}
}```
Did that, and it still does this...
legend ty sm
What does your enemy prefab look like?
use a standart sprite from unity, i assume there is somethign with your sprite, maybe it is just not centered or has whitespace
It's not the prettiest
Is the sprite a child of the prefab root or is it the actual root itself?
A child
Is it positioned at the same position as the root in that case? If it's anywhat offset from the prefab root, it will be offset from wherever you move the prefab to after it's spawned in
I fixed it. It was offset. Thank you guys for the help.
PlayerAddHorizontalMove = Input.GetAxis("Horizontal") * Time.deltaTime * sensivity;
Player.AddForce(Player.transform.right * PlayerAddHorizontalMove, ForceMode.Impulse);
No.
maybe
close but why rotation?
oh I thought it's camera lol like doom
read it wrong
they said Move not rotate
this might work
To clarify: you're saying that you have an empty object in the scene which has references to the models / weapons for the different characters?
you're going to need to be a LOT more specific about the problem than that.
and wrong chat
i made a player in blender and imported it then i deleted the previous cylinder and i put the camera in its head and no matter how i position it its always looking to the right
hes tposing rn and all you can see is his right arm
sounds like you need to rotate the camera?
Blender and Unity don't use the same axis orientation, make sure you made the change in Blender's export settings. You are also asking this in the wrong channel
@queen adder kinda tough to understand what you've got and what you're trying to accomplish, sorry. You have 4 objects in the scene with sphere colliders, each one has a reference to a model in the project, and you're trying to figure out how to put the objects in an array or something...?
Ah, right
Hey everyone :) Can someone help me with my code/unity??
The Dashing doesnt seem to work cuz when I start the game I checked in the inspector the speed and dashingPower variables and they dont seem to change + I get the error that the referenced script on this behavior is missing
So usually what you'd want to do is not to put a copy of every weapon into every character, but instead, create the weapons completely separately from the characters and then parent them to the right place in the skeleton
where is the error ?
show exact error
I meant "warning" idk
did you save any script changes during play mode ?
so you have a list of your characters, and a list of your weapon prefabs; once you've chosen a character, you instantiate the weapon prefabs and then set their parent to the appropriate bone in the character's skeleton
no I even restarted everything
This shows up when you have a component that has an invalid script reference, just remove it. Its not related to your movement.
e.g a monobehaviour you deleted but never removed from a game object
mhh okay, the "dash" still doesnt work tho ?
like it should be dashing forwards and the speed should go up no?
Ah you mean like how to identify the hand? The simplest approach is just to say that the attachment point GameObject has to have the same name in each character's skeleton.
I would probably make the code which instantiates the character once the player selected it, then also instantiate the weapons afterwards. That way the character itself doesn't need to "know" about the weapons.
this is painful to read this is not difficult to do 😐
As they say, spawn in the required weapon and set its parent/pos to be placed where you want in the player bones/transforms
like:
void OnSelectedCharacter(int characterIndex)
{
PlayerCharacter = Instantiate(characterPrefabs[characterIndex]);
foreach(var weaponPrefab in weaponPrefabs)
{
var weapon = Instantiate(weaponPrefab);
ParentWeaponToCharacter(weapon, PlayerCharacter);
}
}
well at runtime you get what weapon the player is using and create that. if they change it, destroy old one and spawn new one?
Have a think about what you are unsure about so you can be more detailed
(I was imagining that other weapons would be SetActive(false) rather than destroyed, but sure)
put them in an array then use a for loop to grab different on based on index or something
What do you mean by "with script inside" ?
If the player can swap between multiple weapons frequently, then keep them and set active.
if it doesn't happen much (e.g. only during some customisation) then no point keeping old weapons.
When character chooses it, it comes with button array.
You mean like an array of "which button selects which weapon" ?
So before the game shall i add to the Awake(); array that activates the proper hand to attach weapon on?
It's not clear which script's Awake() method you're talking about. I would generally not recommend putting scripts on the Character or on the Weapon which handle this (in Awake() or otherwise) - it's usually better to have your Controller/Manager component take care of creating and parenting the objects together, instead of distributing the responsibilities between all the individual objects.
Right
You can share the code into a pastebin and drop a link in here for everyone to be able to help out, if you want.
OK I see - so you are not using prefabs for this, you just have all the objects in the scene
So you need handTransform to point at the correct transform once the player selects a character
Do you have a similar CharacterSelect component?
You can make the CharacterSelect component get the WeaponSelect component and set the handTransform field on it.
It solved itself again and I have no clue how and why. now it works again, I was just adding a simple:
"[SerializeField] private GameObject _testGameObjectToApear1;" in the beginning of the monobehavior class and
"_testGameObjectToApear1.SetActive(true);" inside of my OnClick event with my Sound effect, phone vibration and saving system"
to enable a image in the panel to even know in the android build, that the script was reachable even if the Sound, Vibration and Saving inside of this script was not working.
But the sound, phone vibration and saving also works now but I was only adding this few lines of code to drag a UI Image gameobject inside of it.
How is this even possible?
If it were a mechanical machine, I would have said that something was probably jammed, or if it was a water pump, there were probably a few air bubbles in the pump, which is why it didn't work, but how does that apply to the Android .apk and .abb versions and the Unity Engine?
Good luck 🙂
There's a couple of ways I can suggest:
- Make sure the hand always has the same name in every character, and then use
Transform.Find()on the root of the character to find it - Put a component on the hand (like
WeaponAttachmentPoint) and useGetComponentInChildrento find it - Put a component on the root of the character which stores information about the character, and one of the fields it can store is
Transform handTransform
Will this script make the object I attached it to move 1 tile in the x direction?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and you should configure your !IDE first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
AI Code? Really?
is it?
wher?! 🧙♀️
Yes, I tried watching tutorials but everything seems overcomplicated
I just see blinding light
3 lines of code, 3 comments, yes, I guess so
making a game isn't exactly trivial no
but you can !learn properly
Surely the best way to answer that question is to just test it?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the top line kinda makes think that eh..
theSizeOfThisThing = 10; // the size of this thing
follow the pathways ^
you won't learn anything by pasting code from ai especially when you have 0 clue what you're pasting
if ur gonna use AI
im not gonna go on a witch-hunt..
but test what AI gives u.. and if its wrong..
Go BACK to AI and ask it to help u solve it
keep it self-contained
"Help i made ai generate code i dont understand and it no worky whyyy"
🧪 😈
"AI" is being generous
more like a fancy google search that talks to you, mostly incorrect
I don't know if It works yet
logically it looks fine to me
we're pretty close to just typing in google-search and having gemini generate the code right there at thet top of the search results 😈
in theory it does, but you have no idea what you're doing you should start with the unity learn lessons
The correct term for current 'Ai's' is Stochastic Parrot
aye! i like that one steve
hello, im a beginner with coding, and i need help on how to make a popable balloon when it gets shot at with basically anything with hands, guns , axes
what is the issue , what did you try
im trying to ask for a code because i cant code
no one is gonna code it for you
chagpt?
start with the !learn pathways they will guide you through how to code components in unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
easy to apply what you learn here
you will be using functions you need like, OnCollision or OnTrigger etc..
using UnityEngine;
public class Balloon : MonoBehaviour
{
public GameObject popEffect; // Assign a particle effect for the pop
public AudioClip popSound; // Assign a sound effect for the pop
public float damageThreshold = 0.1f; // Minimum force to pop the balloon
private void OnCollisionEnter(Collision collision)
{
// Check the collision force
if (collision.relativeVelocity.magnitude > damageThreshold)
{
PopBalloon();
}
}
private void PopBalloon()
{
// Play the pop effect
if (popEffect != null)
{
Instantiate(popEffect, transform.position, Quaternion.identity);
}
// Play the sound effect
if (popSound != null)
{
AudioSource.PlayClipAtPoint(popSound, transform.position);
}
// Destroy the balloon
Destroy(gameObject);
}
}
I'm not dealing with AI code, no.
yeah this is ai code.
for lazy people
learn how to actually do things by using logic
managed to make vr run so
or play roblox
i did use to work on roblox studio i know a little there
but i like unity more
its more simple
no shite I can tell
😳
tutorials?
well structured courses
i sent you Unity specific ones
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Valem Tutorials?
you know that guy?
anyways im gonna learn the basic scripting skills then coming back here
its not about copying what tutorial does, you have to learn the building blocks
after you learn the basics, you can watch whatever ttutorials you want
this way you don't just blindly follow, you just lookup specific thing and walk away
recognize where they do wrong and improve
everyones in too much of a rush, the concept of spending years learning the craft of dev fills them with horror
yeah next generation will be the instant download scripts to brain chips
i miss the times before 2022 when people used to ask normal unity questions . now you only get questions asked that ai cant solve for them
i really noticed this after all
trouble is the chip will be instead of the brain rather than as well as
yeah, you would have hoped that anyone wanting to be a dev would have done their due dilligence, but, nah
I think the ones who are out there actually learning anything substantial aren't running on discord asking such questions in the first place
'me play game, me make game', like bro
hmm looks like Unity essentials was updated to have a programming section now?
https://learn.unity.com/mission/mission-4-programming-essentials?uv=6&pathwayId=664b6225edbc2a01973f4f19
In this Mission, you’ll program a simple interactive experience where you control a character in a living room scene and move around to collect objects. You'll be able to choose from a variety of characters and collectible objects. In our example, we'll use a robot vacuum that maneuvers to pick up dirt around the room.
and its proper rigidbody code!
wow
Note: Don’t worry if your IDE doesn’t look identical to the one shown in the demo videos.
If the script doesn’t open in an IDE, follow these instructions to install Visual Studio, relaunch Unity, and try opening the script again.
👏 wow unity
Hello, anyone can help me?
Not if you don't ask an actual question 
actually he already asked a question
actually not an actual question though
don't ask to ask , just ask
So, apparently i'm running into my first ever memory leak
I'm gonna try to put this in the most composed way i can:
what the fuck??
But no seriously what do i do from here? how do i debug this? this doesn't happen after any one action, just as soon as i play in editor
the Debug -diag-temp-memory-leak thing- does that mean i have to build the app?
Unless you are creating NativeArrays or using some low level API that uses native allocations, it is likely a bug in Unity. Probably harmless, just annoying.
Did this start happening recently? Did you add any new packages to the project or start using any new features?
When I try to define a gameObject, it works, but when I instantiate it, the clone becomes the gameObject the script is using to clone items. As it is a collectible, once it is collected, the variable will then become missing, breaking my game. Can anyone help me? Here is the script
I fucked up and tried setting a gameObject reference to null
I realized as soon as i did that that the game was freezing for a good three seconds every time i did that, and then the memory leaks would come in
So i erased that line of code
but it still keeps happening
Setting a reference to null wouldn't do that
why are you assigning "clock prefab" froma clone you instantiate
Then you shouldn't replace the reference to the original clock object with the instantiated one.
Alright, i restarted unity and it stopped, cool
where am I doing that?
clock = Instantiate(clock ...
it would make more sense to distinguish
var clockClone = Instantiate(clock ...
thank you, I never noticed that somehow
is clock here supposed to be a prefab or an object in the scene?
prefab
clockPrefab make things very clear when you name variables
what's with the assignment in Start then
oh ya wtf going on there
Honestly, I was trying anything I could think of, and I just had one offscreen
you don't need that line at all
just assign the prefab of clock from the project folder (prefab) into the inspector slot
Can AddForce (Specifically ForceMode.Impulse) cause my player object to go trough walls?
if its fast enough sure
esp with discrete collision mode
Ok thanks (its continous), for some reason my player character suddenly stopped being stopped by walls, I will test more.
Hello, I am trying to make a 2d game similar to Sonic the Hedgehog and I want my player to turn into a ball when they jump and when they're in ball mode they can bounce on enemies but if they aren't a ball they will get hurt. I am just having difficulties making the player turn into a ball and then back to normal once they hit the ground
Did you add some component to it?
Or just show us the inspector of all its components
One sec
This is the wall that is being phased trough.
whats the problem ? what do you have so far ?
sounds like you can use a simple State tracking variable
even a simple boolean can track that state tbh. less "clean" but does the deed
Wait I posted the wrong thing
Oh i meant the player, but showing that is good too. So is the wall supposed to be moved?
wall also has rigidbody ?
I needed it for... reasons, I hope thats not the problem?
Some context would be nice. All i see is a wall that can move in the Y axis only, and a player that can move in the X axis only
When you say "wall" most people expect a static wall, not a moving one
So far I just have the movement and jump but I'm not really sure how to make it so the player turns into a ball
not always but moving body + moving body could be tricky if speed fast enough
Alright, so, its a game about an umbrella constantly falling (to do that, everything around umbrella is moving up), its constantly (procedurally) generated and has worked fine, but when I added a tilemap, it stopped working, I removed it, and it still doesnt work. The player can move along the X axis (for now) using Forcemode.Impulse. I might've missed something but pretty much everything is here.
maybe you can make the wall kinematic and use .MovePosition ? could help simulate impact better?
Hello, can someone please help me? Im at programming for a year and a half now, but actually i dont know that much about rb and stuff like that. I want to make a Dash-attack for my enemys, but i dont know how to make that really because in my enemy script the whole movement is based on transforms and moveTowards and i dont really know how i can add that attack
the goal is just to dash in the direction of the player
I could try that.
you should use a rigidbody if you plan on colliding with walls especially making an easy dash
If you are gonna use a RB, all of the movement should be done with RB, not transform
okay
If you go with transform, you'll need to do your own collision detection
sounds like it should from describing your game if level moves , should be better with being kinematic rb and use rb.movePosition
You could use a simple state machine so that when you are dashing it will ignore your other movement code
That fixed it...the Kinematic thing actually worked, thanks, I will keep testing to see if there are bugs
okay
Im using Transform to move it, which so far worked fine
yeah but movePosition will yield better result esp with kinematic
otherwise you're forcing the rigidbody to catchup to transform
instead of rigidbody driving the transform (proper way)
Using transform was the cause of phasing thru walls
Not using two dynamic rigidbodies
https://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html
its literally made for kinematic ^
Ok fair, so every object with a rigidbody (that isnt using Force) should use movePosition? (since At the moment, all the other objects that are supposed to follow the walls are also using transform)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Setting velocity is also an option
nah if its a moving level/platform/wall use kinematic / movepositionn
Which works for 2d kinematic objects
so the thing is i used this tutorial https://youtu.be/tH57EInEb58?si=v-dVZ5NEoOzRtm_F to make this dash. And the only problem i have is with the part with "rb.velocity =..." because i dont know what i have to attach to that to get it that its moving to the players direction
In this video I'll show you a quick and simple way to give your player a nice dashing ability! This tutorial is an extension from my previous 1 minute tutorial, where I show you how to create simple top down movement, you can find it here: https://www.youtube.com/watch?v=tFblCEFQoTs
if there are any tutorials you'd like to see, feel free to lea...
the rest is working i guess
You'd use the same direction that you use for moving your character somewhere else in your code
I've never really done something like this before. I guess once I figure out how to transform the player into a ball the rest should come a bit easier to me
What collider does your player have?
those are just visuals, you want to track the "state" your player is in logic/code first.
eg
bool isPlayerBall
the thing is that there i did it with the float of the keys w/a/s/d and i cant use that for the enemy because it´s not controlled with keys
Ok what direction do you want to dash in?
in the direction of the player
Maybe just show your !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
a box collider
okay
for using a simple state tracking
public enum PlayerMode { Normal, Ball}
playerMode = PlayerMode.Normal
then you can figure out if you get hurt or not when OnCollision. But simple bool can also work ofc.
I don't recommend using a box collider for a character especially in 3D. It has hard edges which can feel unpleasant
A capsule collider is the common way to go. Then you can adjust the capsule collider's height to transform it into a sphere when you go into the "ball" mode
https://hastebin.skyra.pw/efajobocub.csharp the rush code is in l.414-426 and l.493-506 and the rb.velocity thing should be in l.389 then
That could just be transform.right or transform.up depending on your player's orientation
in rb.velocity i have to use a vector to adjust it
did you not look to see what transform.right and .up are?
that is why google and docs exist
you are right
it's vector stuff
more likely shorthands for vectors i´d say
brilliant synoposis, you should get a job writing technical documentation
ik
perhaps learn about sarcasm first
perhaps womp womp
is there a way to prevent or reduce that jumping my player does when I turn my weapon?
Provide a counterforce that cancels out the one from doing that
Or make the weapon and arms 0 mass
will try that
Are you using joints? If yes, see Mass scale and Connected mass scale
that worked
what did you mean by connected mass scale?
is it something you can see n debug mode?
Oh sorry, I forgot that it's not a thing in 2D joints, only 3D
Thanks guys for being here to help, I really appreciate it
I try to follow this tutorial https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-charactersetup.md - but nothing I put into the subscene is rendered when I run my game. Any hints? (Using Unity 6 LTS, SRP Universal 3d Core)
Google came through.. I was missing "Entities Graphics" (tutorial says to install, but not for what and why)
This package is for Entities. If you're not using ECS it's not a good fit for you
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOopo-8G3qZ7SaTaQNcRLpR0PnuO2z22RtfHOS5O8ypReuyogaNg2
This is the one made for the standard setup
Looks like SRP (=URP) = not supported by what you linked. and SRP is the new default in unity 6. at least the launcher seems to suggest that when creating a new project.
just run the converter BiRP to URP
the visuals/rendering wouldn't affect how this asset functions.
converter is part of URP package
i use the kinematic controller package as well, it doesn't matter what render pipeline you use, it probably is just relying on one for its example scenes
fwiw that package is extremely good i highly recommend it
If you did actually want to use the Entities character controller then yes, you must use an SRP with Entities Graphics
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you have to save first
A tool for sharing your source code with the world!
also put a speeed/force multiplier, make sure you have enough power pushing this rigidbody and its mass
I have this function in my class. Problem being that I am comparing other to the two colliders the class has, both for different purposes. This code won't work, as it checks if the collider of the object collided with is one of the variables. I need to check if the collider that caused the collision on the missile's end is one of the variables. Is there a way to do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You're not calling OnMove anywhere
thats the new Input system Messages mode i believe
Do messages work on private functions? Maybe they do
yea
Either way, do some debugging
i just do what this guide telling me https://learn.unity.com/tutorial/66f2d394edbc2a011dded49a?uv=6&projectId=5f158f1bedbc2a0020e51f0d#66f2d394edbc2a011dded4a5
step 7. atm
^ put some logs in OnMove as well
type logs into it?
Debug.Log
Detestable 😛
its quick and easy tho lol
like so? void OnMove(InputValue movementValue)Debug.Log
just put it anywhere inside the method see if its being called
do you have a Player Input component on your player and this script on that ?
Completely opaque and fragile in ways that's hard to notice though
yeah the generate c# class method is better / more solid
i just follow the guide
The script should be on the same object
no script?
I can't find anything on this on the internet, and AI just keeps telling me my code is correct when it isn't at all
you do have to put this script on a gameobject for it to do anything
in this case on the same one as Player Input component
probably i dont have to
cause the guide say nothing about that
besides putting it in a scripts folder
okay then I dont't have to
oh okay can you show me how?
the guide the doesnt cover that
MonoBehaviour is a component, in order for a component to do anything in goes on a gameobject
Player input component is complete different from Player Controller
I keep getting a "The object you want to instantiate is null" argumentexception.
// in Start()
prefabTile = (GameObject)Resources.Load("initialPrefabTile"); // no idea if this could be the issue or not
// other code and stuff ...
for (int x = 0; x < objectWidth; x++)
{
for (int y = 0; y < objectHeight; y++)
{
Vector3 position = new Vector3(x * blockSize, y * blockSize, 0);
GameObject tile = Instantiate(prefabTile, position, quaternion.identity);
tile.name = $"tile_{x}_{y}";
}
}
I added some checks and prefabTile != null, and it's definitely fine in the inspector whenever i run the program, so i assume I'm doing something wrong with Instantiate? or something else entirely?
one is for capturing inputs and one is to useing those inputs to do stuff
you keep both
i see, but i shouldnt have the player input comp tho
ou
They you've failed to load the prefabTile
Or you have some other bad assumptions somewhere
@rich adder not working, the get same result
what makes you think that? that is literally whats capturing your keyboard inputs
whats "not working"? show what you tried
How suscribe the event?
+=
The event is must public, right¿
so when i run the playmode, the player controller component is removed, but not the player input
yeah it should be exposed
so that mean i can only keep 1 right?
Why's it removed?
because i go into playmode
And If the event proceed the prefab¿
idk what that means
should i screen record it and send it back to you? vertx?
Sure
The prefab shoot the event, and is a referenced the gameobjects suscribed
whenever the code runs it says that prefabTile is not null, so I'm assuming that means it has loaded the prefab. is it possible that the code that requires the prefab is running before the prefab is loaded..?
please show your current code and explain a bit what you want to do with it. I'm confused here
Ok
using TMPro;
using UnityEngine;
public class UI_Points : MonoBehaviour
{
[SerializeField] Enemy_1 enemy_1;
[SerializeField] TMP_Text pointsUI;
float pointsCurrent;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
enemy_1.UpdateUIPoints += writeUI;
}
void OnDisable()
{
enemy_1.UpdateUIPoints -= writeUI;
}
void writeUI(float points)
{
pointsCurrent += points;
pointsUI.text = pointsCurrent.ToString();
}
}
``` The script the gameobject subscribed to event of prefab
No. Can you link to the complete code?
why are you subscribing to a prefab ?
you would want it from the instance
vertx, it actually work now when i record it :>
ty guys
i readd the player controller
and go to playmode
the comp is not removed
and player is controllable now
How?
if you want this script to listen to ALL enemies event you can also just make the event static and subscribe to the static event rather than a specific enemy
static¿
yeah like public static event
Ok
that way any Enemy class that invokes that event you get notified if subbed
Note that static events are an extremely easy way to create a leak, so you must unsubscribe from them when you're done
ah yeah always do the OnEnable sub, and OnDisable cleanups
I get it, thanks
Of course
If someone knows please ping me
what exactly you want to do, not sure I understand
I'm sort of trying to run the function for every collider on it's own. Do something if this collider hits, something else if the other does, while having access to the object it hit
i would try to simplify the code first... its not a good code design using a lot of nested "if" statements like... if { .... if {.... if {... if { ... try simplifiy it with the things you wont have first... if not xy... return.. then do the 1-2 it should do..
The code is in a test form right now, before cleanup. The problem is I have no idea how to do this
It's the only issue right now I don't know how to resolve
so whats wrong with other ?
But I bet my life it's possible in afairly simple way
You should debug properly with logs or the debugger.
If adding a line of code "fixed" the issue it could be a timing dependent issue. An extra line of code would change the timing of many things in the app. Anyways, without proper debugging it's all just speculation.
My bad, I just need access to the object hit by other
the object is already gameObject or this for the script
I posted an update to this but in the mobile channel bcs it kinda seems to be a .aab specific bug and only one one specific device right now.
2/3 tested phone worked perfectly with the .aab only the A54 of my mother have some issues with the UI toggle like posted here:
#📱┃mobile message
I have tons of scriptableobjects that hold composable data such as CharacterSO for playable characters. What is the best way to access a list of these characters during runtime? Should I create a Datamanager monobehaviour singleton that can access the SO for this info?
gameObject is the missile (missile is the class this function is in), other is the collider that triggered the function. I need the object collided with by the missile.
public List<CharacterSO> allCharacters;```
This is suprisingly difficult to phrase for me
@wintry quarryRight, and where would you put it? SO needs to be instantiated does it not?
can you explain the mechanic , dont explain what you want from code. What is the game part of it
instantiated? No, generally they exist as assets in your Assets folder
You drag and drop them in the inspector
If I have a SO called HealthSO which is shared across all characters in the game, will they share the same health?
HealthSO would be the name of the class
You can make many objects from a class
And name them whatever you'd like
but I don't see a SO as a good way to track the health of an individual character
because then you'd need an instance for each one, and at that point what are you gaining?
SOs are best for immutable shared data reused in many places
Yeah as a reference, because in my CharacterSO I have a "public StatsSO stats" which contains a list of attributes possible for the character. And multiple characters share these attributes. So I mean when I run the game all the characters would need unique instance of these
Yeah I don't see what the benefit of using a ScriptableObject for that purpose is
You might as well use a POCO
The missile flies around. It has a collision collider and a field (or explosion) collider. The field collider causes the missile to prime, storing the objects detected in a list. When the missile stops colliding with these objects, they should be removed from the list. This is used to damage the objects if possible when the missile explodes. Speaking of that, the missile has a lifetime, which counts up every frame (speeds up when primed) up to it's maxLifetime. Once that number is reached, or the collision collider collides with another collider, the missile explodes, dealing damage to the objects the field collider was colliding with at that time.
Here's the missile's code, it should be a bit clearer.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If you have a SO for base stats that's a different thing entirely than "current stats"
Well it is great for the inspector editing
you can edit plain objects in the inspector
Yeah it should be for base stats
e.g.
[Serializable]
public class Stats {
public float hp;
public int strength;
}
public class Character: MonoBehaviour {
public Stats stats
}```
So I guess I should just instantiate a new character using the SO data
then I would do something like this:
public class Character : MonoBehaviour {
public BaseStatsSO baseStats;
public Stats currentStats;
void Awake() {
currentStats = new Stats(baseStats); // copy from the base stats
}
}```
and then you would deal with currentStats from then on out
leaving baseStats to not be modified
so you want all the objects the missles has hit to be destroyed when missle explodes?
Right
No, check if they're a specific class, then do according stuff to them
The problem right now seems to be that the missile won't collide with them
private void OnTriggerEnter2D(Collider2D other) {
if (other == mainCollider) {
if (other.gameObject.TryGetComponent(out LayeredCollidable objectLayeredCollidable)) {
if (objectLayeredCollidable.ship) {
lifetime = maxLifetime;
}
}
}
if (other == explodeAreaCollider) {
if (!zoneObjects.Contains(other.gameObject)) {
zoneObjects.Add(other.gameObject);
}
if (!primed) {
primed = true;
}
}
}```
Now it's a bit cleaner. Still does not work. It appears `other` is the object that was collided with. I need the collider that caused the collision on the missile's end
Like, know if the explodeAreaCollider did it or the mainCollider
Put it this way: I'm not checking if other caused the collision. I'm checking if the missile collided with other
this would be much easier/cleaner if you just used Overlaps/Casts instead of Rigidbody functions
you can have different zones per cast
how do i fix this?I havebeen working on this for 30 minutes and its still not working
You can only use type names and identifiers that exist
Vector is not one of them
Maybe you wanted Vector3 or Vector2?
Or maybe you're using a variable that doesn't exist?
i have writed Vector3 but idk whats wrong with it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
here is my code
Vector.zero is likely where your problem is
but you are trying to write code with an IDE that is NOT configured
you need to configure it before you do anything else
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i dont understand
which part?
How do I get a unity script to say a variable value in the console?
the whole thing
Debug.Log();
Debug.Log
also 
I tried, and it said Debug.LogFormat and I don't quite understand that but its alr
i dont understand any part
idk was first result for me
you need to fix your visual studio so it shows you errors before you continue to write code. Follow the instructions in the linnk I shared above.
Debug.Log($"My variable's value is {myVariable}");```
Or:
Debug.LogFormat("My variable's value is {0}", myVariable);```
or ```cs
Debug.Log("My variable's value is " + myVariable);```
any of these work
hey, i'm using a toggle button and i see there's a "on value changed" option- is there a "on value set false" of something of the sort?
use OnValueChanged and check if it's false in your code
just check the bool on value changed
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Toggle-onValueChanged.html
the toggle it returns you check the isOn property
if (!newValue)...```
I think this would work, but I am trying to get it to spit out the currentVelocity of my character. (I'm using a kinematic character controller tutorial I found on the internet btw). All it's coming up with though is just UnityEngine.Debug:Log (object)
The current velocity for some cusom movement script can only be gleaned from the code of that script
You're just printing some random object out
you need to print the velocity
not a random script or object
Show your code if you want more help
this damn audio adjustment just won't do anything. like it apparently won't save my audio settings in player prefs as it keeps being stuck at 0% volume when i load the game and it won't even adjust the volume when i play around with the sliders and i just feel so lost i have no clue how to fix this
https://pastebin.com/HnmEUEfc
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Start using Debug.Log to see what's going on (sorry misread)
I could do that, but it was a pretty big tutorial with a lot of moving parts that I pretty much just copy pasted. The reason why I want to find out the values of these variables is because I'm new to coding (just in C#) and I don't really understand what values the variables actually are and how adding them together creates the player movement that I'm seeing, so I'm trying to see what the variables are actually doing.
it was a pretty big tutorial with a lot of moving parts that I pretty much just copy pasted.
Then you wasted your time with it
the point of tutorials is to learn how things work
not to just get a thing working
Okay tutorial isn't the right word
I recommend doing the tutorial again and taking it slow and making sure you understand each part
I just copied this movement script for a character, and I'm trying to kind of learn it myself
through finding out what the variables actually are
You won't learn by blindly copying. Anyway it's not clear what your actual question is then
If you won't share your code we can't help you figure out how to get the velocity
hold up one sec
`if (_requestedJump)
{
_requestedJump = false;
motor.ForceUnground(time: 0f);
//Add Jumpforce
var currentVerticalSpeed = Vector3.Dot(currentVelocity, motor.CharacterUp);
var targetVerticalSpeed = Mathf.Max(currentVerticalSpeed, jumpSpeed);
//Add the diffrence in current and target vertical speed to the character's velocity
currentVelocity += motor.CharacterUp * (targetVerticalSpeed - currentVerticalSpeed);
}`
It uses a KinematicCharacterMotor addon type of thing
This is not a script
this is a random several lines of code
doesn't tell us much
Anyway if you want to print the curreent velocity you'll need a variable that holds it
if there is no such variable, you'd have to create and update one
there's something here called currentVelocity which sounds promising, but based on this code snippet it's possibly only holding vertical velocity
Is there a way for me to paste over the entire script without flooding the chat?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Alright here is one of the scripts
https://paste.mod.gg/gqkgjxjqkimm/0
A tool for sharing your source code with the world!
lmk if that works
Ok so yeah pretty clearly currentVelocity is the velocity
this is using the KCC asset from the asset store
https://www.youtube.com/watch?v=NsSk58un8E0
Here is the original video btw
This one is a bit different than the last couple devlogs. I thought it would be fun to share a longer video where I actually make a thing. Might be super boring? Idk!
Links:
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
https://youtu.be/7daTGyVZ60I
https://youtu.be/tYc1yUt0IeA
https://github.com/TheAllenChou...
Not necessary
Lets just say that I want to get the currentVelocity pasted in the console whenever the (_requestedJump) thing is called, how would I go about that?
so like the volume adjustments should be made by setting up the volume sliders in my pause menu with some functions in the pause menu's script, and then when the value of said sliders change they should change the volume. idk i suspect there might be something up with that because i put in debug logs into my code and they said the value that got saved in playerprefs was just 0. problem is, not really sure what to put in the onvaluechange thing's parameter for the sliders here (for reference, below is the function that this particular slider in the image refers to)
public void SetSFXVolume(float volume) { sfxMix.SetFloat("SFXVolume", Mathf.Log10(volume) * 20); PlayerPrefs.SetFloat(sfxVolumeKey, volume); PlayerPrefs.Save(); Debug.Log("Volume settings saved: " + PlayerPrefs.GetFloat(sfxVolumeKey)); }
I had to download KCC to remember how it's structured but:
motor.GetState().BaseVelocity```
if I put that in like this Debug.Log(motor.GetState().BaseVelocity); it still just returns (object)
Oh wait
or you are looking at the wrong log
lmao I am an idiot it is at the top lol
Thanks bro
appreciate it
hold up
I was looking where it said UnityEngine.Debug:Log (object)
not directly above it
thats why
say I wanted it to just spit out the first, second or third value or a combination of them, how would I do that?
- or use $
.x .y .z
just... type what you want to print
it will print it
this is just a Vector3
you can do with it what you want
Yeah man I'm really new lol sorry
I'm probably messing with coding scripts that are way out of my realm of understanding
Well KCC is a little complex for a bare beginner yes
but just simple manipulation of vectors and Debug.Log are very simple
If I want to show two variables in one Debug.Log, how do I separate them? I've tried commas and I've tried adding a + sign, but that just actually adds them together.
I really recommend string interpolation to make this easy:
Debug.Log($"The two values are {variable1} and {variable2}");```
Hey guys! Idk what happened, but my collider isnt working at all. I tried connecting 2 scripts to 2 new objects, none of them work. Its not the scripts, its something with the collider because even a sound doesnt play on collisions, I tested it with a simple script
does Input.GetKeyDown(KeyCode.Letters) work on Bluestacks (any other android emulator) on android builds?
do your android devices have keyboards?
my collider isnt working at all
You mean the objects aren't physically colliding, or your callback just isn't running?
then no
They collide, but the scripts dont work
show how you set it up
you must have messed something up
Show us:
- The inspectors of the two objects
- the code (and explain which object it's on)
https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings#-and--operators
btw this is explains how it all works, but yeah the best method is string interpolation since its clean and legible
I add component to this cube and I add this script
Thanks bro I appreciate it 👍
public class TestScript : MonoBehaviour
{
public AudioClip collisionSound;
private void OnCollisionEnter(Collision collision)
{
AudioSource.PlayClipAtPoint(collisionSound, transform.position);
}
}
I use gpt plz dont hunt me down
Okay then I asign the sound
And nothing works
🤷
you didnt show inspectors
My bad, here
what about other object
Lets just test this one, I meant I tried it on 2 objects
you need two objects for OnCollision to work
where is the other one
Ohhhh The capsule!
OnCollision does not work with CC (Character Controller)
Trigger works but if you need it to be solid use https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController.OnControllerColliderHit.html
I have other colliders that it worked perfectly with
But I just realised for some reason the capsule is not colliding with the cube
the collision works fine, its the event that doesnt get called
OnCollisionEnter wants Rigidbody
thats why OnControllerColliderHit for CC
its the next closest thing
So I shoudl add a RigidBody to the player?
no..
use the other method, which goes on CC gameobject itself then call the method you want based on tag / component check of what you hit
Okay let me check, Thank you!
void OnControllerColliderHit(ControllerColliderHit hit)
{
//e component
if(hit.collider.TryGetComponent(out SomeComponent c))
{
c.DoSomething();
}
//e tag
if (hit.collider.CompareTag("SomeTag"))
{
DoSomethingElse();
}
}```
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Animations : MonoBehaviour
{
private Animator animator;
private Rigidbody rb;
private Vector2 moveInput; // Stores movement input
public void Start()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
}
// Input System callback for movement
public void OnMove(InputAction.CallbackContext context)
{
moveInput = context.ReadValue<Vector2>();
Debug.Log("OnMove called with input: " + moveInput); // Debug for testing
}
public void Update()
{
// Convert moveInput to a Vector3 for 3D movement
Vector3 movement = new Vector3(moveInput.x, 0, moveInput.y);
// Set "isWalking" based on movement magnitude
animator.SetBool("isWalking", movement.magnitude > 0);
Debug.Log("Update Move Input: " + moveInput + ", isWalking: " + (movement.magnitude > 0));
}
}```
Does anyone know how to fix the bug for Unity never finding the OnMove function?
did you put this script on a gameobject
did you add Player Input component on the same object with Move action in action scheme
What do you mean by "never finding the OnMove function"
in what way should it "find" it?
If you're using PlayerInput in "Send Messages" mode, you don't have the correct method signature there
Yeah all the scripts and input schemes are on the same object
What mode is your PlayerInput set to?
ah yeah if its messages mode you need InputValue
If it's on Send Messages you need an InputValue param not CallbackContext
if it's on Unity Events you have to manually assign the function
If you don't have a PlayerInput component, you need more than this to handle the input.
You mean the action type?
no
I mean the PlayerInput component
Do you have one on the same GameObject as this script or not
You said:
all the scripts and input schemes are on the same object
But it's not clear what an "input scheme" is
screenshot us the gameobject with PlayerInput component 😅
That new unity input system. I'm not sure what the name is ngl
will do
Huh?
Is this a complete sentence?
it's a simple question
do you have a PlayerInput component on the object or not?
If not, then it's not going to magically work without one (properly configured) or without other code to hook your function up to the input asset
Ok and like I said it's on Send Messages mode
which won't work with your code
Refer back here
yeah you got wrong signature there
I'll try that out. Thanks
Signature means the same thing Praetor was talking about right?
Just to check
THe method signature is the return type and the list of parameters
yes its parameter types certain method expects, if any
Oh OK. Thanks
Running across a bizzare bug that makes my event system stop working. I have a single eventSystem on dont destroy on load and after reloading a certain scene the event system just stops working. Buttons dont detect mouse presses etc. The only way to fix it is to disable the Event system and re-enable it on the heirarchy (or in code). Has anyone come across this before?
which input module is it? New input system?
yeah the input system
Are you using the default actions asset for it? Or a custom one?
A custom one
I think one possibility is your actions asset is being disabled somehow
Is there a good reason you need a custom one for the input module?
Most of the time I've found that the default asset works just fine for it.
you know what that might be it.. I will investigate
yep I'll probably just use default if this persists
thanks dude
You were right..! Switching actions maps was causing it to break. Super appreciated ❤️
How do I hide a panel/menu? I'm trying to make a main menu with a menu that loads on start, a difficulty selector that loads when you hit Play, and an audio button that lets you adjust the volume, but I don't know how to hide panels with button presses
Deactivate the GameObject
Thank you
its weird to use awake/start inside interface right?
can you clarify? an interface doesn't have Awake or Start . . .
Defining awake or start in the interface is not inherently weird. You can guarantee that these methods are implemented by doing so.
But, yeah, I wouldn't do it.
These methods are supposed to be optional by design.
you may as well make interfaces for all the UnityEvents: IAwake, IStart, IUpdate, IFixedUpdate, ILateUpdate, etc . . .
I think I actually did this for something . . .
It won't do anything unless you're making your own system that uses them manually
Rather than it being weird, I'd say that the purpose behind is weird. Whatever it is. Or it's the wrong means to achieving that purpose.
Hey, what does this mean?
Seems like a random editor bug. Does it cause any issues? Does it reappear if you clear the console?
It randomly happens, comes on every once in a while. Just wondering, thank you!
There's not much info. I can only guess it has something to do with prefab serialization or ui bindings from the error message.
How do I install this? https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.2/manual/index.html Nuget for unity can't find it
In the package manager
I tried searching the registry but nothing came up
It could be in preview and hidden in the normal list. In which case, you'll need to add it via a url.
But I'd check thoroughly in the package manager. Check the different categories.
I installed it by name "com.unity.nuget.newtonsoft-json"
hello guys im having a problem with my enemy animation.. done everything correctly in the animation/animator windows but now my code doesnt seem to work... please could you give me ahand?
Share the !code correctly and explain the issue in details.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so the challengerController is there i shared it, so what happens is the enemy is roaming, and the direction is going is picking the sprite for the respective direction but its only the IDLE one... so when is moving is facing the right diorection but not animating... ive done all the 4 animations in the blend tree plus the transitions and all but i think my code is what seems to be wrong .... what do you mean by share the code correctly?
Share the code correctly. Read the bot message above.
I have the weirdest bug. I can't update my label text, despite it doesn't complain about being null:
var characterNameLabel = characterInfoContainer.Q<Label>("character-name");
Debug.Log($"characterNameLabel is null: {characterNameLabel == null}"); // False
Debug.Log($"Character name: {character.Name}"); // Has value
characterNameLabel.text = character.Name; // Doesn't work
This is called inside a function I run on buttonpress.
Follow the large code blocks section.
but im guessing thats the bit of code that handles the animation
private IEnumerator MoveToTarget()
{
if (!isMoving)
{
isMoving = true;
Vector2 moveDirection = targetPosition - (Vector2)transform.position;
// If moving, update direction
if (moveDirection != Vector2.zero)
{
animator.SetFloat("moveX", moveDirection.x);
animator.SetFloat("moveY", moveDirection.y);
}
animator.SetBool("isMoving", isMoving);
while ((Vector2)transform.position != targetPosition)
{
transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
yield return null;
}
}
isMoving = false;
// Stop movement but KEEP last direction
animator.SetBool("isMoving", false);
}```
Add logs to see if the code executes the way you expect it to execute during the issue.
Sharing more could would be helpful. The whole script for example.
ive done... its showng the proper directions right i removed them ... when its picking a direction is either 0,-1 or 1,0 etc..
A tool for sharing your source code with the world!
Share the code with the logs. It's important for us to know what debugging you've done so far and what results you got.
Also, that website nukes the code on my phone when I'm trying to scroll down, so it would help if you use a different website.
Nvm. Managed to view it in different mode.
You should add logs when setting the animator parameters. You can also open the animator tab at runtime with the animated object selected to see it's parameters in real time. As well as what state it's in.
A tool for sharing your source code with the world!
i added some comments there hopefully it helps
@teal viperThere isn't much more. I think I am running into some kind of redraw problem. That the UI doesn't update.
private void ShowCharacterInfo(Character character)
{
var characterInfo = _characterInfoTemplate.Instantiate();
var characterInfoContainer = characterInfo.Q<VisualElement>("character-info-container");
Debug.Log($"characterNameLabel is null: {characterNameLabel == null}"); // False
Debug.Log($"Character object: {character.Name}, {character.Biography}");
Debug.Log($"labeltext: {characterNameLabel.text}");
characterNameLabel.text = character.Name;
...
When update the label in the inspector it works
Ah wait I fixed it. I think I know what happened kinda. It instantiated a new uxml (which was invisible in the debugger for some reason) instead of using the one that was already there
Comments are not gonna help. Add logs or view the animator tab as I mentioned earlier.
so i was able to make it move .. i open the animator as you told me .. and during the game on i tweaked true and false the transitions and it started working but it was the same before O>o? but now the challenger starts the game already animating
now i added another check when i get component for animator to set the isMoving to false at the start and it worked O.o? really this is messed up haha
It must be an issue with how your state transitions are set up. You probably transitioned into a state where the property being true doesn't change anything. When you set it to false, it transitioned to a different state from which there was a proper transition on when it's true.
Basically, pay attention to your states and transitions and make sure they are working as you expect.
now it is but feels like the program didnt update the animator after i made changes
I was wonder if anyone knew what i am doing wrong as i am trying to connect a script to a game object but it says that the game object i (think ) i connected it too doesnt exist ive checked in unity and it looks good as it is under the game object but im not quite sure what im doing wrong here
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
The tutorial im following if it helps at all
Your !ide is not configured correctly. Follow the config guide:
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Also, avoid sharing photos. Take screenshots instead.
Looks like you’re trying to set the reference in the Start() method. Try doing it right above the green text
Please don't attempt to help people with a misconfigured editor. They should configure it instead of fixing their issue
for some reason when im trying to play my background audio (there are 2 audios) nothing comes out. i have a script where it plays the audio after a certain time limit https://pastebin.com/GVULcgyz
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does your audioSource.Play() gets fired at all. And the coroutine, does this work or what do you mean by your second sentence?
Do you have an audio listener component?
let me see
guys whats the best approach for collision in this situation? i got a 2d top down game snap grid walk, and now im introducing roaming for my enemy .. but as i come near to the enemy with player the enemy doest not collide with player during roaming.... i got rigid body and colliders in both player and enemy... what would be the best approach here?
says this and i dont hear a darn thing
i have two audio sorces
one for a sound effect and one for the music (bad one)
Try setting enemy rigidbody to kinematic. Also try putting all the code for rigidbody in FixedUpdate. Not sure it will help
The code you provided didn’t show a log for coroutine running. Is this from another script?
let em update that
Also your coroutine wont start unless you actually put it somewhere
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
oh shoot
alright then
Looks better
wdym put the coroutine somewhere
let me do a different way rq
In the first code you sent, you only wrote the coroutine method, but never put it in start
What was the solution?
This is a question for #🏃┃animation
but i think its also code related sorry i am new to unity
It's mostly animation, because you need to setup that properly to be able to run multiple animations on different parts - you don't do that with code, delete from here and ask in #🏃┃animation
is there a callback that gets called everytime after you move a gameobject? I have a StickToNearestColliderMethod snap I'd like to automate
I don't believe so. You'd probably have to implement something like that yourself. There's a hasChanged bool on Transform that will get set to true whenever there's any changes to the transform, but that doesn't really sound like it's what you're after.
Does anyone know a tutorial that shows how to create invisible buttons on touchscreen?
id probably just create editor hotkeys
just make a button and put a CanvasGroup then alpha =0
unless you mean something else
No, generally any math-related items (such as Transform/Vector3 in this case) don't have any explicit implementation apart from the direct feature to preserve performance. You should make a method that compares against the last position instead.
However, maybe you should not automate this if you end up checking for gameobjects to move each frame. That's one of the reasons why this doesn't exist as-is
It's better to rely on the build on collission to trigger and handle it from there
public static class GlobalStickToWalls
{
[UnityEditor.MenuItem("Hotkey/Stick Selected GameObject To Wall #s")]
private static void SnapToStickToWalls()
{
foreach(var item in UnityEditor.Selection.gameObjects)
{
var c = item.AddComponent<StickToWalls>();
c.MoveToTouchWalls();
Object.DestroyImmediate(c);
}
}
}```Just did this anyways
you can't use this in a build - if that's what is required
ye, just a hotkey thing to make map designing quicker
the class is still accessible in builds, if everything is fine
UnityEditor namespace can't be included in builds
How to make an object increase x position by 1 when a button is pressed?
var pos = transform.position;
pos.x += 1f;
transform.position = pos;
and the button part is subscribing to the onClick event
or
transform.position = new Vector3(transform.position.x+1, transform.position.y, transform.position.z);
cause it only takes one line
less readable
i presume the 3 property access are optimised but tbh i dont trust mono 🤷♂️
The difference is negligible performance wise, if there even is any
transform.position goes from managed to native code so its not the same
but on non mobile platforms its probably never worth worrying about
wait guys
transform.position += new Vector3(1, 0, 0);
no?
o wait no
need to make it a variable
smh c# kinda ass
or does it just work
am confuse
Can I pm someone to help me
how do we know if we would know the answer before u ask..
i think this is real actually and seems like the best solution
have never thought of that
I need help making a button and moving player when pressed, all the tutorials ar confusing
ur modifying the entire property