#💻┃code-beginner
1 messages · Page 69 of 1
tested creating 2 new project, first project still occur/appear, 2nd aren't
I just thought I had to queue the objects when i returned them to the pool
But I've got nothing controlling that queue lel
If you change to a Release method, it implies a different management strategy. For instance, if you were using a stack (Last-In-First-Out, LIFO) or a list where you want to place objects back at specific positions, Release might be more appropriate. However, this would require significant changes to the pool's logic and might not necessarily offer any benefits over the current queue-based system, depending on your specific use case.```
Use Case: A Player dies, they call an object from the pool. Another player picks that up and the object and returns to the pool, waiting to be used again.
Interesting, didn't know that 
Sucks, I had a core system working before, but now ive expanded its getting convoluted 😦
Well damn. 
fix the compilation error
Double click the red warning down the bottom
It will open your IDe to the problem line
To elaborate, Unity will not update any script changes if your project has any compile errors in it, even if they are unrelated to what you were working on, so youll want to make sure you resolve your other errors first
no issues
the compiler says there is compilation error, or you havent configured your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
how do i do it
im new with unity and stupid
just choose the way how your vs was installed and follow the instructions of the link
installed via unity
so click the link
now regenerate project file and click one of your scripts, the visual studio will be opened
idk how
regenarate
show it
ignore the warning first, double click one of your scripts to see if the vs opened
is your vs underlines line 2 in red in Grab.cs?
blue
show the screenshot btw
it is still not configured...
open the visual studio installer, click the modify button on right hand side, see the unity is clicked
You can probably just right click and Reload these, I think that should fix the issue.
didnt notice that
The recalculate thing you mentioned should have fixed this to be honest
adding a delay fixed both issues somehow lol, thank you very much 🙏
Unless he didn't close the IDE
And that install thing seems weird indeed. Never seen that. Perhaps you are right he still needs more components
so what do i do
Bro u better get back to that eventually. 
where?
the link in !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
which one of those
He also said he installed it via Unity, so that part should have been enabled for him...
Well, just click manually then and read it. What ティナ said is in there.
open the Grab.cs
now
is the ide underlines line 2?
why the file is miscellaneous.... try open c# project in editor
right click in the project window->open c# project
if it still not works, regenerate project file and open c# project again
i dont want to do it
This is what a core workign ver looks like, guess ill just work backwards
I'm not sure what you are trying to say here, this probably has nothing to do with the difference between Enqueue or Release right?
Release is just a wrapper of enqueue
a configured IDE is required on this discord
I was just asking before about deactivation because ive got the exact same code running in my main and its not working
using System.Collections.Generic;
using UnityEngine;
public class PoolManager : MonoBehaviour
{
public GameObject prefabToPool;
public int poolSize = 20;
private Queue<GameObject> pool = new Queue<GameObject>();
void Start()
{
for (int i = 0; i < poolSize; i++)
{
GameObject obj = Instantiate(prefabToPool, this.transform);
obj.SetActive(false); // Initially deactivated
pool.Enqueue(obj);
}
}
public GameObject GetPooledObject()
{
if (pool.Count > 0)
{
var obj = pool.Dequeue();
obj.transform.position = Vector3.zero; // Reset position
obj.transform.rotation = Quaternion.identity; // Reset rotation
// obj.transform.localScale = Vector3.one; // Reset scale if needed
obj.SetActive(true); // Activate the entire prefab
Debug.Log($"Object taken from pool and activated: {obj.name}");
return obj;
}
Debug.Log("No object available in pool.");
return null;
}
public void ReturnObjectToPool(GameObject obj)
{
obj.SetActive(false); // Deactivate before returning to pool
pool.Enqueue(obj);
}
}
Working ver of poolManager
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
InitializePool();
}
private void InitializePool()
{
for (int i = 0; i < poolSize; i++)
{
CreatePooledObject();
}
}
private GameObject CreatePooledObject()
{
GameObject obj = Instantiate(prefabToPool, this.transform);
obj.SetActive(false);
pool.Enqueue(obj);
Debug.Log("Created and added object to pool: " + obj.name);
return obj;
}
public GameObject GetPooledObject()
{
if (pool.Count == 0)
{
Debug.Log("Pool is empty, creating a new object.");
CreatePooledObject(); // Optionally increase the pool size
}
var obj = pool.Dequeue();
ResetObjectState(obj);
obj.SetActive(true);
Debug.Log("Object taken from pool and activated: " + obj.name);
return obj;
}
public void ReturnObjectToPool(GameObject obj)
{
ResetObjectState(obj);
obj.SetActive(false);
pool.Enqueue(obj);
Debug.Log("Object returned to pool and deactivated: " + obj.name);
}
non working
{
// Reset object state as needed
obj.transform.position = Vector3.zero;
obj.transform.rotation = Quaternion.identity;
var rb = obj.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
// Reset any additional components or states here
Debug.Log("Object state reset: " + obj.name);
}
}```
You mean the pool cant return objects?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
pRb.AddForce(-gameObject.transform.right * 5, ForceMode2D.Impulse);
eRb.AddForce(gameObject.transform.right * 9, ForceMode2D.Impulse);
StartCoroutine(Hit());
gameObject.SetActive(false);
if (pScript.facingDown)
{
pScript.bonusJumps += 1;
pRb.velocity = new Vector2(pRb.velocity.x, 10);
eRb.velocity = new Vector2(eRb.velocity.x, -10);
}
}
}
IEnumerator Hit()
{
eScript.isHit = true;
yield return new WaitForSeconds(0.2f);
eScript.isHit = false;
}
this code when ever i hit an enemy i want it to knock back enemy and make isHit true for 0.2 seconds
everything works apart from the ienumerator, i put a debug.log at the start and at the end and it only works at the start not the end
anyone know a fix
!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.
gameObject.SetActive(false);
You disable the gameObject though. 
It wont run the script anymore the next frame.
that is the sword hitbox so theen it does not hit the enemy multiple times
so it should only do it once
wait
nvm you might be right
What is escript? Enemy script?
And i think there are more than one enemy in your game, and you dont know which one you hit, so you should use the argument of ontriggerXxx
you are right
The SetActive(false) call in your CreatePooledObject() method is standard for object pooling. It sets the newly created object to inactive so it can be activated later when needed. This is part of the pooling pattern where objects are created and stored inactive, then activated when they are taken from the pool, and deactivated again before being returned.
So how do i get around that logic then if it deactivates it for the next frame no matter wht action is called next?
I was talking to poo!
Oh sorry
I don't know how to fix your problem. For me pools usually just work.
so what is the problem... i cant get it....
to me it seems that the pool cant return the obj
Well first it was that he couldn't give back to the pool, but now it seems like it doesn't do it for all of them.
is this better than github for a collaborate project with two people in realtime?
pause the game and see if all the active objects on scene
object pool is unordered so the hierarchy tells you nothing about the pool
this is the same as using Gt + Github
there is no "realtime"
as long as the number of objects in pool+number aof objects allocated=initialize amount of object created then it is correct
oh, thank you again :>
Will this just set the "Target" variable" to be the "mousePos" variable?
yes = is for setting values
its gonna copy it
thank you
How can I get a script to read a variable from a component in a game object?
make a reference to that script / component
eg [SerializeField] private Foo foo; var valueFromScript = foo.bar
thank you again
can I do this even if the script I want to get the variable from is attached to a different gameobject than the reading script?
yes exactly , you just drag the component / script from that gameobjectt into the slot created from that code
oh okay
[SerializeField] private or public are serialized in the inspector
(they will show up in the gameobject inspector)
Yep understood
How can I specify for it to get the target value of the Game.Object?
Instead of GameObject, use the type of the component that has the target field
Right okay
Actually no nevermind I do not understand this- could you explain?
What is the name/type of this script?
How should I make a camera rotate system around an obejct with cinemachine, but in a way that it doesnt rotate exactly around the object, but it does a rectangular motion (I want this to be implemented into my housebuilding system, where you can rotate the camera around the rectangular shaped house).
Thanks
Right, the script is Movement Manager, it just tracks the current location of the mouse
Oh I ditched that and will just get the target value in the movement script
So make a serialized field of that type: cs [SerializeField] private MovementManager movementManager;
Then you can access target with movementManager.target
oh okay thank you!
target has to be public to be accessed from other scripts
What does it mean to serialize a field?
Serialize means 'save' pretty much
It also means that unity will show the field in the inspector
okay
Can someone explain or just provide a link to an existing solution please?
Serializing means Unity will convert some class(object) into a readable format of JSON(example). This happens in Scene file too. Likely, if you open a scene file in text editor, you will see how serialization works.
afaik Unity uses Yaml not Json
You can create a predefined path a suppose, making a rectangle should be fairly easy
make 4 corners and connect said corners, make cam only move on said path between points
you might be able to use unity's spline
Thank you for the help
Is it possible to have two different inspectors looking at two different game objects
Yes, you can select one object, then right-click the Inspector tab at the top and select Lock
^^ additionally, you can right click one of the components and click Properties and it will pop out its own inspector
Do you have a link for that spline stuff, or how to create a path to follow with cinemachine?
https://docs.unity3d.com/Packages/com.unity.splines@1.0/manual/getting-started-with-splines.html
pretty sure cinemachine has its own though, maybe try Rig/Dolly
okay
Thank you very much, will try it
I went like 3 years without knowing this at first and I'm still salty about it 😆
Better than fiddling with the locks
same! such a time saver tbh especially when using the Debug part, i used forget to turn it off sometimes on main inspector then wonder why later my inspector was all weird and missing fields lol
the editor will throw if too many of inspector windows are opened when enter play mode iirc
Now i that i think about it, i wonder how crap my editor scripts are. 
why does this not work?
The mouse position it relative to the screen, not your World
yes and?
You need to "translate" it to World coordinates
what is this supposed to do exactly ?
its supposed to make the Movement Target equal the MousePos
wait
if this supposed to be a unit mover I would call the MouseInput method directly from Unit controller not unit itself
unity absolutly LOVES not working
wrong channel
How can I check if the gameobject the script is attached too is the Selected Unit?
Selected Unit variable is not a GameObject, it's a Unit (the script you've shown in this screenshot).
So that would be a if (selectedUnit == this)
thank you
I feel like selectedUnit should be in some sort of manager script instead of a unit
Yeahh
ill do that later
currently just trying to find out movement script
how do I make sure that the objects Z coordinate will remain over -1?
Make a new vector 3 with the z forced at -1.
Make an invisible wall (collider)
If you use rigidbody, pretty sure there's a way to lock the z position.
Yep but they want to limit it to min -1, not lock it entirely
hey i'v been coding in js for the past decade and my C# skills are rusty. im trying to use Visual Studio but not getting any auto completion from the UnityEngine library
so i make silly typo mistakes and need to wait for Unity to compile the script before I can see it
I have the tools installed do why cant my VS read the library?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
btw
and 
are different so make sure you are talking about VS 
that would also work though
and yeah found it
thanks
nevermind
can you use 3d rigid body for a 2d object?
Only if every other object uses 3D colliders & 3D rigidbodies
Because 2D and 3D physics can't interact
Why do you want a 3D rigidbody though?
you can't lock Z coordinate for 2d rigid body
Usually people skip over the step of installing the workloads when installing Visual Studio.
i did the first guide
Sure you can
Edit: wait what, why do you need to lock Z?
Whatever the case is, go through the check list and tell us what you did and did not do.
yeah im was using code for years haha
using webstorm now
But why is it moving in the Z axis in the first place?
is it possible to use code instead and still have complitions?
i prefer it
yes
!vscode
because i made mousePos vector 3 or else it wouldnt work for transform position
Are you teleporting the player to the mouse?
If so, you should use rigidbody2d.MovePosition
fixed it
just made the mousePos vector 2
yez because Z pos
You should still move it with Rigidbody functions if you want to use physics
Perhaps I need to restart the pc to register the path envs of .net
nope ):
still no auto completion
@rich adder
did you follow the IDE guide to the letter?
made a character controller with isGrounded but if you fall off you can jump again. do I use a OnCollisionExit void?
yeah ):
is that vs?
2019 or 2022?
is Unity Extension installed and all ? and did you restart pc
and show external tools page
no, use a proper way to check grounding
Overlap, Cast or Checkbox/sphere
Character Controller component has a built one with .IsGrounded but its not reliable
Oh i'm using Rigidbody
using UnityEngine;
public class CharacterController : MonoBehaviour
{
[SerializeField] Rigidbody rb;
public float movementXZ;
public float movementY;
[SerializeField] bool isGrounded;
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
rb.AddForce(0, 0, movementXZ * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
rb.AddForce(-movementXZ * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.S))
{
rb.AddForce(0, 0, -movementXZ * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
rb.AddForce(movementXZ * Time.deltaTime, 0, 0);
}
if (isGrounded)
{
if (Input.GetKey(KeyCode.Space))
{
rb.AddForce(0, (movementY * 100) * Time.deltaTime, 0);
isGrounded = false;
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "Floor")
{
isGrounded = true;
}
}
}
yes
oh vsc
regardless, point still stands
try hit regen project files.
also you dont need all those checked off lol
Wait that extenstion exists???
lol i got desperate
you restarted PC ? dotnet install usually requires it
ok im not sure what happned but it works now!!!!
Don't check for input in fixed update
Also this code would cause you much pain to work with, it is not extendible
Fixed update is only for physics operations
Checking for input there is not correct and might behave weird
void Update ()
{
transform.RotateAround(player.transform.position, Vector3.up, Time.deltaTime * speed);
}
I am using this to rotate my camera around a player when I press X or C (for left and right). For now I'm just experimenting with rotating it at a constant speed
however this causes my camera to rotate faster and faster as time goes on
as you can see it goes faster and faster gradually
why is it doing this and how do I resolve it?
Do you change the value of speed anywhere?
Show the entire script.
notably, you can completely miss an input if more than one frame passes between each physics update
(i.e. when you're running at more than 50 fps)
I have an empty Player object that's a ragdoll, it has all the body parts properly set up attached to the torso
If I want to make my player move left & right, where do I apply the force?
Do I apply it to the torso so my other body parts automatically follow?
Or is there something I can add to the player object so I can directly move that and it will control all the children?
This is during a fall animation, so it doesn't have to be pretty
you can test it by freezing the torso and dragging it around to see how it behaves, my guess is yes the torso will have the most mass and will dominate
does anyone have an idea on how to create source engine movement & rocket jumping in tf2?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class RotateCamera : MonoBehaviour
{
public GameObject player; // the player object
public float cameraMaxSpeed = 10.0f; // rotation speed
private Vector2 direction;
public InputActionReference rotate;
private Vector3 input;
private float speed = 1; // current rotation speed
void Awake()
{
rotate.action.performed += OnRotate;
}
void OnEnable()
{
rotate.action.Enable();
}
void OnDisable()
{
rotate.action.Disable();
}
public void OnRotate(InputAction.CallbackContext context)
{
direction = context.ReadValue<Vector2>();
if (direction.x < 0)
{
Debug.Log("rotatingL");
}
else
{
Debug.Log("rotatingR");
}
}
void Update ()
{
transform.RotateAround(player.transform.position, Vector3.up, Time.deltaTime * speed);
}
}
the other parts of the code is for eventual rotation using C and X
there seem to be a lot of projects trying to recreate quake movement physics in unity like this one https://github.com/WiggleWizard/quake3-movement-unity3d
hm, nothing here looks problematic to me
does it have similar movement to tf2's rocket jumping mechanic?
I wonder if you're just seeing a weird interaction between your manual movement of the camera and Cinemachine's attempts to move it
Framing Transposer could be trying harder and harder to catch up with where it wants to be
oh that might be it
tf2 is built in Source, souce is built on quake engine, with most of the physics from quake 1 still present, like surfing and rocket jumping, i think its safe to assume it will be almost identical, at least at the base level @fresh roost
to find out, turn off the Body behavior
kk,got it thank you
I would suggest moving a camera target that the camera then chases
if you feel the need to directly move where the camera
do you know of KCC?
nope it still speeds up
nope
oh, hang on
you parented the virtual camera to the main camera
the dog is chasing its own tail
don't do that
wait what that's so cool why does it do that
the main camera is being repositioned to where the virtual camera is
look into KCC, as a base controller on top of which you can build any mechanics you want, but its pretty advanced coding
so the virtual camera winds up getting moved
it's the Kinematic Character Controller
it's pretty neat. I haven't used it to its full potential yet
okay gotcha
It gives you a bunch of hooks so it can ask you things like "is this ground stable?" and "where should I move to?"
It definitely requires more work than just using the CharacterController
KCC gives you full access to all data, whats ahead, all the contact points, everything, so you can modify and make decisions on how it should behave
best thing about it is that it wont get stuck like CC, works in any conditions
the thing is,im making a mobile port of tf2 so alot of movement needs to be simplified
crouch jumping to rocket jump etc will have to be simplified
as in direct port? what does simplified mean in this case?
say in tf2 you have to press alot of stuff just to do a simple jump
how could that even be achieved with 4 fingers on mobile
so, if im going to add rocket jumping
its only going to be look behind
shoot
and yeah
recreated i guess?
right, still use KCC as a base, if you are comfortable with it, because using anything else while on the surface will be simple, will introduce many edge cases
gotcha
landing on a sharp corner after jump, walking into a tight spot, etc
thank u
for the help
rocket jumping works currently its just not 1:1 or close to tf2
how do i make a child inherit only the position of its parent
And not the scale and rotation?
You cannot
You would have to track the rotation and scale of the parent and inversely change them on the child.
That kinda goes against what a parent/child relationship is for though
Easier to just NOT have it be a child, and follow the other object via code
Or have them BOTH be children of a common gameobject that only moves, then change the old parent now siblings scale and rotation
There are these but require some configuration:
https://docs.unity3d.com/Manual/Constraints.html
Assuming you want it not to rotate then you change the rotation of the child to point to another non-rotating element (some hidden gameobject like a singleton/manager)
silly hack but it works
Hi team - Say I have team A of 200 agents attacking a team of 200 agents. Best Approach A) Each agent has it's own event on "I am targetting enemy X", "I am shooting enemy X" "I am melee attacking enemy X"" etc, so everyone subscribes to each others events when they target or attack, and the one that is targetted, attacked, or whatever, knows it and runs appropriate logic to respond
or B) Have ONE global event that they all subscribe to, like Global_I_Attack_Enemy (myID, IDofEnemy, AttackingRangedorMelee, DirectionofAttack, yaddaYadda), and all the units get those events but only act if their ID is the one called
Right, or change state logic they run to Attack
Not sure if 400 agents subscribing to like 400/800 events is the right way, or all subscribe to one event. Not sure the best practice for scalability
B) is interesting for something like an RTS when you're dealing with pathfinding as multiple attacking units may need to communicate with each other
That's exactly it
Think Mount and Blade clone
basically
Is there a best practice for when you can have X agents, each with like 3-4 events that trigger, and you can subscribe/unsubscribe chaotically multiple times in a ten second span?
or is the performance hit so not worth it that I shouldn't worry?
I might be overthinking it
Just my experience with pathfinding and optimizing it is that I'm not updating/recalculating every frame if not needed. Units farther away from combat will only recalculate very other frame, but those closer to combat will be higher priorty on calculating new paths. As far as subscribing to a new unit each time they change target is miniscule.
General idea is to prevent a large amount of calculating (don't have every single unit and unit groups calculate path/subscribe/communicate at once) and to spread it over each update.
VERY good point!
You're right
even if I have say 500 guys killing each other
it won't be every frame
and I'm trying to offset logic anyway by a few frames
so they're not all doing the same thing on the same tic, like raycasts for enemies, etc
My problem though is rendering and that's a whole another issue itself ;)
So yeah, keep is simple, have em each have local events that they subscribe to, etc. I'll use a map in a global script so it's fast to pull the right reference to subscribe to, without using a "getcomponent"
ah yes
rendering
I'll eventually get there. My rendering and physics is killing me, but that's my last step haha
wish I could help you
Thanks man, I appreciate the advice
I've just some shader batching issues which I'll eventually take care of haha
Yeah np
rendering is just mumbojumbo to me lol. I'm primarily a bbackend guy haha
Hm damn. http://theliquidfire.com/2015/06/15/better-than-events/ Good test on events -GC concerns whenever a sub/unsub to an event...
so for lots of sub/unsub, might not be best, but when it's fairly static, then no concerns
Makes sense. Maybe I'll consider using unity events more in the future, haha.
the sample size is quite large for a single update, but yeah perhaps it's just better to couple references in some data struct on each unit instead
how can i invoke a prefab with a random color?
well yeah that's what i mean
Objects don't have a color.
This cube is only visible because it has a Mesh Renderer component, for example
Sprite renderer
Okay, so that'll be easy
The sprite renderer has a tint field
er, a Color field, I should say
this color is overlaid on the sprite to tint it
so, if you change the color field on your sprite renderer, you will change the color of the sprite
I would suggest doing it like this
[SerializeField] SpriteRenderer myPrefab;
public void Whatever() {
var instance = Instantiate(myPrefab);
float hue = Random.value;
instance.color = Color.HSVToRGB(hue, 1, 1);
}
Since myPrefab is a SpriteRenderer, you will only be able to drag a prefab that has a SpriteRenderer on it into the myPrefab field
and when you Instantiate it, you'll get a SpriteRenderer
Color.HSVToRGB creates a Color from a hue, a saturation, and a value
hue is the kind of color; saturation is how strong the color is; value is how bright the color is
so, if you pick a random number between 0 and 1 and use that as the hue, you'll get a random color
using 1 for saturation makes it a vivid color (instead of gray) and using 1 for value makes it a bright color
and then you assign the resulting Color into instance.color, which changes the color of the sprite renderer
IEnumerator FireShakeEvent(GameObject obj, float count)
{
Debug.Log("SHoot");
obj.SetActive(true);
Color color = obj.GetComponent<SpriteRenderer>().color;
int x = 1;
while (x < count + 1)
{
Debug.Log(color);
color.a = UnityEngine.Random.Range(0f, 1f);
obj.GetComponent<SpriteRenderer>().color = color;
x++;
yield return new WaitForSecondsRealtime(Time.fixedDeltaTime);
}
color.a = 0;
obj.GetComponent<SpriteRenderer>().color = color;
//obj.transform.position = new Vector3(-0.45f, -0.15f, 0);
obj.SetActive(false);
}
So I just Changed Color Alpha, but the GameObject keep displaying total black even the color is white
What did I wrong?
you've got a sprite renderer inside of a canvas, which is weird
Does the sprite look correct if you don't run that coroutine?
I'm also unsure about the material you're using
Isn't there a specific sprite shader?
I have no idea why and when this thing added
You've got the Standard shader
well, did you parent this object to a canvas?
If you want to display a sprite with a UI canvas, use an Image
Fen, what does the s and v do in the random color thing
S and V
oh
wait
you explained i think
ok yes ty
wait
in my prefab
i have a cube
that has a sprite renderer
but the prefab doesn't
how do i assign
my prefab to the script
fixed
i just added a sprite to the prefab
but is it possible to make it so it cannot be white?
make a complete sentence before you hit enter, these vertical message are bit much..
cause i made my background white
sorry
maybe i can do it with a switch thing
Is it "okay" to call another method inside OnTriggerEnter2D which is doing a gameobject.transform.localScale?
Or should the gameobject.transform.localScale only be executed inside FixedUpdate?
should be fine for one frame scale
What do you exactly mean by "one frame scale"?
FYI the game object is a moving car if this makes any difference 😄
I do not understand.
Perhaps you've dragged the prefab into the scene, then added a SpriteRenderer to that instance?
This won't affect the prefab.
OnTriggerEnter only happens in one frame , you can't do any type of gradual scale or anything, thats what Update is for.
how can i make the instansiated prefab move -2 and 2 x axis
on spawn, so it like moves back to back
Okay, so as long my game object is transformed in the OnTriggerEnter event it should be fine because it only affects 1 frame
I don't follow. Do you want the individual prefabs to be moving side to side, or do you want to spawn many prefabs in a pattern that goes left and right?
i think i could minus the transform.position.x with 2 and plus 2 but idk how to make it update
side to side
the prefab will need a component on it that changes its position
You can use somthing like https://docs.unity3d.com/ScriptReference/Mathf.PingPong.html to get a value that goes up and down
I have two models in unity i want to have an idol animation. one works fine, and the otehr one jsut doesnt animate even tho both are almost exactly the same jsut different models and i dont know whats wrong, they both also ragdoll when i enable it but one just wont animate
trying to create a shooting system for my topdown shooter but for some reason my bullets are travelling on the y axis instead of the x axis https://gyazo.com/3db400159260684b88ee070eac66f620
this is my code, i dont know whats causing the issue
!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.
the error im getting is "the variable bulletgenerator of playershooting has not been assigned"
where is bulletgenerator in this script ?
are you sure you saved?
That script doesn't use that variable..
changed the variablename to firepoint
Show the actual error
but i do
mate we have to see the pivots for bullet and firepoint
how can i make raycasts not interact with triggers
there is a parameter on it
you want the forward direction not the up direction
what is it
queryTriggerInteraction
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
its an enum
how do you see pivots
click the move tool
put it Local / Pivot mode on scene view
is it a true or false how do i change it
its an enum, your IDE should suggest you which one
i dont have an ide
then you should be coding with a proper IDE
Visual Studio for example
but how would i put it in here RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range, null, true);
ok i managed to do a hacky solution
so configure it
how
manually flipped the firing box
do you have
or 
the blue one
!vscode
still waiting on this
#💻┃code-beginner message
i tried something else
because if this is supposed to be Local Pivot then you're using wrong direction
transform.right is the correct one
ok lemme test that
bullet must also point the same way
check that its in Local
nope, didnt work
changed firePoint.up to firePoint.right
show video of issue
and are you in Local mode? you never said if thats what you've shown
also show bullet pivot in local mode
it doesnt show Query TriggerInteraction
ok
that was to somone else
managed to pivot it 90 degrees and its fully functional now
thanks for your help
What KIERA said was to navarone haha
Can anyone help with this problem... recently i made my game multidevice so it can be played from pc mobile and ps. However to do this i had to switch to the new input system while all my scripts were coded woth the old one. I found on unity how the controler is but does anyone know how is this line translated: Input.GetAxis("Horizontal"); or at least how to make smooth movement using it?
you then didnt configure it properly
I literally told you how, you have to pass is one of the enums..
ok how woyuld i do that in this code becasue i dont know what a enums is ----- RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range);
yeah but is it a true or faslse
RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range, ignore);------------like that
not even close no
just tell me how
You should learn how an enum works
then tell what it s
if this is something you are struggling with you're gonna have even more of a hard time
Its literally in the example man
fucking read it
dude you can make so much easier for both of us just tell me if it is more than one word or just how to do it
has anyone played celeste before?
i dont know what that is
is there a question related to code? this is a code channel
ok np
can you answer my question
yes does anyone know how it's dash mechanic is coded?
is that what i type
if you had your code editor fixed it would literally tell you
you guys are just showing me a picture
how to type it
you should put the basic effort to solve your problem
Just a question... are there any new features for 2D in 2023 Unity version except Visual studio 2022
is it a number or a word
That is how you write an enum. EnumType.value
or a bool
its an enum
what dont you get
public enum Moods { Sleepy, Annoyed, Productive}
public Moods Mood = Moods.Annoyed;
so its just a number
they are enums, named numbers
you could have said that and not have taken 5 mins
You could have looked it up...
you could perhaps lookup the basics of terms being thrown at you
i came here for help
this is part of help, to teach you how to help yourself
It is expected to do some work for yourself. Nav walked you through 99% of it, you only had to do 1%
This is a place of learning, not spoonfeeding
@rotund hull Read up first what enums are https://www.dotnetperls.com/enum Then comeback and read the answers, you'll save everyone time
also had you configured your IDE we probably wouldn't even have to tell you exactly what to put there
It's actually against the rules to help people with an unconfigured IDE, just so you are aware
https://discord.com/channels/489222168727519232/854851968446365696
🤓
Hello, got some weird thing where during the transitions from my idle and walking animation, if I were to stop, it'd wait for the animation to finish then stop even though exit time has been ticked off - any help?
Yeah, caring about others and not rudely demanding help is very nerdy.... 
Some people....
how are you switching transitions ? code? show it.
also which transition has exit time off
thats is how you read it
In regards to the what transitions has exit time, the transitions from idle to walking and walking to idle - I'll send SC now
@celest shoal You should post completely illustrated question in #🏃┃animation
Of course - sorry if this is the wrong location
rb.AddForce(new Vector2(horizontal * 50, 0), ForceMode2D.Impulse);
Why does this also slightly increase my falling speed?
hey guys.. is there a way to change the color of the text of those strings that I show inside the red box?
wdym the color?
think you can add some html/css tags within the strings
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/StyledText.html
Rich text perhaps?
wdym?
managed to do like that ```cs
fireRate.text = "Fire Rate: <color=red>" + _player.fireRate.ToString("F3") + "/s</color>";
vcontainer in 2023 is actual?
Evenin' all, Could someone help me out with this please? I'm thoroughly confused as to why this isn't doing what it's supposed to be doing.
void Update() {
firingPoint.LookAt(playerTarget.transform);
GameObject bullet = GameManager.instance.GetPooledObject("Bullet");
if (bullet != null)
{
bullet.transform.parent = firingPoint;
bullet.transform.localPosition = firingPoint.localPosition;
bullet.transform.localRotation = firingPoint.localRotation;
bullet.SetActive(true);
bullet.transform.parent = null;
}
}
And on the Bullet script (lives on the bullet prefab.....
private void Update()
{
transform.position += bulletSpeed * Time.deltaTime * Vector3.forward;
}
It's a simple bullet firing system, I have a firing point that is always pointing at the the player (works great), but the bullets don't travel along it's forward direction, they just travel in the 'world' forward direction and I'm seriously baffled as to what I'm doing wrong.
you're adding Vector3.forward to the position
you will always move in the world's forward direction
you need to use transform.forward if you want the local forward direction
Where do you usually put UI objects you dont want the camera to see?
I'm not getting it. Can you give an example?
the red thingy in the top, i want to like hide it from camera sometimes, im just using -(5000, 5000) for now.
I cant really close it since it invokes some things when it did
you could move it to a layer that the camera ignores
I think that'll work for an overlay canvas, at least
oh, you could also just use a CanvasGroup
I'm sure I'm making an obvious mistake here but after looking at the same lines of code for hours, obvious things become invisible.
I have a simple water wave effect that moves vertices of a mesh based on some simple sin wave and world coordinate math. This is working correctly but I've created a "runaway" effect where the ocean object's X and Z position continually adds to the position of the vertices. I need the ocean object to follow the player to create the illusion that the ocean is larger than it is (pretty basic stuff) but the ocean mesh shouldn't run away from it's object :p
I'm almost certain the issue is with my wave math on the line commented but I can not for the life of me figure out how the object's position is continually accumulating the vertex position. Thanks in advance for any help.
using System.Collections;
using System.Collections.Generic;
public class Waves : MonoBehaviour
{
public float linearWaveSpeed;
public float linearWaveHeight;
public float linearWaveLength;
public float rippleWaveSpeed;
public float rippleWaveHeight;
public float rippleWaveLength;
public Transform waveOrigin;
Mesh mesh;
MeshCollider physicsMesh;
Vector3[] newVertices;
void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
physicsMesh = GetComponent<MeshCollider>();
newVertices = mesh.vertices;
}
void Update()
{
if (linearWaveLength < 0.01f) linearWaveLength = 0.01f;
if (rippleWaveLength < 0.01f) rippleWaveLength = 0.01f;
for (int i=0; i<newVertices.Length; i++)
{
Vector3 vert = newVertices[i];
Vector3 wPos = gameObject.transform.TransformPoint(vert);
float dist = (vert-waveOrigin.position).magnitude;
newVertices[i] = new Vector3(wPos.x, (Mathf.Sin(Time.time*linearWaveSpeed+wPos.x/linearWaveLength)*linearWaveHeight) + (Mathf.Sin(Time.time*rippleWaveSpeed+dist/rippleWaveLength) * rippleWaveHeight), wPos.z);//Setting vertex height here based on sin waves.
}//here
mesh.SetVertices(newVertices);
mesh.RecalculateBounds();
physicsMesh.sharedMesh = mesh;
}
}```
Beyond getting too involved with the math it seems the world point values you're adding is increasing some values exponentially
at least that's my observation on the clip here
I'm not seeing any accumulation in your code though but reading this stuff on mobile is hard.
Could also just keep it stationary in a sense and transform the waves, while following the player
Ah, that's a good alternative.
Though if I simply add the player's horizontal position to the waves then I won't get the world coordinate waves...?
Oh it works!
Nice workaround. Thanks!
oh, hey im just thinking out loud but nice haha
that's simpler than trying to solve whatever the issue was.
moving the ocean causes ai boats to fall off the end of the world so I'll have to fake their ocean physics somehow :p
Hi, I’m having trouble with a CS102: error with the type CharacterMovement already containing a definition for hSpeed. I really don’t know how to fix this, and I’d love to have some help thank you
You have two definitions for hSpeed
Thank you I’m so sorry I can’t believe I didn’t see that😭
also configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Your !ide doesnt look configured
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
Damnit
Okay thank you!
wtf is happening here
"Screen position out of view frustum (screen pos 403.000000, 319.000000) (Camera rect 0 0 699 542)
UnityEngine.SendMouseEvents:DoSendMouseEvents (int)"
here is my code:
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovementBasic : MonoBehaviour
{
public float speed = 10.0f;
public InputActionReference moveAction;
private Vector2 moveInput;
private Rigidbody rb;
public CinemachineVirtualCamera vcam;
void Awake()
{
rb = GetComponent<Rigidbody>();
moveAction.action.performed += OnMovePerformed;
moveAction.action.canceled += OnMoveCanceled;
}
void OnEnable()
{
moveAction.action.Enable();
}
void OnDisable()
{
moveAction.action.Disable();
}
void OnMovePerformed(InputAction.CallbackContext context)
{
moveInput = context.ReadValue<Vector2>();
}
void OnMoveCanceled(InputAction.CallbackContext context)
{
moveInput = Vector2.zero;
}
void Update()
{
Vector3 moveDirection = new Vector3(moveInput.x, 0, moveInput.y);
moveDirection = vcam.transform.rotation * moveDirection; // Rotate the move direction vector by the camera's rotation
moveDirection.y = 0;
// Set the player's velocity
rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z) * speed;
// If the player is moving, rotate the player to face the direction of movement
if (moveDirection != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.deltaTime);
}
}
}
it looks like the player is just being instantly sent to another realm whenever it touches another object with rigidbody
Yeah it's the way you apply the velocity, especially with the Y component. It's exponential right now.
Given a speed of 10 and an Y velocity of 1.2 when you hit the object, after 3 frames (48 milliseconds at 60 fps) the Y velocity will be equal to 1.2 * 10 * 10 * 10, which is already a lot
Solution is to exclude the Y component when calculating the final vector, by multiplying moveDirection itself with the speed, before applying it to the velocity
How can i make it so that my player moves smoothly on a platform going up and down instead of not being able to jump when going up and constantly falling then hitting the platform when going down
example of what im saying
Platforms are notoriously difficult, since you have 2 different forces being applied (the gravity of the character and their own velocity, as well as the velocity of the platform), this example shows horizontal moving platforms, but the logic may help for your scenario as well: https://blog.devgenius.io/moving-platforms-in-unity-4d7299b2d013
How do I reset the text input field after "inputting" text? i.e. on spacebar resetting the field
I'm having some issues while setting up my IDE, it's not autocompleting code or underlining errors at all, I've been doing solid 3 hours research on the internet on why this might be happening and have done everything on the Microsoft website, any ideas why this is happening? Thanks
keep in mind I'm very new to unity please
void spawnAsteroid()
{
if (spawnRate > 1.4)
{
int whichSprite = Random.Range(0, asteroidPrefabs.Length); // Picks a random normal asteroid sprite.
}
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Instantiate(asteroidPrefabs[whichSprite], new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
}``` How do I do this without getting an error instantiating the prefab?
What's the error?
the name 'whichSprite' does not exist in current context
Instantiate(asteroidPrefabs[whichSprite] // here
Does whichSprite exist in the given context?
int whichSprite = Random.Range(0, asteroidPrefabs.Length); here in the if statement
Stuff inside the if statement only exists inside the if statement unless they existed outside of it.
ohh, so would I make a seperate int outside the if statement then change in the if statement?
IDE isn't configured. !vs (usually folks miss the installation of workloads)
https://pastebin.com/06h63pDJ
Hey I'm having trouble with this script. It is attached to a sphere with a rigidbody and for some reason when I print rb.velocity.magnitude it always returns 0. I made sure the rb reference is the correct one.
If magnitude returns zero that means velocity is at zero
void spawnAsteroid()
{
int whichSprite;
if (spawnRate > 1.4)
{
whichSprite = Random.Range(0, asteroidPrefabs.Length); // Picks a random normal asteroid sprite.
}
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Instantiate(asteroidPrefabs[whichSprite], new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
}``` still gets the same error, it may just be a dumb mistake by me
You can verify this by printing velocity
The object is moving tho
The error is different now
what line of code would i use to wait a certain amount of in game time?
Also it used to work before
oh i didnt realize
I don't know what changed broke it
What happens if spawnRate is less than 1.4? Your variable doesn't get a value. The compiler tells you that by reporting that error
If the object moves with physics but rb says it's velocity is at zero then you're referencing something other than what's moving.
Vector3 velocity = rb.velocity;
print(velocity);
this is printing numbers
Fixed it, just had to add an else to the if statement, thx
Are we to assume this is being print within the same scope/script?
I think?
I just changed print(rb.velocity.mag) for this
I guess I can make use of these numbers for my purposes
Let's say i create a variable for a game object(public GameObject gameobj;), if i do an IF statement like this: if (gameobj), will it detect if the gameobj is active?
you can check with gameobject.activeself
how do i make an object move forward and not stop? nothing else
It should detect if the reference is not null
so it checks if it exists?
Use the appropriate property to check if it's active
it checks if it has a reference but not if it is active
Translate in update
go.activeSelf returns true or false depending on if it active or not
I've already done the stuff on !vs , installed "Game development with Unity" in VS and it still doesn't work, editor version is 2022.3.13f1 and VS version is 17.8.0
did you follow every single step?
installing the workload is not the end of it
Yeah, I've done everything else as well
Show me your External Tools preferences page
close Visual Studio, hit "Regenerate project files", then double-click a script asset in Unity to reopen Visual Studio
Still the same thing unfortunately
Do you currently have any compile errors in Unity?
This would stop new packages from activating.
i have that but it doesnt move my object and its slightly grayed out, but doesnt say their is anything wrong with my code
No, the only script I have is this empty one
how can you pass the class in itself as a generic? I want to get who is calling this function at runtime so I can debug the class causing the issue (some hidden class on the Player gameObject is calling this when it shouldn't)
public static void EnableMouseLook(GameObject source)
{
Debug.Log($"[Enable] Mouse Disabled?: {mouseLookDisabled} from {source.name}!");
}
Are you doing 3d ? Show which object has this script
Console is empty
just look at the stack trace
okay, good
One other thing to do
go to your project root and delete any .csproj files that are present
then regenerate project files again
I had a problem once where everything was doubled up in the .csproj files for...some reason
Just the .csproj files?
o dang, that does that always show the exact order of operations? Like always shows who called what?
Correct.
awesome thanks
how do i add camera borders to unity 3d? there are always 2d solutions
i am not clear what a "camera border" is
restricting the camera from moving past a certain point?
no like restricting the player to go away from the camera view
hm, you could apply a force if the player's screen space position gets too close to the edges
Nothing changed, there was 2 .csproj files, I deleted them, regenerated them and reopened VS
no errors
I don't use VS, so I don't know where you should look for any errors
Does the project appear in VS, in the Solution Explorer tab?
Someone else might be able to help
how do i access those edges?
https://www.youtube.com/watch?v=ailbszpt_AI&t=4s i want to do this but in 3d
In this tutorial I explain how to force your sprite to stay within the screen limitations using just a few lines of code.
SUBSCRIBE: https://bit.ly/2Js78lE
In this video you will learn how to:
- 0:35 - Scene Setup
- 1:05 - Calculate Screen Boundaries
- 1:30 - Create a new C# script
- 2:10 - Calculate Screen Boundaries in World Spa...
somehow
https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html + compare the resulting position to the screen width and height
The difficult part is that we don't have an orthographic camera here
perspective makes it harder to reason about what to do
But I think a decent approximation would be to just shove the player to the camera's right if the player's screen space X position gets near 0
Only the .csproj files, it says "The application is not installed" but I'm not sure what application lol
that sounds relevant!
Thanks for trying to help :)
Right click the first one and select Reload With Dependencies
And that should be all fixed
Debug.Log inside the script make sure it’s running
i just deleted it and re did it and now it works, idk what was wrong but i fixed it, thanks for your time tho.
Careful with how you name things, esp using all caps lol
that was most likely what it was
Always make sure filename matches the class
this look ok for the titles?
Can I put a particle system on top of the word snow?
particle system of snow flakes?
this is a code question
what is a good list type for storing the information of highlighted objects?
for example, you're locking onto multiple targets and want to store their positions and the order of which you've locked onto them
arrays?
do arrays store the current position and the order that they've been added?
you can have an object array which contains all of the objects/targets that are "highlighted". if you have an object array "GameObject[] targets" you could then access their position with: targets["index in array"] .transform.position;
ah i see
so say I wanted the objects in the array to be destroyed in the order that they were added, would that also be possible using this method?
yes. the array index starts at 0 and goes up to however many you have. you could use a for loop to go through each position and destroy it
Ngl, it looks like a logo made from 1980s. Idk if that's deliberate. 🍵
starting from 0 and going up every loop
yes 1980s is best

gotcha, I was planning on using a loop or a coroutine to make an object zip from each object in the array and destroy them as it passes by each one
thats one way. i personally prefer arrays
I think List might fit too. 
yeah arrays are perfect for what I'm trying to do here it seems. I figured I wouldn't be able to use a HashSet because it doesn't store enough information or something
But i'd like to know more how you're going to make the selected items into a set first before i would suggest list or array.
Because with List, you can add 1 item at a time. Arrays are just locked into one size so you normally have to know the count in advance.
You can't change the size of an array.
actually yeah List would be better because I don't know many objects will be added to the array once the player finishes locking on
List on the other hand is secretely an array with some utilities to be able to add stuff and remove stuff.
List<TypeGoesHere>
thanks
i have i just didn't realise they were lists
still pretty bad at programming tbh
btw do I create this list as a variable by itself or do I create it once the locking on has started?
Ah, you'll have to learn generics eventually, i suggest you search up on that later.
Generics basically just templates that allows it to work with different types. You can have a generic class or methods. GetComponent<>() is an example.
List<GameObject> targets = new List<GameObject>();
i use GetComponent all the time but I guess i dont really understand its fundamentals
You can then do targets.Add(The stuf u wanna add);
And also targets.Clear();
i assumed you just tell it to get a component and specify what type you want to get in the brackets
U gotta start somewhere. 
In my experience, I might have re-hauled here and there.
this whole convo reminds me that i need to start using lists, theyre really useful
Generics are important since they're not just for arguments on methods.
class MyClass<T>
{
public T value;
}
You can make generic classes that can hold a generic value.
what is this useful for other than arguments on methods?
Welp, I think any sets are going to need generics.
Look at List<> it kinda has to be a generic to support any kind of type right?
And so the Add method also changes. Since the argument is based on the generic type of the list you're using.
so is getcomponent a generic?
Just the GetComponent<>() one.
Another benefit of generic is you can restrict what you can put in it.
E.g. GetComponent<TComponent>(); where TComponent : Component
Compiler will not let you use int in the generic parameter. Just anything that inherits from Component like Monobehaviour.
Aye, i guess it's not time yet. 
Yeah, one at a time. 
bro just described all of programming
just when you think its starting to make sense, you discover more...

i also started learning shader programming and it just feels like being back to square 0
@static cedar btw, do you perhaps know a couple of things about 9 slices and animations? 👀
look
i want to have a conveyor belt animations
that i can like stretch
or have it be any length
could i use 9 slice to split it up and have the middle part have an animation?
Ah. Idk too much about that yet. But what i do know is that in 9-slice, the corners don't stretch whilst the side stretches only on 1 direction, and the middle section stretches both directions.
So you shouldn't be using 9-slice for the conveyor belt, that will still stretch the sides.
Hey guys, can you tell me how when I clicked a button in one menu it will open another menu? Like this, I clicked inventory button and it will open the inventory menu. I tried to make simple inventory system as I added the inventory script to the player.
It's as easy as activating and deactiving your UI elements
Use buttons and their events to call those methods
The On Click () under Navigation in Inspector?
yeps
Alright. So I use that On Click on the Button, then which one that I should drag to the On Click?
Which ever game object you want
you don't even need to make a script, it can already access the gameobject setactive method
Netcode For Gameobjects and Local same system co-op multiplayer - Is it worth trying to solve both onlien and local play with the same system? Is there a pattern for local co-op as managed network objects?
I put the InventoryMenu and the method are these, so I should chose the SetActive method, right? And after that, what I should do?
try it out
Everything correct but it seems something wrong with my Main Menu and Inventory Menu scripts. No errors showing on the console though
I also looked through youtube about On Click but it seems the fault lies on my Main Menu and Inventory Menu scripts
hello! i was following the unity course but while doing so i came across a problem but idk how to fix it, im basically trying to drag a script i made in an object in the hierarchy then this window pops up 😛
idk what channel to get help i hope this is it -_-
does anybody know how i can make an object rotate around a 2d play by pointing at the mouse
i wanna make like a sword that swings around the player at a fixed distance
please google "how i can make an object rotate around a 2d play by pointing at the mouse unity"
you'll find some resources on that
hey guys, its been a while since i've used unity and i thought it would be nice to relearn it by making a lil Sonic fan game, more of a test/tech demo thing but uh yeah.
question i got here: how do i make it so there is acceleration to the walking, like: goes from the minimum speed to the maximum in a certain amount of time. (pretty much how acceleration works-)
nvm found the exact thing i was trying to do in git hub
hey! I'm making a game with input fields, I'm a starter so I don't really know much, so like I have it if its a string that it needs to be then it shows the gameobject, I aalready have everything but the script isn't really working, the text is equal as the string but it still somehow sees it like not equal (its a string "number")
Here is the script:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public InputField inputField;
public string desiredString = "1";
public GameObject correctObject;
public GameObject incorrectObject;
private void Start()
{
if (correctObject != null)
{
correctObject.SetActive(false);
}
if (incorrectObject != null)
{
incorrectObject.SetActive(false);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
CheckAndShowObjects();
}
}
void CheckAndShowObjects()
{
if (inputField != null && !string.IsNullOrEmpty(inputField.text))
{
if (inputField.text.Equals(desiredString))
{
StartCoroutine(ActivateAndDeactivateWithDelay(correctObject));
Debug.Log("Correct!");
}
else if (!inputField.text.Equals(desiredString))
{
StartCoroutine(ActivateAndDeactivateWithDelay(incorrectObject));
Debug.Log("Incorrect!");
}
}
}
IEnumerator ActivateAndDeactivateWithDelay(GameObject targetObject)
{
if (targetObject != null)
{
targetObject.SetActive(true);
yield return new WaitForSeconds(2.5f);
targetObject.SetActive(false);
}
}
}
please help me with this asap, I tried so many things!
!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;
using System.Collections.Generic;
using UnityEngine;
public class BaseStatModifier : ScriptableObject
{
public iStatsHandler source; //what iStatsHandler created this stat modifier script
public UnitStat.StatType statType;
public UnitStat.IncreaseType increaseType;
public float amount;
public bool extra;
}
Hi, I'm getting an error with the following code(and another script using a BaseStatModifier value). I get a similar error when I create a new so script thats supposed to hold data for similiarly named script.
did you save your script?
yup
are there any other compilation errors, the script looks correct
there;s that, but i think they has to do with layers
my only work around so far is slightly changing the name
.Equals will compare if 2 objects are the exact same, so case sensitivity and symbols like spaces, escape characters, etc matter - try logging both your text and string to make sure they are exactly the same, if so, try using == instead to see if it helps, you could also try logging the length of the input field and string to make sure there is no escape chars in them
doesn't work
https://referencesource.microsoft.com/#mscorlib/system/string.cs,11648d2d83718c5e
== call .Equal in background
Can I ask git related questions here?
Fixed
soemthing in this code keeps freezing Unity and i dont know what
[Header("Fan")]
public bool ActiveFan;
public float floatiness;
private float EndHeight;
public float FloatHeight = 10f;
public void ToggleFan()
{
EndHeight = Player.transform.position.y + FloatHeight;
ActiveFan = !ActiveFan;
if (ActiveFan == true)
{
floatiness = 1.2f;
}
if (ActiveFan == false)
{
floatiness = 0f;
}
}
void Update()
{
if (Player.transform.position.y > EndHeight && ActiveFan == true)
{
while (ActiveFan == true)
{
floatiness = Random.Range(1.15f, 1.2f);
}
}
else if (ActiveFan == true)
{
floatiness = 1.2f;
}
}```
Its the while loop, if ActiveFan is ever true, it will freeze Unity.
thanks that worked

how do i fix this error??
i was following the unity official course and while in the lesson 1.2 in moving the "PlayerController" script, i came a cross an error but pop up window and an error came along too!
this error window
You can't continue until you fix the error
https://www.google.com/search?q="unity"+hostfxr.dll and go through the suggestions
thanks
Sup, ive ran into a pretty weird problem, when i hover over the gallery button the sounds still play even though its inactive, same thing with all the other buttons. However, the sounds do not play when all of the buttons are disabled, do you guys know what the problem could be?
so what is the problem exactly ? the sound keeps playing or ?
yeah, the buttons played sound even though they are inactive
its fixed now though, somehow they all depended on if new game button is active or not
how can i only show an value in the inspector if another value is true
ive seen it done in some packages not sure how to di t
Hey guys, how can i create maps like this? so realistic map with mountains and the stuff like that
i want to create a terrain generator but doesnt work
this isnt a code question
and you need assets
anyone can make this with Enough assets
i have assets but need a script to generate maps
who?
this isn't a hand me script forum
i have a question for a script
this channel is "code-beginner" with description "Ask questions and discuss anything related to beginner coding concepts in Unity"
and?
doesn't mean scripts are handed out
you're expected to do at least some of the work yourself and come here for extra help / stuck
that's why i said how i can do it because i'm not getting anywhere with my own stuff
how can you do what?
generating a map involved MANY different systems
including rule sets
i tried to create a gen but doesnt work
the terrain looks like this, wait i create pic
If you want to make a terrain generator that yields something remotely complex, you're not going to do it in 4 hours
ik i have time i work yesterday like 6 hours but without success
the only thing i get is this like the pic
I'm talking more in the range of weeks-months to achieve a fully auto-generated terrain like in your first screenshot
i tried with ChatGPT but ChatGPT and coding is bullshit
go figure
you have to grasp a firm understanding of mesh / uv manipulation including height map etc
make pong or some shit
this isn't a code beginner thing
i've been working on the game for a long time and have always tried something new and now i'm failing on the terrain
if you're serious start something like here
https://catlikecoding.com/unity/tutorials/procedural-meshes/
you can apply the same knowledge on terrain
Basically you throw a bunch of noise maps at it until it looks like something
pretty much xD
https://www.google.com/search?q=generating+procedual+map+unity+terrain
There are thousands of results. just gotta go through it
I've got a question regarding rigidbodys and their constraints. I've got a grabbable object (cube), and a grabber (my vr controller). I froze the cube's rotation in x and z but it still rotates in all directions. Following is the code responsible for the rotation (it's on the controller/grabber):
protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
{
if (m_grabbedObj == null)
{
return;
}
Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;
if (forceTeleport)
{
grabbedRigidbody.transform.position = grabbablePosition;
grabbedRigidbody.transform.rotation = grabbableRotation;
}
else
{
grabbedRigidbody.MovePosition(grabbablePosition);
grabbedRigidbody.MoveRotation(grabbableRotation); //that's the problem
}
}
I think the constraints of the grabbed object get overwritten by the code part marked with the comment.
Changing the grabbableRotation to
Quaternion grabbableRotation = Quaternion.Euler(0, rot.eulerAngles.y, 0);
solved my problem, but that's a dirty workaround. Is there a way to make the freeze rotation constraints work the way they should?
anyone here worked with Microsoft mesh before?
It rotates because you do so via transform.rotation, which bypasses the rigidbody. Try with grabbedRigidbody.rotation directly, which makes the rigibody process the rotation before applying it to the Transform
I'm trying to setup animations via C# and I get a bunch of errors. Anyone know why?
regen project files maybe
Will try
if you are using assembly definitions that might also be something to look into
Regen didn't help
also tthese errors are from another script
Animator.cs ?
not wise to name classes after Unity components that already exist
Ah
That fixed it. Renamed.
TY
That unfortunately didn't work.
That's the updated code:
protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
{
if (m_grabbedObj == null)
{
return;
}
Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;
if (forceTeleport)
{
grabbedRigidbody.transform.position = grabbablePosition;
grabbedRigidbody.rotation = grabbableRotation;
}
else
{
grabbedRigidbody.MovePosition(grabbablePosition);
grabbedRigidbody.MoveRotation(grabbableRotation);
}
}
It still rotates in all directions
hello, im still new and im not sure what im looking at...
i made a grid that dis places sprites, as you can see there are sprites, they are just small... im confused as to how the ui overlaps with the game camera and why wouldnt i see the sprites in the game view?
The UI doesn't overlap, it's just how Unity renders it in the Scene View
and that's the cube
To focus the canvas, select it in the Hierarchy, move the mouse over to the Scene View and press F to focus it. It'll be huge (because 1 scene unit = 1 canvas pixel)
Resize your UI elements so they fit in that rectangle
the art im using is 16x16 per sprite, so should i increase the zoom of the main camera to see the sprites? is that my issue?
Are these sprites under the UI, or in the world?
world
Shouldn't make a difference anyway, but you might want to change the Pixels Per Unit value in the sprite import settings to make them bigger. That value represents how many pixels should be in a 1×1 square in world space
Like if you need the 16×16 image to fit in a square of 1×1 unit in the world, then set the PPU to 16
awesome, i can see the grid alot more clear now. i made its 16.
should i scale the camera to the ui or something? im not sure why i cant see the things in the game view
Nah camera and UI are separate. Looks like you're spawning them in via code, maybe they're at the same Z position as the camera (or behind), rendering them invisible?
They should be spawned at Z = 0
And the camera below that (default is Z = -10)
jup, it was the camera, it was set to 0, thank you :D
solved it. I added a custom method "ApplyRotationConstraints" with a bunch of if statements, itsn't exactly what I wanted, but good enough for now
[CustomEditor(typeof(Item))]
public class ItemEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Item item = (Item) target;
if (item._stackable)
{
item._maxStack = EditorGUILayout.IntField("Max Stack", item._maxStack);
}
}
}
im trying to make the inspector only show the max stack property when stackable is true but this dosnt show anything wether it is true of false
not sure if this makes a difference but in the IDE
it says both the ItemEditor class and the OnInspectorGUI have 0 references
guys i am making an application that converts speech to text in unity engine, how can i do it ?
how do you put lights in a particle system in 2d because it doesnt let me
wdym lights in a particle? particles are just sprites that are billboarded
in the particle system there is a tab for lights
show me , I haven't messed with it
ok
yeah but if doesnt let me
it is on the right
if its 2D light that might be why
I don't use 2D like that
not really a code question #💻┃unity-talk
ok
but yeah pretty sure its because 2D lights are different component than Light
true
i dont see whats so special about this light slot
just make a prefab with the particle + 2D light
i am finna try that
I want to move a UI object to the Mouse position. Which of these camera conversion methods do I use?
For reference, Vector 0,0 is exactly in the middle of my Canvas and the _child is a direct child of the Canvas
_child.transform.position = Camera.main.ViewportToScreenPoint(Mouse.current.position.value);
None of the conversion methods, mouse position is already in UI space
Assigning the mouse position directly to the RectTransform's position should do the trick
_childRectTransform.position = Mouse.current.position.value;
Unfortunately, this does not work, the position is somewhere in the middle of nowhere
It prints the resolution coords (at the end I was near the center of the canvas)
Okay so like the old Input.MousePosition. Try changing the rect transform's .anchoredPosition instead, as this will respect its current anchoring preset
It is closer, but also out of bounds of the Canvas. I think if the vector 1376,1254 is appromately the center of my resolution, that's the issue right? Because the object would be considered in the center if it is at vector 0,0
That's why I thought I need some kind of conversion
how would i make it so that any tile on a given layer automatically becomes a wall
The coordinates you see in the inspector is local (relative to parent) position, like a regular Transform. Global position is what your logs show, where (0, 0) is bottom-left, and (x, y) is top-right and depends on your screen resolution. Your canvas is a screen-space overlay one, right?
No it's screen-space camera
