#💻┃code-beginner
1 messages · Page 11 of 1
I fixed it
If I delay the function that connects the neighbors by one frame via a coroutine it works.
I think the Physics2D might need a frame to catch up with my transformation of the newly created cells.
This makes it work. >.>
IEnumerator DelayOneFrame()
{
yield return new WaitForEndOfFrame();
ConnectNeighbours();
}
Absolutely 100% do not use colliders for this.
Physics2D.SyncTransforms() will also work
But its so convenient 😢
Graph algorithms are even more convenient
As are array or dictionary lookups
Much faster than physics queries too
Right now I place several rects that are being filled up with cells. Colliders help me prevent overlap with other rects or static cells. You really think I should try to redo this with arrays or dictionaries? :/
with 2d array u can check any combination of tiles a line box sphere custom shape without too much effort does it sound good yet 
Rects in yellow, static cells already there. The rest gets instantiated in first frame.
So redo with array[,] ?
Yes, simple grid lookups would be much better and faster for detecting such overlaps
Or a Dictionary<Vector2Int, Cell>
I dont want to but I guess its good to learn that anyways. 😄
I have a player that moves forward using rigidbody. Is there any way to rotate it say -90 on x in an instant and move towards the new direction without losing speed?
when i did the game of life i just used a tilemap and 2 2d arrays (one for current generation and one for relevant changes) and just changed the colors of tiles on the tilemap to apply the changes. it was incredibly easy to set up
Just manually set the new rotation and new velocity
Can you animate tilemaps 2d so they make a small animation when changing state? (in one cell)
I move with AddForce at the start and dont apply any more force. Should I still set the velocity?
If you want to instantly change it, you should set the velocity
So I should also remove add force and manually adjust the velocity for moving forward as well?
If you want? It's irrelevant to the question at hand
Does directly setting velocity keep the object from interacting with other objects?
I mean can I still see the physics effects?
It doesn't really matter where the initial velocity came from
The only thing AddForce does is change the object's velocity. There's really no difference
you can use animated tiles and just swap them out when necessary 🤷♂️
or you can use tiles that actually spawn gameobjects. you don't even have to use a tilemap though, that's just how i did it because i didn't do anything fancy with mine, i just did it to show i understood the concept
I see okay. Thanks a lot.
I'm making a pixel simulation, should I use a class or a struct to store a pixel's data? would be nice to know why as well.
It Depends™️
do you need references to the data so that you can just pass the reference around and modify that data without needing to pass it back to the object and reassign? or do you need this for the jobs system where managed data isn't allowed? whether you should use a class or struct depends entirely on your actual needs for the data
also note that the questions at the beginning of the paragraph are simply examples and not in any way exhaustive
hello, does anyone know why my code editor isn't like automatically attached to unity whenever i open it? i use microsoft visual studio code 2022, and im a beginner in unity.. yesterday when i was coding on unity, it was all fine, but now the code editor wont show the assets files that are inside of unity, if yk what i meant, and the attach button should've had "attach to unity" already written on it, but it doesn't, it's just "attach".. and there isnt auto complete why is that?
sorry if you don't understand but i am really really bad at explaining things and problems
make sure that it is configured !IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i'm gonna go ahead and guess that the external tools setting in unity got reset
ah yes, that was the problem
thanks lol, is there any way i could prevent it from reseting?
restart the editor and make sure the setting stuck
if it did not then something is preventing unity from writing that setting so you'll need to launch as admin, assign the setting, then launch without admin privs. that has fixed it every time i've seen that issue come up
no need to do that im pretty sure, i restarted the editor and it didn't reset external tools
thanks man, appreciated
oh and also, may i ask if you have any good code editor theme suggestions?
i dont really like the default ones
i use darcula 🤷♂️
this one right?
wait, the one i linked was the vs code one. hold on a sec
I'd like to be able to pass the reference around so I use a class right?
yep
I want to spawn Meteors at a random location outside the gamewindow and add some movement to them so they will pass across the gamewindow. Does anyone a good way to implement this?
this is the one i was referring to https://marketplace.visualstudio.com/items?itemName=FINNSEEFLY.Darcula-Theme-For-Visual-Studio
if you google "unity 2d spawn outside camera bounds" you'll find many examples of how you can do that
Thank you for the tip. Couldn't find the right words to google it (English isn't my primary language).
Hi,
What can you do if the editor think that a class/namespace doenst exist even though it does?
I renamed a class and got an error. Deleted the script and created a new with the correct name. Vs Studio doesnt see
any errors but its like the editor doesnt want to recognize that the class now exists again
can you explain what you mean when you say "the editor doesnt want to recognize that the class now exists"
I get an error CS0246 that says the namespace doesnt exist
im trying to make all game objects in my overworld canvas fade when i click the esc button to pause, but objects like the tiles and player are not
https://gdl.space/uvasoyefec.cs
it seems you are fading a canvas group. your player and tilemap shouldn't be on a canvas so that wouldn't work
This is the error
Assets\Scripts\ResourceGenerator.cs(51,46): error CS0246: The type or namespace name 'BuildingTypeHolder' could not be found (are you missing a using directive or an assembly reference?)
this is my public class:
public class BuildingTypeHolder : MonoBehaviour
{
public BuildingTypeSo buildingType;
}
This is the code:
resourceGeneratorData = GetComponent<BuildingTypeHolder>().buildingType.resourceGeneratorData;
No errors is VS
would moving them under a canvas fix that?
But Unity is handling it as the BuildingTypeHolder doesnt exist
your player and tilemap shouldn't be on a canvas
if you see errors in the unity editor but not visual studio, then your !IDE is likely not configured. but you also aren't showing whether that type you are trying to use is in the same assembly you are trying to use it in or whether it is in a namespace you have imported into the file you are trying to access it in
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
One small question regarding the grid lookup: Since the data is of interest for different classes I am considering making it a ScriptableObject to decouple the data to prevent one master class that keeps track of everything. Can you give me a short opinion what you think of this? And what helps you to decide when to put data in a SO and when to keep it in one bigger class?
Yeah, how would you configure that? What basicly happened is that I removed a class and then added it again in the editor but it still think its gone. Everything is as it was when it was working, its just the refference that somehow has gone missing
instead, i would recommend having a panel or something behind the other canvas elements that is semi transparent that you can fade the alpha on to sort of "fade out" your non-UI objects
Was the second set of code line 51 of the resource generator script?
thank you!
Pretty much the same thing
buildingTypeSo = gameObject.GetComponent<BuildingTypeHolder>().buildingType;
how would you configure that
see the bot message directly below my previous message.
you're also still not showing enough context for the issue to determine exactly what is causing it
Yeah dont really know what else to show. The editor is somehow not aware that the class exists, had similar problems before and reacreating it has worked, dont know why it doesnt now. But thanks for the link, ill try to update the editor
Could be anything. I'm guessing the meta file is not updating.
Yeah, did a hard rebot and recreated the class exactly the same way and now its working
GameObject.Find is okay to use a lot as long as its once per frame and rare right?
just checking
private void Move()
{
_rb.velocity = transform.forward * _moveSpeed*Time.deltaTime;
}
Isnt this code moves player to its local forward?
When player's forward changes it still moves it its previous forward
Delta time should NOT be factored into velocity
Also make sure transform and rb are the same object here
Yes they are the same object
It's best to avoid entirely but no it won't be an issue if used sparingly in a small scene
okay thanks!
https://hatebin.com/unqiypntnv so okay. If i put the move in either updates the rotation on trigger works just fine but the gravity does not work as intended. Character is floaty when jumping. I'm kind of confused here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotator : MonoBehaviour
{
Rigidbody _rb;
Vector3 _leftRotation = new Vector3(0, -90, 0);
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("RotatorLeft"))
{
_rb.MoveRotation(Quaternion.Euler(_leftRotation));
}
}
}
this is how I change its rotation btw if it matters.
MoveRotation is useful to produce a smooth rotation. If you want to "teleport" your object at a new rotation, just set its rotation (Rigidbody.rotation) as someone suggested you
All right thanks.
np
why is it not working
Is it okay to clamp addforce speed so i dont go fast since im using add force in update?
messing with the set velocity did not work all that well for me.
there's like 3 things wrong with this
?
1 - you're trying to modify the x component of a quaternion, which you shouldn't ever be touching really. Quaternions are not euler angles
2 - you're trying to modify a field on a copy of the struct returned by a property. This will do nothing, and the compiler is giving you an error to prevent you from accidentally just doing nothing
3 - you're trying to assign a whole quaternion to a single float
@vocal fable
what
AddForce should only be used in FixedUpdate unless it's a one-off force and you're using FOrceMode.Impulse or VelocityChange
also clamping velocity with AddForce doesn't work all that well since the change in velocity is delayed until the physics simulation runs (which is later)
I put add force in Start since I got no friction. The issue with that is when player enters trigger It rotates but no force is applied to move its new forward.
Do I have to add another impulse on the new forward?
as mentioned before it will be simpler to just modify the velocity directly
AddForce is additive
meaning if you want to cancel out a previous velocity you'd have to add a force cancelling it out and then another force in the nww direction
But when I modify the velocity directly my gravity does not work
much simpler to just set the velocity you want directly
Aren't we talking about a thing you do just one time?
It shouldn't affect gravity since the coide is not running constantly
only at this one particular moment
Setting the velocity prevents me from jumping
only if you're doing it every frame
which again, I didn't think that's what we were doing
We're talking about OnTriggerENnter here. It runs once when you enter the thing
Yeah it is just rotating my player in the desired direciton
yeah, don't you want it to also change the velocity?
if changing the velocity means that player stops previous forward movement and switches to the new forward movement yes
e.g.
if(other.CompareTag("RotatorLeft"))
{
Quaternion rot = Quaternion.Euler(_leftRotation);
_rb.MoveRotation(rot);
_rb.velocity = rb.velocity.magnitude * (rot * Vector3.forward);
}```
though rather than euler angles I would probably just do this:
if(other.CompareTag("RotatorLeft"))
{
_rb.MoveRotation(Quaternion.LookRotation(Vector3.left));
_rb.velocity = rb.velocity.magnitude * Vector3.left;
}```
All right. So I also want to set the velocity in start?
again it doesn't matter
AddForce or setting velocity in start, you'll get the same result
why not
your jump and your move code are not really compatible
that's why your jumps are so harsh
If i put the move in start it works just fine
well, you'll have a very hard time changing which way you're moving if you only set your velocity once (:
right - because overwriting the velocity like this every frame is going to smother the normal physics simulation
So I should be setting the velocity again everytime entering the trigger?
we don't really know what you're trying to do so it's really hard to make calls about stuff like that
I mean it works just fine atm
Let me explain it real short without stealing your time any longer. I am sorry i havent been clear..
yes
As you can see in the video. I have a character which moves without input. There are box colliders checked as triggers on the turning points. What I want is that when I enter the trigger zone. I want my character to turn the way I want, for example left on the first trigger. I also want my character to jump when Space is pressed.
i would just set the horizontal velocioty only in FixedxcUpdate
allow gravity to handle the vertical
I want the turning to be instant so I can move to my players new forward direction instantly.
e.g.
void FixedUpdate() {
Vector3 forward = transform.forward;
float currentYVel = rb.velocity.y;
Vector3 newVelocity = transform.forward * moveSpeed;
newVelocity.y = currentYVel;
rb.velocity = newVelocity;
}```
Okay this works
I will spend some time understanding what you did. Thanks for the help again. Sorry for not being clear enough
Hi all, does anyone know how to fix this things? or at least tell me how this issue is called so i could google it please.
not code related question
this should go in #💻┃unity-talk (i can explain it there)
Which part should I apply a script when checking for the no. of enemies in a scene then doing something after they all get destroyed?
put them in a list,when you destroy one remove from list
if list count <= 0 then you killed all enemies
Ok but where do i attach that script though?
Ah I see i think ill just attach it to the room where they spawn
yeah any would do, as long as you can reference it to remove elements
also is there a way to hide and disable a gameobject and vice versa?
do ij ust use gameobject class?
yeah is just gameObject.SetActive(false)
does that include its visibility or?
if you set it inactive yeah it becomes not visible
then doing it vice versa makes it visible and activates any scripts attached to it?
Ok thank you very much for your replies!
Oh okay!
if you ever want to do anything on disable/activation
You can use OnDisable/OnEnable methods respectively
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotator : MonoBehaviour
{
Rigidbody _rb;
Vector3 _leftRotation = new Vector3(0, -90, 0);
Vector3 _rightRotation = new Vector3(0, 90, 0 );
private float _moveSpeed;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("RotatorLeft"))
{
Quaternion rot = Quaternion.Euler(_leftRotation);
_rb.rotation = Quaternion.Euler(_leftRotation);
_rb.velocity = _rb.velocity.magnitude * (rot * transform.forward);
}
if (other.CompareTag("RotatorRight"))
{
Quaternion rot = Quaternion.Euler(_rightRotation);
_rb.rotation = Quaternion.Euler(_rightRotation);
_rb.velocity = _rb.velocity.magnitude * (rot * transform.forward);
}
}
}
Whichever rotation trigger I encounter first does its job. But when I try to trigger the next one, my rotations are messed up and player rotates to somewhere else.
well this is rotating to some absolute direction based on what you hit, rather than relative to your current orientation
ohh interesting thanks for the extra tip!
How can i update textmeshpro's text field? (non UI)
I placed a simple TMP above the character that display its HP and it seemslike its not working as the legacy text used to work. (hpNumber.text = enemyHP.ToString();) . im also imported using TMPro;
should be the same method, which TMP did u reference?
You probably want more like:
Quaternion diff = Quaternion.identity;
if (other.CompareTag("RotatorLeft"))
{
diff = Quaternion.Euler(0, -90, 0);
}
else if (other.CompareTag("RotatorRight"))
{
diff = Quaternion.Euler(0, 90, 0);
}
_rb.rotation *= diff;
_rb.velocity = diff * _rb.velocity;```
what do you mean which TMP? the non-gui thingy
Can i see the script
The middle one
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
one sec.. let me clean it up 😄
Aa okay okay I got it. Thanks
I only know what quaternion identity means. The rest needs researching. I will activate my neurons.
https://paste.ofcode.org/9mzxhwcDjLvYiEgakDtRwx
it makes no difference if i put it on awake/start/update
which object has this script (screenshot its inspector)
& any errors in console?
object refference not set at line 28.. but the code should set it for itself..
Sure. If it helps here's my english translation of the code:
Define a rotation we will apply to the object called "diff"
- if we hit a left rotator, that diff will be a 90 degree rotation to the left
- if we hit a right rotator, that diff will be a 90 degree rotation to the right
Rotate the object's orientation by the chosen rotation
Rotate the object's velocity by the chosen rotation```
you probably dont have this script on the same object that has TextMeshPro
if thats the erro you got
hpNum = GetComponent<TextMeshPro>();
Specifically looks for TextMeshPro on this script/object
you are right, the scripts sits on the Parent and the text mesh is it's child
if thats the case just remove that line and assign the component in the inspector since its public
You're the best. Thanks!
Is diff the default naming for desired rotation? or you just decided to use that word?
just a name I chose
all right thanks.
This is also not the desired rotation, it's an amount we're going to rotate by
it's relative to the object's current rotation
another good name would have been rotationToApply or rotationToAdd
got it.
ohh its working that way.. if there any method if i want it to be private? do i need something getcomponentinchild thingy?
if its private you use [SerializeField] private MyComponent myComponent;
try to assign inside inspector when possible
avoid GetComponent when possible
Wait. It's working but still gets refference error
maybe you have a copy somewhere with unassigned field?
probably i have some other AI that use the same script (those might dont have HP textmesh pro on their prefabs) i will try to separete them. one sec
also you should only update text when hp changes not in Update
also a good lesson to start separarting scripts functionalities 🙂
ie your HP script should not be mixed with your ragdolling stuff & watnot
Yea its all good now.
i know, i just having this 'learning project' and i throw a bunch of code together to test things that came in my mind so my code is anything but not clean on this project. ^^' (...and im very lazy to refactor stuff)
its all good, its easier that way in the beginning . just something to keep in mind in the future
of course if i going to work on a big project that i want to give to people to play i will rethink everything 100 times and will put away my laziness if i screw something up, but thanks for the heads up! and also the help 
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
oh
can anyone help?
got this problem where 1 unit in other got a visual bugs
how can i fix it?
yeah, don't cross-post. no reason to ask the same question in multiple channels, especially a beginner one about learning . . .
alright mb
is this a code question, not sure what visual bug you mean
try to explain what the visual bug is (what is wrong) and what should happen. it's hard to tell from a still image . . .
they need to be like 1 on 1 +- like 1 pic
but they are going inside them, like 2 pic where gray body up costumed guy or pic 3 where in left side we see knife and glasses what on costume guy, but gray guys up him, and they need to close a costume guy
(hope you understand, sorry for my English)
I have this issue where when my RedBall collides with my player from the sky it subtracts 1 heart (0.5f) damage but sometimes it subtracts 2 but I want it to remain consistent and subtract 1. Can anyone help please? Here are the scripts: https://gdl.space/eyoyuheyad.cs
startingHealth = 5 in PlayerHealth script *fixed
Is there a way at runtime to assign the render camera to a canvas using screen space camera mode?
it will only subtract one time unless you have multiple colliders on either object
use Debug.log and see how many times it's running and how much damage it's applying
I tried assigning world camera to the main camera but I don't see it updating the render camera in the inspector at runtime
does anyone know how to make a VR HUD?
So i'm having this issue when spawning enemies, I am trying to randomly spawn enemies of different types and some times they render on top of each other. This is my spawning script
// Start is called before the first frame update
[Header("Spawner Settings")]
[SerializeField] public float spawnRate = 1.0f;
[SerializeField] public int enemyCount = 1;
[SerializeField] public GameObject[] enemies;
private int roundTimer = 120;
void Start()
{
StartCoroutine(Spawn());
}
// Update is called once per frame
private IEnumerator Spawn()
{
WaitForSeconds wait = new WaitForSeconds(spawnRate);
while (roundTimer > 0)
{
roundTimer--;
for (int i = 0; i < enemyCount; i++)
{
int choice = Random.Range(0, enemies.Length);
GameObject enemy = enemies[choice];
Instantiate(enemy, transform.position, Quaternion.identity);
}
yield return wait;
}
}
when the enemies spawn they move towards the castle, how would i flip the sprite to face the castle
Apparently for the Gameobject class to instantiate the game object it has to be set to active in the scene, then just deactivate in start method later to make it disappear lol, cant believe i took like 30 mins for that lmao
This doesn't sound correct, I think you're doing something weird.
Also Instantiate is part of the UnityEngine.Object class, not GameObject
you're not doing anything to space out the spawning inside the loop. All the enemies spawned in the loop will spawn instantly at the same position (transform.position)
i thought by adding in a spawn rate it would space them out
I did I have the box checked for a gameobject
for the script to read it
before i had it unchecked
for whether it was active or not
Dot product I think, maybe there is an easier way
Solved the camera issue - it couldn't find it in Awake, but it can in Start()
oh wait no
transform.position.x > castle.position.x //Look left
else if transform.position.x < castle.position.x // look right
i think
but you're only doing yield return wait; OUTSIDE the loop
if you want to wait inside the loop, you obviously have to wait inside the loop
hmm weird
you're being very vague. Sounds like possibly you're using GameObject.Find or something and that's the source of your problem
Instead you should just use a direct reference, and to a prefab not to an object in the scene.
If I understand your issue correctly
The code works in the start() method
however trying to change it in the update() method doesnt work
still vague
if you want help with code, share the code in question
and explain what errors and/or wrong behavior you are encountering.
um ok wait how do i share code to look like in code format
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections.Generic;
using UnityEngine;
public class EnemySequence : MonoBehaviour
{
private GameObject[] normalEnemyLeft;
private GameObject bossEnemy;
void Start()
{
normalEnemyLeft = GameObject.FindGameObjectsWithTag("Enemy");
bossEnemy = GameObject.Find("BossEnemy");
bossEnemy.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (normalEnemyLeft.Length < 1)
{
bossEnemy.SetActive(true);
}
}
}
I'm trying to activate a boss gameobject when 4 enemies have died
normalEnemyLeft is never going to change
You're setting it once in Start and then never changing it
Why don't you just directly reference the boss object?
Like I said you're using GameObject.Find and that's your problem
if you did a direct reference you would not have this issue
Change private GameObject bossEnemy; to [SerializeField] private GameObject bossEnemy;
Then just drag and drop the boss into the slot in the inspector this creates. Then delete these lines:
bossEnemy = GameObject.Find("BossEnemy");
bossEnemy.SetActive(false);```
and you can leave it as inactive in the editor
also yes Digi is correct about the enemy count tracking.
even inside the loop they still overlap
show code
private IEnumerator Spawn()
{
while (roundTimer > 0)
{
for (int i = 0; i < enemyCount; i++)
{
int choice = Random.Range(0, enemies.Length);
GameObject enemy = enemies[choice];
Instantiate(enemy, transform.position, Quaternion.identity);
yield return new WaitForSeconds(spawnRate);
}
roundTimer--;
}
}
Oh yeah i totally missed that lol, sorry am tired af with less than 2 hours of sleep
Ah I see thanks, that is easier lmao
- How many copies of this script exist in the scene?
- Is transform.position ever changing?
- are the spawned objects ever moving?
Where do you start the coroutine
- 2
- no
- yes
in the start function
so if two copies of the script exist in the scene, they may be overlapping eeach other
Thanks a lot, your method made it a lot easier
having an issue where the canvas appears lower than where it should be when running the game
How do I give sounds reverb?
what canvas scaling mode did you select? make sure scale with screen size is selected with proper rez set
you've anchored your ui elemnts incorrectly
thank you
oh I also have this issue haha
things get super small and in the wrong place when i build
which one...
"make sure scalre with screen is selected"
that's all?
scale with screen size + proper anchoring is all you need
that worked, ty!
shrimple setting change
oh yeah, one more thing
this prefab is a little bitch and the movement thing isn't centered on it
unlike literally everything else
why is that
press Z
oh so THAT'S why that toggle was randomly changing
and X toggles local/global
i'm not losing my mind
I think I have a weird case.
I have a trigger with OnTriggerStay and OnTriggerExit. OnTriggerStay calls a function to destroy a gameobject that touches the trigger. The weird thing I think I'm seeing is: OnTriggerExit gets called IMMEDIATELY in that line in OnTriggerStay where the object gets destroyed. Is this supposed to happen?
Oh Mah Gawd
I'm trying to make a prefab stop all movement when it touches my player, I tried coinRB.velocity = Vector2.zero; but it still moves after hitting my player.
first, check if your code is even running
Debug.Log("Hello"); would be sufficient
second, consider what could move the rigidbody after you've set its velocity
if it's not kinematic, then it's going to get pushed around by physics
I know its running because the other part of my code is working
and I dont think anything else is moving it, but if it was, what could I do to stop that?
well, the player is probably touching it at that point
so there's your source of force
is it a dynamic rigidbody or kinematic?
dynamic
ok, so setting velocity = 0 doesn't stop everything that could move the rigidbody
other forces like gravity, friction, etc can still work on it
also, if you have other parts of your code using .AddForce or setting the velocity in some way, then you can also get it moving again
is there a way I can stop the object and make it so nothing else can act on it?
Hey everyone! I am new to game development and would like to get a career in it. Can anyone recommend any good resources for learning?
https://www.youtube.com/watch?v=XtQMytORBmM start here
GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit
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 give you some goals to learn ...
Thank your
under the collider, there are override options for force send and force receive
force send = this object can apply force to anything in those layers (currently set to everything) that it can collide with.
force receive is the same, but to receive forces from other objects
if I have layers 1,2,3. And 1-2 touch each other, 2-3 touch each other, and 1-3 do NOT have collisions. Then I can set an object to Layer 1, and it will automatically only collide with layer 2, and ignore layer 3 objects
If, in my code, I set this layer1 object's collider force receive layers to 0, then this object will no longer take forces to get pushed around by anything.
I see, thanks
probs a dumb question, but why isn't this scriptable object creating a drop-down for me to select the typing?
you've declared a type
but you haven't actually given CritterType any members
all this does is declare CritterType.Typing to be an enum with the values you listed
public Typing myType; would add a field to CritterType
this is almost identical to writing
hmm
public class CritterType : ScriptableObject { }
public enum Typing { ... }
that's embarassing lol
Nesting a type has some effects (it can access private members of the enclosing type)
but in this case, it strictly just means the type is named CritterType.Typing instead of Typing in any context outside of CritterType
I'm trying to figure out the best practice of having a reference to typings/elements that other things can reference so I don't need to put enums in all of the scripts and see if they match in functions
so I was thinking having a scriptable object of each 'typing' would work, and then I can just parse the scriptable object reference for my checks
What would the SO achieve other than holding an enum?
You could make it so that each type is defined by an SO asset
nothing, but I tried to do this whole convaluted system of comparing enums from scriptable objects to strings, or something
you should not have to compare to strings at any point
right
if (enemy.mainType == move.type) would compare two enums for equality
now, you could make an SO that defines an entire type
so
public class CritterType : ScriptableObject {
public string typeName;
public Color color;
public List<CritterType> strongAgainst;
public List<CritterType> weakAgainst;
public float DamageMultiplierAgainst(CritterType target) {
if (strongAgainst.Contains(target)) return 2f;
if (weakAgainst.Contains(target)) return 0.5f;
return 1f;
}
}
You would then deal entirely in references to assets
the simplest way to explain what I want to achieve is to create a pokedex - current thought process is to have the Typing SO so I can have an array of the typings assigned to each 'pokemon'
I understand I could also have the enum in the 'pokemon' SO along with all the other info and have two 'typing' fields, but then I don't know what I'd do for the second if it's a 1-element like pikachu
I'm worried that leaving it blank could cause issues later on
If you used an enum alone, then you would need to have a "No Type" enum value
Alternatively, you could just use a list of enums
so that a monotype creature simply only has one type
I had considered that, but I read online that you shouldn't use enums in a list - they didn't state why
If you did this, then you'd need to check for null instead of a "none" enum value
nothing special about using them in a list
but
enums do have one headache: they aren't serialized by name, but rather by value
so, if you rearrange your enum values, all of your data gets screwed up
you have to assign explicit values to them to prevent that
public enum Stuff {
Foo = 0,
Bar = 1,
Baz = 2
}
you could then safely update this
public enum Stuff {
Baz = 2,
Foo = 0
}
it's kind of ugly
hmm
If you used ScriptableObject assets, then you'd just need to make sure you...don't randomly delete the assets
lol
note that moving assets around and renaming them is fine
unity understands that it's the same asset
I think I'll try the typing enum in the SO and then having like
Typing TypeOne
Typing TypeTwo
and see if i run into issues later
as in, one SO asset for each creature?
hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas
yeah
like this
and then have the same enum setup for the moves SO
What's a good way to "check distance between multiple objects, and get shortest distance to player"?
Essentially iterate through the array/list for distances relative to player, then picking shortest (respawnPoint[i].position, player.position)
If they're not already in some special data structure of some kind, you just have to loop over them and pick the closest
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
like get the classes position from within the class? i.e. the class self-registers its position, then the array checks that data (from self {spawner} to player)?
There is actually an algorithm that's better than brute-forcing
oh wait, wrong algorithm!
I was thinking of closest pair
but your objects would need to be in an spatial acceleration data structure already
not just finding the closest point to an arbitrary point
e.g.
float closestDistance = float.PositiveInfinity;
RespawnWaypoint closest = null;
foreach (var obj in objects) {
float distance = Vector3.Distance(obj.transform.position, player.position);
if (distance < closestDistance) {
closestDistance = distance;
closest = obj;
}
}```
like <RespawnWaypoint> has a "vector3 position" field, which registers on awake. Then my function calls "look for nearest" and gets the respawnWaypoint[i].position
closest pair has a funny n-log-n strategy that i still don't fully grok
but this isn't closest pair; it's just closest point
public void FindNearestWaypoint()
{
RespawnWaypoint[] objects = FindObjectsOfType<RespawnWaypoint>();
float closestDistance;
Transform closestRespawnWaypoint;
foreach (RespawnWaypoint obj in objects)
{
float distance = Vector3.Distance(player.position, obj.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closestRespawnWaypoint = obj.transform.position;
}
}
}
hmm trying to understand the logic there. closest distance is of the waypoint class or the player holding the respawn manager script?
the respawn manager is the one throwing out the signal to see "what is closest to me"
ah ok, that seems to make some sense, i'll try that
is the transform within the waypoint class as a field? like self registering as i mentioned above?
that should work i think
closest distance looks like its the "variable which gets updated" based on the distance info, but running some kind of comparison
I updated it
u need to initialize local variable to something
ignore the player position, the closest distance thing is the issue
float closestDistance = float.Infinity or what that is I forgor
ah yep gotta assign a value, float closest distance has 0 info
^ mb
also idk about that FindObjectsOfType I would drag in references if respawn points are already known if not make them register themselves to the respawn manager in awake
what type is the closestRespawnWaypoint variable?
yeah self registering is probably best
can you do just .transform
sec lookin over the code
says its a transform defined above, gotta convert it to a field by the looks of it
what? no. you just need to give it the transform not the transform's position. unless it's the position that you need in which case your variable is the wrong type
it could stay local if you use it right then and there that wasnt the problem
oh true
that seems like no errors, though i probably need a field array for "objects" right? like a field, not a temp variable
then have it self register (waypoints self add themselves to the array/list on awake)
yes, that would be better than using FindObjectsOfType. but you'd want it to be a List not an array since arrays are not resizable
gotcha, yeah ive been using lists as of late, they are very useful
ait giving it a shot now
also the name implies it should be returning the nearest waypoint rather than assigning it to a field. so you should return either the transform or the vector3 position
then both closestDistance and closestRespawnWaypoint can go back to being local variables. and closestDistance should be assigned to float.MaxValue not 0
ah i think im following, but the other issue is "assign the list position index as the "spawn anchor" point"
sec, trying to process that
ah, so would i return the waypoint class (so i can get the anchor point WITHIN the class)?
I want to access a field WITHIN the nearest class detected
if that it the type you need, then yes
yea rather than the parent object, if i moved it up/etc for visual reasons
public RespawnWayPoint FindNearestWaypoint() correct?
if you need to return the RespawnWaypoint object instead of a Transform, then yes
now make those two other variables local variables again and instead of that long ass line for the return you could just assign obj.respawnAnchor to it in the if statement
hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas
hmm geting s tuck on the return part
why do you have two dots
the format specifically, of what specifically im trying to grab the componet off of
mb sorry that was a quick edit
Hey, guys! I have a problem. I am attending now the Junior Programming Pathway and I have 2 scripts first called Unit second ProductivityUnit and I have the second one inherit from the Unit. I have got a method inside my Unit script that is called BuildingInRange and for one reason when I want to override it in order to do some modifications in my method in Unit Script i ve got an error. I have declared 2 variables in ProductivityUnit script first m_CurrentPile and ProductivityMultiplier the first one variable has a class ResourcePile on it, so it says in my method when I want to override it that it does not exist in the current context. I am sending scripts rn
public Transform FindNearestWaypoint()
{
Transform closestRespawnWaypoint = null;
float closestDistance = 0;
foreach (RespawnWaypoint obj in objects)
{
float distance = Vector3.Distance(PlayerObject.Instance.transform.position, obj.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closestRespawnWaypoint = obj.transform;
}
}
return closestRespawnWaypoint.GetComponent<RespawnWaypoint>().respawnAnchor;
}
can you please read all of the info that has been provided to you before making a change and asking for further help
If I have a list of enum in a scriptable object, how can I compare an enum from a different script to see if they match?
Ah thanks for specifying, will do that now (if you are referring to the rules)
what is the error?
oh, you have two completely unrelated Typing enums.
yeah
I have read it 10 times already bro and haven't found the solution
where would I do that?
i don't know what you think you were supposed to be reading, but my message was not in response to whatever your question was
typically in its own file
public enum Foo { } does not declare a field. It declares a new type.
Typing.cs
I would probably call it CritterType or something though
Typing is a confusing name
Wait the response wasn't for me really?? XD
no, it was clearly in response to the person whose message came after yours (and directly preceded my message) whom i was already in a conversation with
Share your scripts. Most likely you are just using the incorrect access modifier for your method or something
is there any benefit to making it a scriptable object like i had planned in the past? my thought process is I can assign them sprites for the logos and hex codes to colour sprites they're meant to affect
That's what I am thinking too
Minute
yes that could be useful
You probably still want the CritterType enum though
Here is the method in Unit.cs
{
if (m_CurrentPile == null)
{
ResourcePile pile = m_Target as ResourcePile;
if (pile != null)
{
m_CurrentPile = pile;
m_CurrentPile.ProductionSpeed *= productivityMultiplier;
}
}
}```
Here is what I have in ProductivityUnit.cs
{
protected ResourcePile m_CurrentPile;
protected float productivityMultiplier = 2f;
}```
[CreateAssetMenu(fileName = "New Critter", menuName = "ScriptableObjects/Critter Typing")]
public class CritterTyping : MonoBehaviour
{
public enum Typing { Beast, Fire, Water, Wind, Earth, Nature, Thunder, Spirit, Elemental, Aura, Martial, Toxic }
public Typing type;
public Sprite typeIcon;
public string hexCode;
}
So, what happened is the m_current var and productivity multiplier are underlined with red
this seems backwards
something simple like that maybe
The child can access things from the parent, not vice versa
All ProductivityUnits are Units
Not all Units are ProductivityUnits
So Unit cannot do things with fields from ProductivityUnit
it doesn't make sense
this looks like code that should live in the ProductivityUnit class, not in Unit
it should be a ScriptableObject
not MonoBehaviour
yeah i forgot to change that
and I still recommend declaring "Typing" in its own file
this is its own file
no, that's your scriptable object's file (or will be once you swap to SO from MB)
you've nested the enum inside your CritterTyping class. move it out of that
see why Typing is a really bad name?
you're having trouble keeping it straight from CritterTyping
just call it CritterType. Its values are valid types for a critter.
right, i need it in it's own file for move references
no, this is not about files
Enums are types, like classes and structs. They can be put alone in their own file, and you should do that if the type is used in 2 or more places
this is strictly about names.
Wait! I think I found the solution myself I had to declare that method in the other script and did a mistake and declare it in Unit script. Let me check a little bit and if that was not the solution coming back and telling you btw thanks 🙂
in the engine is sais i aint using isGRounded(its a bool)
See these squigglies
you should read what they're telling you
Let me ask you this - if you have:
bool x;
And you want to assign the value 5 to it on the next line of code, what would you write?
x = true;```
or
```cs
bool x = true;```
isGrounded is a bool
doesn't matter what type it is
bools are not a special type that work differently from everything else.
there I changed the example
you sure?
you rewrite the type of the variable every time you want to assign it?
Your way:
https://dotnetfiddle.net/p7PCCO
The correct way:
https://dotnetfiddle.net/Br8xJz
The compiler knows it is a bool from the point you declare it. You never need to tell it twice
If you do, it thinks it's a new thing
yes
when you do that you are actually creating a brand new variable (a local variable inside the function)
and the original variable is unaffected
ye
And you do not want that
You should really do some basic c# lessons before unity
how do i make a game object rotate on the spot with moving my mouse as to how much it rotates
can you rephrase that in a way that makes sense?
have you tried holding alt while in panning mode?
so im in 3d third person view and i want a cylinder to spin on the spot by how much i look around with my cameras
alt + drag with click
no not in scene view
Basically rotate the cylinder whenever you move your mouse in-game, right?
you'd need to tie the rotation of the cylinder to the mouse via code
^
you basically need to code: everytime I move the mouse, I'm going to interpret it as a command to rotate by X. Then I'm going to rotate the cylinder by x
either by its transform, or applying torque to a dynamic rigidbody
guys I just realised I was dying trying to get an IEnumerator to count down while the time scale is set to 0 are there any work arounds to count down ?
show the code so the issue can be pointed out
thanks mate forgot that the count realtime seconds existed I don't think I ever had to use it
https://hastebin.skyra.pw/jizutuqaqi.java Hi I wanted to ask. I currently have this code from a tutorial, and I tried to apply it to a 3D model's torso and I was wondering how I would change this such that the torso properly follows the mouse?
Anybody know why StartNetwork as Host keeps crashing the Unity editor? I have literally never had this issue until yesterday when I started up my game for another edit session.
define "craching the unity editor"
most likely you have an infinite loop
For Start Network as Host?
no, in your own code when you start the network
The audio still playing is another hint that the main thread is blocked actually. Audio runs on a separate thread.
so the runtime is not crashing
but the main thread is blocked
Odd. The thing was working before, and when I started it up again this happened. I didn't change anything after the last time it worked
you didn't change anything that you remember or that you think mattered
Like, I saved and quit, and then got on and this happened
thats always the classic, "i didnt change anything". you should use version control if you arent, which would prove if you have changed something
The surefire way to see what's going on is attach a debugger to unity, and when it's frozen you can pause the debugger and see what the main thread is doing currently
I'm not going to ignore this advice though. I shall go check out the code and look for infinite if or while loops
I would require further assistance for that
So I am going to start with finding loops
Oh hey I already have that attached 👍
can anybody help me? My question isn't about programming, but I don't know which channel to send this specifically
I'm making a procedural system for my game, how can I create a separate tile?
So I guess I just need to look at it
The nice thing about having the debugger attached, is when you hit the infinite loop somewhere, you can pause the execution by hitting the "stop all" button and see where the execution is at that point
It's gonna be just my luck that I did in fact change something. Time to go see 🤦♂️
MY GOSH WHERE DID THAT WHILE LOOP COME FROM?!
git blame
You, 3 days ago - commit 8bfe346
🤣
Programming is like being the detective in a police procedural where you are also the murderer
Thanks. I shall pin this legendary quote to my wall above my PC. I am just relieved that my game isn't corrupted where I have to revert to an old version. I was about to backup this copy when this happened. 🤣
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Guys, I have a problem, I went to import Starter Assets first person from Unity, and so far everything was fine, but after I imported a PREFAB, unity crashed, then when I logged back in, the whole map was purple, Then I saw on YT what I should have done, to import the first person, I should have configured Render Piperline first, now the first person is working, but the map is all purple, can you help me?
Not a code question => ask in #💻┃unity-talk
ok
please help me in #💻┃unity-talk
hey, two questions
- how can i add reverb to sound effects?
- how i can prevent sound effects from cutting each other off?
ok thank you
oh and where do i store them haha
having each sound be its own gameobject seems... suboptimal
You'd play them via code, with the PlayOneShot() method, that one allows overlapping of sounds
yep that's how i'm doing it, except need to apply reverb to it
Reverb zone components can do that for you without any code
works perfectly, exactly what i need
You can have them as fields on a single gameobject. Or an array of them. I do that to randomly select from similar sounds to give variety
fields?
Variables
Oh ok cool.
I was looking at this
#💻┃code-beginner message
Well it's still referencing the objects here
Hmm, what do you mean?
but if i have a bunch of sounds this is gonna be a pain
Why not have variables of the CLIPS not the object?
That's what I meant
Usually you'd have one field of type AudioSource and a few fields of type AudioClip yes
Idk what a clip is Lol
The sound file
You can separate the fields in the editor with [Space] or [Header("Name")] if it gets too messy
ok,
public AudioClip footstepSound;
oh that's not allowed
1984
anyway let me be clear
if every single sound effect in the game requires its own gameobject, that is really gonna suck
i'd like to not do that
but it's the only way i can figure out
Why would it need that? We are saying not to do that
Single object, multiple AudioClip variables
.
you have now told me an alternative option
i dont see
Not a component
I told you that option BEFORE you said that, that's why I was confused
Oh I Have Small Brain I Didn't Realize That it Wasn't A Component
yeah this is what i was looking for ty
How an i make Object snap to grid when in the 2D mode
Should work the same way as in 3d
2d mode just enforces a camera angle for scene view
okay ty
...why the hell does adding an AudioSource to my charactercontroller cause my fps to halve
That's it
Changing nothing else
If I remove it the performance is normal
are you certain it is just the audiosource causing the issue and not perhaps some code you're running?
is the audio source itself
or the inspector for the audio source
do you have multiple audio listeners?
Rigidbody has a famously slow inspector
yeah you should use the profiler to determine the actual source of the issue
if I also press any input keys fps tanks
wtf
but only if I have audiosources
¯_(ツ)_/¯
idk what any of this means
Noone does 
Look at hierarchy not timeline
On the left in the middle there should be button
yep, looks like it's the editor, not the actual audio source
U can change to editor mode to profile editor
?
So, my physics material looks like this and is attached to my character controller like so, it moves as expected.
When a moving sphere, with the same physics material, hits the bumper, it loses all velocity towards the bumper and starts drifting to one side or the other depending on the angle of impact.
Expected behavior is that velocity is preserved and it bounces, behavior can be observed when ball hits the walls of the arena.
the "Bouncy" material is on the ball, the bumper, and the wall, but ball-bumper collisions exhibit this problem
Hey, I have an object (A) that I want to be IsTrigger so that I can check when it is colliding/touching another object (B) without physically interacting.
But I need the object (A) **not **to be "IsTrigger" with other objects (C which is ground) so it can stand on something.
Is this possible?
whats the easiest way of refiling holes in mesh after removing bunch of polygons from it
use two colliders where one is on a child object on a separate layer that only collides with either the objects you want to detect with the trigger or the ground for the non-trigger
Do whatever you did to remove polygons from it but in reverse
no i want the holes
Does anyone know how to separate these? Like the dark green thing en the light green squares. These r the codes
This is not a unity question
this is a unity server. not a general coding/web dev server
Here's what you need to do:
LMFAO
Bye🫡
but the holes with texture in newly made hole not the missing faces
i thought about moving polygons instead of deleting them but would be hard to figure out where to move it to be inside mesh still
Okay I created a child empty object of original object A. I made it isTrgger. I made a new layer for it, and in the Physics settings, I said it can collide with everything.
But the script is still in the parent, will the OnCollisionEnter detect any child object collision as well?
does the parent object have a rigidbody? if so, then yes. all children colliders will become part of the rigidbody's compound collider and will have physics messages like OnCollisionEnter sent to the rigidbody
what code would I do to make this red UI's y position 0? I've tried this but it doesnt go anywhere close:
remove.GetComponent<RectTransform>().position = new Vector3(1311.7f, 0, 0);
Yes the Parent has a Rigidbody, and the parent has a Box Collider that is not isTrigger.
The parent carries the script with the OnCollisionEnter().
The Child has a Box Collider that is isTrigger only. And is on a separate layer.
Inside the Parent script I am just running this;
`
private void OnCollisionEnter(Collision collision)
{
Debug.Log(rb.name + "colliding with " + collision.collider.name);`
But it doesn't detect collision with other object it seems 🤔
so how can i make hole in mesh that will not be missing faces in hole i made
At runtime? Complicated procedural mesh.
can someone explain why the materials dont load when i import a package and how do i fix it
The package is using shaders not compatible with your render pipeline.
i did wanted do that because thats how im editing out vertices to make hole in first place
but im not sure how to auto fill the missing faces
Looks like they're using a different render pipeline than you are
where do i see this
URP package?
im currently using urp
making sure this is urp right
This is not a urp shader afaik
ok makes sense
i took off urp and all the things loaded 👍
ty
Thanks for the help, it seems like even with Physics messaging and a breakpoint I am not getting a response.
But I will investigate cause I really like the concept of having a child collider that acts as just a trigger, it would be amazing if I could get it working.
did you go through the rest of the steps to make sure you have your rigidbody and everything set up correctly?
hello,
I'm making a simple segment of my inventory system where the player can hold down left click to rotate a model of their player in the inventory screen. I want to make it so that the rotation has a bit of energy (that is to say that spinning the camera will increase its velocity so when the player lets go the model spins just a bit) how would I go about doing this? Here is the script I have so far https://hatebin.com/gnisfntzss
I should note that this system uses a second camera in the scene that is tied to a pivot which is tied to a G.O tied to the player. The pivot is what rotates around the player giving the illusion that the character "model" is the real thing
EDIT:
Figured it out, just add a rigidbody to the game object, and then use .AddTorque. It works in a very similar way to updating a quaternion without multiplying.
Here is my Gameobject hierarchy.
Green contains Script + Box Collider without isTrigger + Rigidbody.
Cube contains just the mesh, a cube.
InvisCollider contains the second Box Collider with isTrigger.
show the inspector for the collider and also the rigidbody
okay now show the layer matrix in the Physics settings
Here is the Box Collider inspector for the "InvisCollider" child by the way.
okay and now show the object that it should be colliding with
Well maybe that is the issue 🤔
This is a Prefab, all of this. ("Green")
It is instantiated multiple times. So it collides with other instances of itself.
well the Cards layer can collide with the Cards layer so that is fine. do you see it actually reacting to collisions in the game? like the objects are physically colliding?
Yes but only with the Box Collider in the parent. Because it is not isTrigger.
And the breakpoint works for that, when they collide.
But I made the Box Collider (with isTrigger) in the Child much bigger, but still no Collision detected.
okay so this whole time the issue has been the triggers?
are you sure you read the site i linked? because trigger colliders do not send an OnCollisionEnter message because they are not entering a collision
you should be using OnTriggerEnter for trigger colliders
How can I completely stop my game? basically making it so nothing happens and I can't do anything until I reset the app
while (true) { }
well I don't wan to crash it I just want to stop it
Wow 🤦 I have been calling it from OnCollisionEnter.
Changed to OnTriggerEnter, now it is working 😂
Feels good. Thanks a lot @slender nymph , really appreciate it! 🙏
OnCollisionEnter is for entering collisions like when two non-trigger colliders begin colliding. OnTriggerEnter is for when any collider enters a trigger collider
Makes sense, thanks for taking the time to help and explain ⭐
what they suggested isnt a crash (and technically fits your description), what are you trying to actually do though
How would I go about creating a sliding 2D platformer character with various shapes?
Something like this:
https://springboard-cdn.appadvice.com/generated-app-plays/443637419/148302848-quarter-apng/med.png
Can it be done with built in physics system using gravity to speed up the player and slopes being 99% or 100% slippery(so you can go up the slope)
Basically you need to gain speed faster when you go down than you lose it when you go up if that makes sense.
I am open for ideas tho as I am not sure what are my options.
The link has an animation if you want to see it play out.
Perhaps I need a script that gives player speed when you slide downwards + forward
Should be fine with rigidbodies and unity's physics
I would probably not use the physics engine for this. I'd use the Splines package and just have the thing slide along the spline when it's on the ground and otherwise just do a rudimentary gravity simulation
the spline can also be used for the grounded-ness check. e.g. the position of the spline at that point is the lowest allowable y position for the penguin
I was thinking maybe some techniques to make the level in a paint program then rasterize it all in unity
SpriteShape also has a built in spline framework too
and can be used for worldbuilding here as well as the physics sim
hi im trying to fix an issue where my character is stuck in a walking down animation after going down a certain point
make video mp4 so we can view it on discord
you'd have to share your code
which animator parameter controls the walking animation
so you're only setting that when input != Vector2.zero
meaning when you actuall release the input, it won't run at all
so it will never stop
shouldn't you move that outside of that if?
oh but if i stop before reaching that point thats low enough, i can still move again
Then your other problem might be while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
you should add Debug.log inside the Move coroutine and make sure it's actually finishing
you might be stuck in the loop permanently
like this ?
{
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
Debug.Log("Movement finished");
}```
sure - but you probably would want to put a "movement started" one too
i see neither of the messages appear on the console
oh nvm, im not sure how but it fixed itself?
thanks for the help!
Hi I keep getting a CS0103 saying the name of bulletpoolInsstanse does not exist in the current context
In my Fire bullets script, and I just cannot figure out why this is happening does anybody have an answer or way to fix this
bulletpoolInstanse is a static variable on the bullet pool class. It does not exist outside of that class, you have to access it via the class name. bulletpool.bulletpoolInstanse
Okay thank you, I put bullet pool with bulletpoolinstanse is that what I’m supposed to do?
You should use proper naming conventions to distinguish between variables and types/classes.
I would love to do that, but I have no idea what that means😭
Thank you!!
public class BulletPool: MonoBehaviour
{
public static BulletPool bulletPool;
}
Okay I did this!! This helped but mows it’s saying CS1061 for BulletPoolInstanse
errorcode# isn't as helpful, look at the specific error message it says
I bet its "GameObject does not contain definition for bulletpoolinstance and no accessible method blabla"
https://unity.huh.how/compiler-errors/cs1061 yeh, likely in this case the type is never declared at all, and it's not namespaces
Yeah, it’s that one
you never changed this
#💻┃code-beginner message
BulletPool instead of GameObject
GameObject types only know GameObject things 😄
Okay thank you!
wait actually they just need to to use the class directly , the reference isnt needed since its static
BulletPool.bulletPoolInstance.GetBullet()
So don’t delete game object
Oh I missed the static part.
Yeah, static means it belongs to the class itself not an instance (simplifying things). There can only be one, so the compiler will always know which one basically
So yeah, you don't need the variable at all
OK now it’s saying bullet pool does not exist in the current context
OK actually it it works. Thank you so much!!
Thank you guys so much it really means a lot. You guys have just saved my freaking project. Thank you.
Is there something that might be easier to do as I never did splines? This is a prototype only so I don't care about optimization, but I need a way to control the speed based on penguin rotation + collision/drag perhaps.
hey fellas... would you mind helping me out
so basically I have a gameobject that when the player collides with it it loads a scene
i have a string set as the exact scene name and the code for collision works because when i put destroy game object it destroyed itself
Do you ever assign anything to that field?
oh well now that you mention yes its with a bunch of other string/floats
should I just state that string outside?
This is just a variable. Unless you assign a value to it, it's gonna be an empty string or null.
in the inspector
and what's it set to in the Inspector
ahhh
can you elaborate
i see
I feel like there's a total lack of basic understanding of working with unity...😅
Or code.
learning both at the same time is difficult in the beginning
yerp
im basically mimicking my code that i used for a button to load a scene
execpt when colliding with a game object
the game object being a white cube with rigid body
although i don't think that matters
its just the code thats the issue
To be clear, this is meaningless:
#💻┃code-beginner message
It has no value there
They want to know the value of the string
Right
Show the inspector in unity with the object that has that script selected
This is my player movement script
The issue is that they don't seem to understand what an inspector is...
We don't want to see code
unless I should make a seperate script for when the block touches the player instead
Congratulations. Now show the inspector for it
Show it with the MainMenu script on an object
That is the one with the string we want to see
Right?
this is what you are supposed to touch
its only for 1 button
You have 3 errors
ill pull it up
Yes but what about the title string that we care about
yeah because of the empty script
im sure i stated it though
We just want to see it
Wheres the rest of it
yeah ill pull it up
mb
this is the error in question
this is my WHOLE player scripy
Ok, so as they thought, the string is empty
Okay, so do you have a scene named
no
i have a scene named title
and gameScene
yeah i put "title" in it
the empty string
mb for not getting the inspector out sooner
whenever I clicked on the error as I would it would bring up visual studio
so I figured it couldve been an issue with the code
yes, because the error happened in your code
you tried to load a scene that didn't exist
that was the error
yeah
no but I stated it through the inspector instead
but I would totally do that next time
assigning value and stating /declaring variable are different
just state it right in the code
right
well, that's the thing
This says that the default value for title should be "mySceneName"
but Unity is going to save whatever value you entered in the inspector
I getcha
A common mistake goes like this:
- Create a new field
- Attach the component
- Give the field a default value
The instance of the component already has an empty string saved for that variable
adding a default doesn't change that
unity will load the saved values for the component and overwrite whatever the defaults are
Hi I’ve got some more work done on it and now it’s saying this and I researched a bit on it but the ways I’ve tried or not working
Do you understand the error?
LISTENN i’m tired y’all I’m I’m using a school computer that doesn’t let me screenshot, so I’m sorry that it looks like dookie but i’m on my last strand i’m losing my mental
it's windows
press win + shift + s
or open snipping tool
They probably mean by that they don't have discord installed on that PC.
"Just take the screenshot, email it to yourself, and put it on discord from your phone" 😂
Sounds like a plan
Is this the same line as before?
It kinda looks like you've barely started anything. Isn't it too early to "lose your mental"?😅
I’m not gonna get into it, but my computer broke early in the week with an actual complete game on it and my two of the games that were saved on another school computer are gone so it’s just kind of been a frustrating week😭
if only there was a browser version of discord 😢
You guys are giving very good advice. I’m just I think I’m just tired
Can't imagine how you were able to complete a game with the current understanding of C#.🤔
Listen, it was simple really simple. I’m in the class, so it was really simple and I had my teacher help me.
Okay. But I still suggest learning the C# basics, so that you can make the game without your teacher's assistance.
Discord people be like "guys why doesn't this code work"
BRUHHHH YALLLl
I mean, at this point we can't really help. You showed an error code and that's it
It's too blurry for the compiler to understand it.😬
error on line... well... every line
compiler error: could not read the file(it's too blurry)
new captcha , deblur this image
Fix all the compile errors in the next code.
compiler error: git gud
lmao if you can do it you're a robot
one of us
How can I create a car with an npc inside so that they can get out of the car and get into it?
simple triggers
some code
It's not something that can be explained in a few sentences in discord. Unless you're asking about a certain specific part of it.
step 1: make car
step 2: make NPC
step 3: ???
step 4: profit
where is the "make npc" button 
Near the "make a world of warcraft killer mmo" button.
should be right under the "finally finish a game" button
Item not found
object reference not set to an instance of an object
least confusing error for newcomers ^
no it's below the "make game multiplayer with 100,000,000 player capacity" button. right?
Ay
did anyone here send me a message request lmao
I accidentally declined it and I don’t know who sent it and what server they were from 😭😂
it was like 5 minutes ago so if it was from this discord I’m hoping the user is still online
eh I’ll figure it out
I have two layers for an enemy. One layer is if I get into contact to that enemy I die. However the second layer is on the top of the enemy head. How can the player jump on the enemy head and kill it.
make sure the box collider that makes the player kill the enemy is slightly more scaled to the center than the sides. this will prevent the player from walking into the enemy to kill it. <3
those are colliders.
use one of these methods to detect enemy
if head is trigger use
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
if its not
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
also, the other collider should be on a separate (child) GameObject . . .
How can I prevent it from going back to Idle when I jump?
So if I change the Jump Force to 14 it doesn't do this. But if I change it to 10 is does do this.
Why dont you just check if you're not grounded
Is it okay to just have a bunch of classes in one C# script?
typically, you have one class per script, but sub-classes are fine (as long as they don't derive from MonoBehaviour) . . .
you can only have one class derive from MonoBehaviour in a script . . .
Except in 2022+ ?
I know at least the name doesn't have to match the file name, but I thought you could have multiple classes too?
I can't conceive of a reason you would ever want to though
why would they do that? yeah, let's make this more confusing . . . 🤦♀️
