#💻┃code-beginner
1 messages · Page 176 of 1
if (_isJumping) // Jump logic
{
var hit = Physics2D.Raycast(transform.position, _rayDirection, 2, _groundLayer);
if (hit.collider != null)
{
if (hit.distance < 0.36f)
{
_rb.AddForce(Vector3.up * _upwardForce, ForceMode2D.Impulse);
}
}
_isJumping = false;//Will never jump again until the button is pressed again
}```
Just one of them to spawn one.
which one
As I mentioned resetting jump will force another jump click. I want it to jump automatiaclly while jump button is held
On normal click its working fine
On held its acting possesed
The object
"The" object is everything this script is on
which one should spawn the new object
I've got no clue what you mean by automatic jump at this point, so I'll let others help you.
The puyo
Which one
The one that = 2
The one that what equals two
dropSet
Okay, so, whenever this object's dropSet is 2, and it collides with an object that is the floor or another instance of this script
That is the condition in which you want to spawn something?
Yes
why cant i get close to the player in the editor without it clipping?
You hold button. Player hits floor. Player jumps.
So, that'd be what you want. Inside of your trigger function, check those conditions. Start by checking this object's DropSet, then check if the object is floor or puyo, and if both conditions are true, spawn your thing
not a code question. likely due to your scene view camera's dynamic clipping planes needing an update. double click the object in the hierarchy to focus it
Select the object, hover it, double-tap the F key to focus on it. It'll adjust your camera's clipping planes to something reasonable for an object of its size and distance
sorry thought i was in general
@stuck palm You've been told multiple times in the past about posting non coding questions here. You should know this by now, and the next one will be moderated.
You could use a singleton, static class or ScriptableObject, if the data needs to exist across scenes, you could mark it with "DontDestroyOnLoad", if your goal is to save to a file at some point, you could then use a serialized class and save an instance of that class with something like JSON, maybe a combo of a serialized class and ScriptableObject might help, depending on how much data and the type of data your trying to persist
i have 2 discord instances open i thought i was in unity-talk 😭 soz
Key word is multiple times. Just be aware next time please.
i shall
I'm using a scriptable object now, but every tutorial regarding saving I can find with scriptable objects treats them as unique objects and for multiple of them.
It overcomplicates it and makes it a ton harder to follow
What kind of data are you trying to save?
Do note that "saving" data to scriptable objects is not persistent. In builds, restarting the game will discard changes made to scriptable objects.
As such, you most likely need another system, where the data is saved to a file, and loaded when the game starts.
too much for playerprefs
yes that's what im working on sidestepping
Plain text Json time
that's what i need to learn how to do, scriptable object data to plaintext json
but this is extremely vague. A simple variable "stores" data. You need to specify the lifecycle you want for this data.
A local variable "stores" data during function execution
A member variable "stores" data for the lifetime of the object
No scriptable object, just a regular class. Saving and loading that into a file with JSON is literally 2 lines of code
What are those magical lines
Depends on if your using the built-in JsonUtility or something like Newtonsoft JSON (which I suggest due to its flexibility) or another package
yes the whole thing though is you need to design that "playerData" object
that's where most of the code is
+1 NewtonSoft Json.Net
you create a class that stores a description of your game state
you create an instance and then serialize it to JSON to save
you deserialize from JSON and use the instance to restore your game state
I’m reinstalling Unity. I need to know which version of unity editor corresponds to June of last year. How do I find that out?
am I doing something wrong or it doesn't work on new input system?
private void OnMouseEnter()
{
Debug.Log("Mouse over object: " + gameObject.name);
}
private void OnMouseExit()
{
Debug.Log("Mouse left object: " + gameObject.name);
}
Doesn't log anything (It's attached to primitive Cube created via hierarchy, it has collider on it obviously)
OnMouseEnter/Exit are not supported in the new system. Use the Event System alternatives
IPointerEnterHandler/IPointerExitHandler
that'll also work for 3D objects?
yes as long as:
- They have colliders
- You attach a Physics Raycaster component to your camera
- You have an EventSystem/InputModule in the scene
cool thanks
ty
U good buddy?
That sounds like a “sanity check” type of thing
private void ScrollBackground()
{
var xScrollClouds = Time.time * _speedClouds*_movementVector.x;
var xScrollMountainsFar = Time.time * _speedMountainsFar * _movementVector.x;
var xScrollMountainsNear = Time.time * _speedMountainsNear * _movementVector.x;
var xScrollTrees = Time.time * _speedTrees * _movementVector.x;
var offsetCloud= new Vector2(xScrollClouds, 0);
var offsetMountainFar = new Vector2(xScrollMountainsFar, 0);
var offsetMountainNear = new Vector2(xScrollMountainsNear, 0);
var offsetTrees = new Vector2(xScrollTrees, 0);
_rClouds.sharedMaterial.mainTextureOffset = offsetCloud;
_rMountainsFar.sharedMaterial.mainTextureOffset = offsetMountainFar;
_rMountainsNear.sharedMaterial.mainTextureOffset = offsetMountainNear;
_rTrees.sharedMaterial.mainTextureOffset = offsetTrees;
}
private void GetRenderer()
{
_rClouds = _clouds.GetComponent<SpriteRenderer>();
_rMountainsFar = _clouds.GetComponent<SpriteRenderer>();
_rMountainsNear = _clouds.GetComponent<SpriteRenderer>();
_rTrees = _clouds.GetComponent<SpriteRenderer>();
}```
Im using tiled images on background I want to make ilusion of them moving. This is not working, dont know what to do?
Is the code actually running?
Yes
Time for Debug.Log
I can place an interruption and its infact running but Im not sure if its doing anything
^ time for
log some values. Make sure things are as you expect
Or sure if you're using the debugger
look at the values there
You need to define what's not working and log the necessary related stuff
I mean nothing is moving
99.9% sure mainTextureOffset is not implemented on SpriteRenderer
or at least not on the default sprite material
I think so to
don't think - check lol
I have no idea what to search
Use a different material and potentially renderer (MeshRenderer)
you need a material that supports texture offset
a quad with a basic unlit shader should do
Hmm gonna add change things
it’s a “my computer got fried, and while I wait for the backup files to be accessible, I’m installing the version of unity editor that matches what I was using.”
eg “fine”
so got it working, but, the "click!" debug log isn't displaying after pressing down the left mouse button, but it's printing after releasing it (up! is also printing)
void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData)
{
Debug.Log("enter!");
}
void IPointerExitHandler.OnPointerExit(PointerEventData eventData)
{
Debug.Log("exit!");
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("click!");
}
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("up!");
}
is that something I need to adjust in the new input system module?
yes that's expected for Click
IPointerDownHandler is for the first part
Jeez. Rip your computer. How did it get fried?
so what's the difference between Click and Up?
Click is the whole process of clicking and releasing
PointerDown is just the initial click
PointerUp is just the release
ow so Click is down and up combined
i suspect there is a failure of a component on the motherboard
one that handles power
Hello. I am trying to create an EdgeCollider2D for in my Edge class's constructor.
Here is the relevant constructor code:
{
m = Instantiate(Resources.Load("Vessel") as GameObject);
ec = m.AddComponent<EdgeCollider2D>();
lr = m.AddComponent<LineRenderer>();
//Debug.Log(v1.localPos());
//Debug.Log(v2.localPos());
ec.points = new Vector2[] { v1.localPos(), v2.localPos()};```
`Vertex.localPos()` just returns the Vector2 that the Vertex was constructed with.
`Vertex.getRealPos` uses `transform.TransformPoint(localPos)`.
Neither `localPos()` nor `getRealPos()` connects the EdgeCollider2D to the vertices without a considerable offset. What can I do to negate the offset?
What do you mean by "connects the EdgeCollider2D to the vertices"?
and where did v1 and v2 come from in the first place? What values did you give them and where did those values come from?
I set the EdgeCollider's points to the Edge's vertecies
i think you have a bit of a disconnect in your meaning
yes but where did those come from
edgecolliders have vertices, connected by edges
why do you have a separate class of edges and vertices
There's nothing wrong with edges/vertices
i’m just confused why there is a second class here
Because lots of algorithms operate on Edges
I honestly don't think it's that important in the context of the question
oh, are you trying to start with a representation of vertices and edges, and then create an edgecollider that matches this?
The class is likely just "boxing"
We need to see the behavior pattern of what's working and not working (the actual data)
if you need to create an edge collider based on a predefined path of vertices, you want to use SetShapes, and PhysicsShapeGroup2D or something like that
Hey all, i'm trying to make a simple pong game and im currently working on getting the ball to bounce off correctly, while giving it bounciness achieves this, it does bounce in the directions it should like the original pong as it is really a flat surface, so i'm trying to implement bounciness myself.
I have this code here:
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Bumper")) // Get other's distance from centre and check Y offset
{
float yOffset = transform.position.y - other.transform.position.y; // Set velocity based on this offset
rb.velocity = new(-rb.velocity.x, yOffset);
}
}
On detecting collision with the bumper, it tries to inverse it's x velocity to start travelling the other way and give it y velocity based on it's offset from the centre of the bumper. The issue is, as of the time of collision, velocity is zero, how would i go about getting the velocity before it collided?
Basically @dusty silo is saying "Vertex.localPos() just returns the Vector2 that the Vertex was constructed with." - so I want to make sure what they're passing in here is actually a local position in the coordinate space of whatever m is.
which seems unlikely since m was just spawned inside this constructor
the edge shape has a set of vertices, relative to the offset of the collider, which is relative to the transform
Vector2 oldVelocity;
void FixedUpdate() {
oldVelocity = rb.velocity;
}```
OnCollisionEnter indeed happens after the collision is already processed and it already bounced and changed velocity
Makes sense thank you
if your edgecollider2D is on something with transform at (100,0), it has an offset of (0,10), and you put a vertex at (1,0), then the edge will have a vertex at (101,10) in world space
I am using the EdgeCollider's for collision detection, but the Edges will store more information than just edge detection
Sorry for the ping again but i realise i might have another problem, when colliding with the bottom or top, it doesn't bounce as i would expect to even with horizontal momentum, and im not sure how to get it the way i want really
nevermind, it was the friction i had set, apologies
getRealPos() returns localPos transformed by m's transform
Thanks. Will try this
is there a builtin way to do a knockback grenade? Like an ImpulseForceAt()?
or do we manually have to code it with a overlap, then manually doing the addforces?
how would built-in feature for such system work
when in every game it works differently by design
get colliders with overlap, calculate knockback direction, add force in that direction
5 minutes of work
and extensible/configurable to your needs
https://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html This seems to be basically that
Still you'll likely want some way to exclude any object that's too far away, likely using an OverlapSphere
When I use this bit of code I end up just turning off my ui but am unable to turn it on again, any help?
if (Input.GetKeyUp(KeyCode.Escape))
{
Netmanui1.SetActive(!Netmanui1.activeInHierarchy);
}
Update does not run on disabled objects
it seems to have a range, and i assume the grenade will like call it right?
oh nvm
Must be called on the RB, hence the usefulness of Overlap here, but the neat part is that it does the math on your behalf for creating the correct force vector
yea, i quite want to let unity handle the physics math as well
Hi.
Good day!
I have a question :
How can i have multiple cutscenes in a scene and how should I summon them?
You should have another object with this script that dosn't disable, to manage the state of the object
Yeah, I belive I fixed it
Thank you!
OH, do you know how to make a mission objective, like quest?
I searched the unity blog but I didn't find anything.
You have to define what an objective/quest is in your game
like goals? get x thingies, kill x monsters?
Objectives and quests are veeeery broad topics
Very much so . . .
how do I remove elements from this custom list thru gameObject?
Like if that would be the List<GameObject> list, I would simply : list.Remove(gameObject);
but how do I do that with custom list?
!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 same way, but you use an instance with the same type as the list . . .
I don't know what you mean by a "custom list"
{
if (i != 0)
{
if (BSM.EnemySpots[i].UnitOnSpot == gameObject)
{
BSM.EnemySpots.Remove(BSM.EnemySpots[i]);
}
}
}
got that, thank you
Hi im trying to make an aim and shoot basketball game but im a big beginner o 3d and been using different tutorials online to make the code, it all works as wanted except when clicking to aim the line renderer used to aim appears way above the starting point given although the x axis is fine. Could anyone fix this? thankyou
The methods are the same, just make sure you insert an instance of type T . . .
I've gone ahead and looking into taking your advice here, because it seems like the best approach. I have a few questions/issues though: Localization. I probably won't be launching with localization, but I definitely would want to add it in the future. SO's seem problamatic as I'd need to double all these SO's for each lang. But I've seen that it would basically be the same thing for a json, but externally, so I'm not too worried about this, but wanted to know which is the more efficient route.
Also, the memory issue again. I can either load the appropriate scriptable objects according to language all at once on startup and leave it there, or load & unload dynamically as the user requests dialogue. I think the first approach would be better as using Resources.load and unload every single time the user requests dialogue seems taxing, but I wanted to get input from someone who knows more about this first. Maybe there is another way?
maybe loading it async or something
Is there an is touching method/function?
Like if (object.isTouching.otherObject) {Do this}
The closest thing I've found is just a boolean setup
I can probably check for a collision but I figure the proper formatting makes more sense
what ive used is checking for a collision but it needs a box collider2d if you do it that way
if you're even doing 2D
I don't know much about 3D
Would OnCollisionStay2D() work?
I'm trying to detect if an object is touching another object so that I can later attach/detach the two objects on a keypress
Can someone help me find the answers im looking for by either;
- sending me to the correct discord channel.. or
- direct me to the correct tutorials/docs/youtube video(s) for syncing my game across gamecenter on iOS for a turn based board game.
void OnCollisionStay2D(Collision2D collision) can i put specific colliders into inputs so that a different action happens depending on the collider that was hit? (like this maybe?)void OnCollisionStay2D(Collision2D BoxCollider2D)
hey, so in this unity document (https://docs.unity3d.com/ScriptReference/Vector2.ClampMagnitude.html), it explains what the Vector2.ClampMagnitude is and how to use it. The thing is, I understand that one of the parameters is to set the velocity using Vector2 to tell the program what that the maximum velocity. The thing I don't understand is the other parameter, the maxLength, which I don't know what it is. Can someone explain to me what it is?
how to make most default green progress bar that i can display script progress on
What does that even mean?
What's your usecase?
script that digests through text file for 5 mins to get all vectors
I am trying to delete a Canvas when its content has finished an animation, but this error shows up
What is causing that?
is that green bar even usable or is reserved for unity stuff
having a problem rn, it seems like the OnTrigger function doesn't work
Trying to make it so when the enemy shoots a laser, and that laser collides with the player, an event will invoke and set off different methods.
This helped solve something similar
Make sure you are following that
Hey guys, Im currently getting an issue with connecting to an Ip, when I get my ip from a textbox in ui and put it into the unity transport system it must have an invalid charcter, is there anyway to trim it?
can someone help me here #💻┃code-beginner message
"Returns a copy of vector with its magnitude clamped to maxLength."; you take the direction and length of the vector and then cap it to the maxLength value
The magnitude of a vector is like how far does it go
oh ok, so the vector parameter is like checking if it goes to a certain speed, and if it does, then it will cap it to maxLength
did I get that right?
Vector is not necesarily speed, but yeah, pretty much
If you are using it to set the maxSpeed of a 2D object, that would do
I've never seen this version of the graph, where did you get this from?
Someone else shared it
And I saved it
In future, I made a robust physics messages debugging resource that is pinned to this channel
Cause it seem superusefull XD
I tried using it in my program, but nothing is working, what is wrong here?
Vector2.ClampMagnitude(new Vector2(maxRunningSpeed, rb.velocityY), maxRunningSpeed);
rb.AddForce(new Vector2(direction * speed_mid_air, rb.velocity.y));
}
You cannot just start the lane with vector2
Is like starting a statement saying "3"
It is a value, not a variable
I don't get it, how do I use it then?
What you want to do is something like rb.velocity = ClampMagnitude(rb.velocity, maxVelocity);
Or somethin like that
Also why are you using an int for direction?
That seems not very optimal
oh I use that to multiply it with the x velocity to make it go left or right
Yeah, but shouldn't that be at leats a float?
but doesn't that just overwrite this other line rb.AddForce(new Vector2(direction * speed_mid_air, rb.velocity.y));
I don't want the player to slow down or increase the speed, I just want the speed to stay the same
What do you want with that method, I don't get it; you want to Clamp the speed and allow for movement in the air?
so basically there is no diffrence between making it a float or not
alr, so I want to let the player move a little mid air, but I need to clamp the max horizontal speed so that the player doesn't move too fast mid air.
I have tried to use if statements, but I had problems with that, so someone here suggested me to use Vector2.ClampMagnitude
Why would you want to clamp the speed just in mid air and not on the ground?
yea I was going to do that after clamping the max speed on ground
I do need to know how to apply it before using it on other things
Just clamp the velocity overall and apply the clamped value directly to the rb velocity instead of adding force
oh yea that sounds that it is better, but there might be a problem, setting it to rb velocity will get overwriten by the other movements.
im tryna practice my coding basics with c# and made a rock paper scissors game. It works perfectly fine but I can't seem to get the part of the code which allows the user to play again to work. Please let me know if you can help.
I have had a similar experience with that before, it is like setting a value to a 3, and on the same function you set it to a 4, so the final value will be a 4
I mean, clamping the max velocity should be the last step of all the calculations; should be overriden by anything
Seems like in your case just loading the whole scene would work for you
lol
it loads but when it gets to that one part it doesnt work and idk y
Load again, when you want to do another game
I'm trying to access a public vector2 from a prefab script into another script but it always comes out to be (0, 0) even though I have it log the vector2 in the original script. I'm using this tutorial as my main reference (although I have done a lot of Googling as well) https://www.youtube.com/watch?v=JJUnufMLUp0
//Here's the relevant function on the Tile script:
void OnMouseDown()
{
var x = transform.position.x;
var y = transform.position.y;
selectedTile = new Vector2(x, y);
Debug.Log(selectedTile);
OnTileClicked.Invoke();
}
//And here's the GenerateObject script:
using UnityEngine;
public class GenerateObject : MonoBehaviour
{
public Tile script;
void Start()
{
// Iterate through all tiles in the grid and subscribe to their OnTileClicked event
Tile[] tiles = GameObject.FindObjectsOfType<Tile>();
foreach (Tile tile in tiles)
{
tile.OnTileClicked.AddListener(HandleTileClicked);
}
}
void HandleTileClicked()
{
Debug.Log(script.GetComponent<Tile>().selectedTile);
}
}
Hello, I want to load characters data from a JSON, and I have some character images separated as moods (angry, sad, happy, etc) how can I load the character expressions based on a MOOD variable and the character data?
put them in a dictionary
e.g.
Dictionary<Mood, Sprite>```
you can can just do mySpriteRenderer.sprite = myDictionary[currentMood];
and how do I populate the dictionary?
in Awake
iterate over your json data
foreach (MoodInfo mi in moodInfos) {
myDictionary[mi.mood] = mi.sprite;
}```
would be ideal
can we manually play an animation clip via code without sending to animator?
assuming you structure your json well
you need an Animation or Animator component
ooh didnt know there's this animation thing, thanks
that's more playable
isnt there an animation thing that is already deprecated on new unities?
forgot what though
or that was an audio thing, dunno
Yes it's called Animation
whoa, what a component
I am using a World Space Canvas to show some floating text, I want to save it as a prefab and it has a general script that just makes it look at something, in this case that would be the camera. When assigning the main camera to the object to follow on the inspector it works as expected, but when I save it as a prefab I cannot assing anything that is not directly on the prefab itself as a gameObject to follow. Do I have to make a reference to it directly in the script for it to work as a prefab? Cause that seems really inconvinient for scripts like these
If I drag the component from the scene to the editor's reference it says "Type missmatch"; which doesn't show when the prefab is in scene and I assing it there
you have to assign the references at runtime, in your code
assets (prefabs are assets) cannot reference objects inside scenes.
Simple example:
[SerializeField]
MyCanvasScript myPrefab; // assign in the inspector to the prefab
[SerializeField]
Camera mainCamera; // assign in the inspector to the camera
void SpawnCanvas() {
MyCanvasScript myInstance = Instantiate(myPrefab);
myPrefab.cameraRef = mainCamera;
}```
This would be the code that spawns the floating text thing
What was it supposed to be?
I'm trying to access the selectedTile variable in a different script
Looks fine. What's it supposed to be rather than (0, 0)?
That seems really inconvinient, but ok
You don't need to call GetComponent for the referenced Tile btw
It's supposed to be the vector2 of (transform.position.x, transform.position.y)
it wouldn't make any sense otherwise. What would happen if you assigned a reference on a prefab to an object in a scene, and then spawned that prefab in a different scene??
it's really very simple
Mainly cause the script itself set the object to follow as the player of it is null, which means, now it would be changing the value twice for no real reason
Did you perhaps reference the wrong object?
once you get the hang of passing references around it will be second nature to you
Maybe show us the inspector for that component?
Then it would say that there is a missing reference, not that I just cannot assing it
well, it doesn't work that way
get used to dealing with references in your code
I mean assingining a value on the isnpector is not equivalent of doing something like... GetComponent<>;?
no
Why would it work differently?
it is not
because it's a direct reference to an object
that object has to exist to be able to reference it
It has the tile game object attached to it
Also imagine if you loaded the same scene twice (which you can do, no problem, with additive scene loading). Then which copy of the object would it reference?
When you think about it, what you want doesn't make any sense unfortunately
The same as getComponents, if there are none is a nullReference, if there is multiple just the first one it catches
Don't get why it would be coded differently
That would lead to bugs. Anyway IDK why you're debating me about it. I didn't design the system, I'm just telling you how it works and how to make your code work
Yep, thxs, just though was kinda unecessarely restrictive
still dont get how to "choose" the images from the folder, that's the part I dont get
Did you reference the prefab Tile or an instance in scene?
The prefab would just be a reference to your asset in your asset folder and not something in the scene/hierarchy.
To be clear, you can assign (as a prefab overload) to an instance of a prefab that is already in the scene.
Only for instantiated objects do you need to assign from another reference already in the scene
I want to load to load it by code
Try changing the log tocs Debug.Log($"{script.selectedTile}", script);
Click the log in the console during runtime and see which object is highlighted yellow.
[SerializeField]
Sprite sadSprite;
[SerializeField]
Sprite happySprite;
void Awake() {
myDict[Mood.Sad] = sadSprite;
myDict[Mood.Happy] = happySprite;
}```
Then you do the "choosing" in the inspector.
It references the prefab using the variable in its script
How so?
You may want to drag your console windows out and have it place next to your assets or something to have it visible during the selection
How can I do a prefab overload?
If the prefab is in the scene, just drag a reference into that instance
So it's referring to the prefab at (0, 0) and not the selected Tile object in scene then.
It makes sense by design, as prefabs are unrelated to any specific scene. It would also be more difficult to serialize the reference to something that is stored inside a scene file.
I'm not sure how to make a public variable that each instance can interact with, although the variable does work within the script
Good day everyone, PLEASE HELP! Can anyone point me towards a good direction. I would like to create knitcap for a snowman but I don't know and I didn't find a resource that teaches how to do it. Thank you for any advice.
But I can't save it with that refernece, it is just lost along the way
A good start would be to reference these tiles as you create them.
Yep. Can't do that. Refer to my previous reply for some of the reasons why.
the problem is that I have a List of Lists
client1 [ client1_sad, client1_angry, client1_happy]
client2 [ client2_sad, client2_angry, client2_happy]
...
clientN [ clientN_sad, clientN_angry, clientN_happy]
Oh welp, it is what it is
im looking for an option that doesnt work with the inspector
I have a dictionary variable, but it's in a GridManager script. Could I make that public to access it in the Tile script?
Why is that a problem?
that's the thing i wanna use 
(anyways, not deprecated for me means it's still good to use 😁)
Then use Resources.Load or Addressables
it doesn't change the basic idea
I don't really see what benefit you have from avoiding the inspector though
its only there for backwards compatibilty.. it is still deprecated
i guess its still okay to use.. || learn the animator, though||
alright ill try that, thankx
You'd do so when you instantiate or reference them with your manager.
An example for when they're instantiated:cs var tile = Instantiate(tilePrefab); tile.OnTileClicked.AddListener(HandleTileClicked);``````cs void HandleTileClicked(Tile tile) { Debug.Log(tile.selectedTile); }``````cs OnTileClicked.Invoke(this);*Implies you've got an event/action that has one parameter of the type Tile.
!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.
I'm confused as to how HandleTileClicked can have a parameter, since it tells me it's a function when I add a parameter. I'm also not entirely sure where all of these scripts are supposed to go, since my event listener is in a different script to my instantiation script.
Hello, how can I change a texture from a gameObject?
Texture2D newTexture = Resources.Load<Texture2D>("pixi");
gameObject.GetComponent<SpriteRenderer>().sprite = // what to put here using "newTexture"?
Create a Sprite from the texture
Why not just load it as a Sprite to begin with?
Don't make life harder for yourself
how to do that?

Sprite newSprite = Resources.Load<Sprite>("pixi");```
Ohh thanks
(and make sure you actually imported the image as a sprite)
I just tried to display the destination of NavMeshAgent, but the Ray seems to draw wrong positions. How to solve this?
(In the screenshot, the agent is going to (-3,0,-4) but ray points at opposite way)
here's the code -
IEnumerator NormalMove(Vector3 vector)
{
navMeshAgent.isStopped = false;
animator.SetTrigger("IdleToWork");
navMeshAgent.SetDestination(vector);
Debug.Log(vector);
while (true)
{
yield return new WaitForSeconds(0.1f);
if (Vector3.Distance(transform.position, vector) < 0.001f)
{
Debug.Log("Reached");
transform.position = vector;
animator.SetTrigger("IdleToWork");
break;
}
else
{
Debug.DrawRay(transform.position, vector, Color.red, 0.1f);
//Debug.Log(Vector3.Distance(transform.position, vector));
}
}
navMeshAgent.isStopped = true;
navMeshAgent.velocity = Vector3.zero;
}
oh shit wait it was (-3,0,-4) but anyways it is wrong
it worked, thank you uwu
When the green wall is placed, I need it to recognize which of the red lines have walls and which don't. I've been trying to do this for awhile but I'm drawing a blank
I already have blank walls on the red lines without non-rendering walls that have hitboxes for raycasts but I have no clue how to actually detect them aside from comparing coordinates which seems unreliable at best
and I also want to avoid iterating through a list of every single blank/not blank wall because that will have issues scaling
I wouldn't use physics here. Is this grid-based? I would maintain a graph data structure of the grid spaces and edges
it is grid based and there are no physics applied. What is the best way to encode the grid?
would each wall have its own list stating which walls are adjacent or is there one grand list that has all walls with there adjacencies?
Does a function exist that draws a line between two points?
Debug.DrawLine()
more like each box in the grid knows which edges it has and the neighboring grid boxes, and each edge knows which grid box it's part of.
Thanks
The LineRenderer component.
Good evening all. I've been messing Unity for a few days now. Dabbling in making my own game. It's coming along but one frustration I can't overcome is my objects overlap no matter what I try. I've made a completely new 2D project with 2 simple objects. Both with rigidbody2d and box collider and I control one of them into the other and they overlap. I've watched tutorials and in 5 minutes they make a platform jumper. My "Player" just falls through the floor. What am I missing?
Probably the basics of Rigidbody motion.
Make sure you're following all the steps of your tutorials
But if I follow a tutorial exactly as they do it and it falls through the floor. I'm just confused as to why
and that would just be stored in a list? I'm missing how that is abstracted
Don't skip or change anything the first time through
no... an adjacency list
to be honest this is not really a beginner topic so if you're new to programming it's going to be difficult.
is an adjacency list completely separate list syntaxwise from a normal list or is it just an application of a list?
I'll try one more time
not completely new... just rather new to unity and C#/dotnet
It is a completely different data structure
oh ok
in practical terms it could just be a List<GraphNode> where each GraphNode has a List<GraphNode> representing its neighbors
and I assume I would have one master list as a static element of some class?
but you have to understand graphs and graph algorithms to do this effectively
implementation details, up to you
alright makes sense, that's probably how I'll wind up doing it
VS isn't showing GraphNode as being a thing in unity, do I have to add a new using statement?
It's not a thing
it was an example class name I made up
ah that makes sense
I'm having trouble getting my game to register my left mouse button to fire projectiles and I can't seem to figure out why.
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ProjectileGun : MonoBehaviour
{
[Header("References")]
public Camera protagCamera;
public Transform attackPoint;
[Header("Projectile Info")]
public GameObject projectile;
public float shootForce;
[Header("Gun Info")]
public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
public int magazineSize, bulletsPerTap;
public bool allowButtonHold;
[Header("Keybinds")]
public KeyCode reloadKey = KeyCode.R;
public KeyCode fireButton = KeyCode.Mouse0;
// private variables
int bulletsLeft, bulletsShot;
bool shooting, readyToShoot, reloading;
[HideInInspector] public bool allowInvoke = true;
private void Awake()
{
bulletsLeft = magazineSize;
readyToShoot = true;
}
private void FixedUpdate()
{
MyInput();
}
private void MyInput()
{
if (allowButtonHold) shooting = Input.GetKey(fireButton);
else shooting = Input.GetKeyDown(fireButton);
if (Input.GetKeyDown(fireButton)) Debug.Log("Button Pressed");
if (Input.GetKeyDown(reloadKey) && bulletsLeft < magazineSize && !reloading) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
{
Debug.Log("Shoot Function Called");
bulletsShot = 0;
Shoot();
}
}
private void Shoot()
{
readyToShoot = false;
//Find the Hit Position using Raycast
Ray ray = protagCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
RaycastHit hit;
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75);
// Calculate direction from attackPoint to targetPoint
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
// Random spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
float z = Random.Range(-spread, spread);
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, z);
// Creating projectile
GameObject currentBullet = Instantiate(projectile, attackPoint.position, Quaternion.identity);
currentBullet.transform.forward = directionWithSpread.normalized;
// Adding force to projectile.
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
//currentBullet.GetComponent<Rigidbody>().AddForce(protagCamera.transform.up * upwardForce, ForceMode.Impulse);
bulletsLeft--;
bulletsShot++;
if (allowInvoke)
{
Invoke(nameof(ResetShot), timeBetweenShooting);
allowInvoke = false;
}
if (bulletsShot < bulletsPerTap)
Invoke(nameof(Shoot), timeBetweenShots);
}
private void ResetShot()
{
readyToShoot = true;
allowInvoke = true;
}
private void Reload()
{
reloading = true;
Invoke(nameof(ReloadFinished), reloadTime);
}
private void ReloadFinished()
{
bulletsLeft = magazineSize;
reloading = false;
}
}
When I change the fire button to my F key it works just fine, but for some reson it won't register a click on Mouse0
You're trying to handle input in FixedUpdate
input should only be handled in Update
Also if you move this handling code to Update you will need to make a few other small adjustments
well I've changed it from FixedUpdate() to Update() and it still doesn't seem to be registering a left click. what else should be changed?
hi, im trying to implement a MouseLook script for my Main Camera, in order to look around using the mouse in a 3D game. Is there documentation to go over how to do that with the new input system? Every tutorial/documentation doesnt go over the basics or what each block of code means
Also each vid goes over the old input method. Brackeys and other popular utubers just gloss over any relevant info
You'd just have a switch statement (or a delegate dictionary can work too) on the SO that provides you a way to pick the dialogue depending on the game's settings, so this should allow you keep it at 1 SO per npc.
I'm confused as to how
HandleTileClickedcan have a parameter, since it tells me it's a function when I add a parameter.
Functions can have parameters but I'm guessing you did not declare your event/action to accept functions with a parameter type.
I'm also not entirely sure where all of these scripts are supposed to go, since my event listener is in a different script to my instantiation script.
It's practically your code so you ought to be able to recognize most of it: #💻┃code-beginner message 🤷♂️..
Here would be an example using plain c# that adds a listener with a parameter to another class (Echo) and have a manager (Cave) broadcast the messages without knowing the underlying implementation https://dotnetfiddle.net/OYrVn9 (main defined the functions, echo referenced the function and cave manages echos).
In your case, you'd just need to change the declaration of your event/action to accept a parameter so you could pass the Tile data to the function to be printed to the console when the tile is clicked. Printing the position value of the prefab is what I'm assuming you're not wanting from your original code post.
I have an idea, but id just like confirmation/ a second opinion on how to do this with OnTriggerEnter instead of CollisionEnter
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == ("Bullet"))
{
Debug.Log("Collision Found");
}
}
At minimum, both gameobjects need colliders, one at least needs IsTrigger on the colliders, and at least one gameobject needs a rigidbody (can be kinematic)
i know how to do an OnTriggerEnter
i want to know how to check the name of the enterer
oh ok. is there a way to like, not have that per NPC though? like i said its personality types and there will be a lot of randomly generated NPCs, cant they all just inherit or reference the same object?
should be similar but instead of a collision object you get the object's collider instead but you can still get the gameobject from both
so instead of if(collision.gameObject...)
i just do if (collider.gameObject... )?
if you're randomly generating npcs then you can make a script that picks from a pool, sorted by personality types and whatnot.
ooh
ive always wondered about random picker things
https://docs.unity3d.com/ScriptReference/Collider.html
Can also check the properties and methods of an object in the documentations
ill have a look and try something, and come back if theres further errors
but as you should know, the collider is a component, and if it's a component then it must inherit from mono, meaning it will always have a gameobject property
and transform for that matter
Collision object on the otherhand is not a component, but an object generated by colliding, but it has properties referring to the gameobject's properties
right
oh yeah
documentations are your friend
thats right;
they are
i use them alot
ok
one last question (for now)
actually ill google it first
If your handling input through Update, you should be able to follow any tutorial for mouse look, and replace the old input checks for Mouse.current or setup delta in an input action asset, and reference it, you could also refer to the "how do I?" page which may help: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/HowDoI.html
This approach, would be polling in Update rather than using events of the input system, for a mouselook, it should be a fine approach
not my original question, but how do i make children of an object not match the scale of their parent object
you dont usually as you should consider making those siblings if needed instead
don't make it a direct child, but instead use another gameobject to wrap them
not so much new, as unexperienced
do you mind providing an example
your implementation: parent -> child
my suggestion:
another gameobject ->
gameobject1 (previous parent)
gameobject2 (previous child)
isnt that childing
oh
so have it 3 layers deep
like
Parent>Obj1>Obj2
or is it
Parent>Obj1 + Obj2
right, if you're going to scale and don't want the children to scale, then don't directly add children to those objects
2nd one.. u dont want to nest more than u need to..
if it makes sense to go
- parent
- child
- child
- child
then sure
The Shape module defines the surface from which particles are emitted and can drastically change the appearance of your particle effect. All the shapes have properties that define their dimensions, except for Mesh, which will follow the details of the mesh you select. In this tutorial, we’ll explore the options in the Shape module.
oh
its literally an option right there
guess i didnt look hard enough
oh
you have to click on it after you enable it
hello! ive imported Mirror and done all the steps, i can connect locally and such, but the tutorial says i should tick Client Authority, but in the network transform there's no client authority anymore....
how do i put authority on the player prefab?
main problem is one player can manipulate all the characters at once so... what can i do?
Unity 2022.3.2f1
Should ask up in the Mirror discord, otherwise try #archived-networking
but usually if it's a specific library, you'd probably get more help in its related communities cause not everyone uses Mirror
ive made a script and its not creating errors, but it isnt working
public GameObject BoxObj;
public GameObject BoxPref;
void Update()
{
if(BoxObj == null)
{
GameObject newBox = Instantiate(BoxPref, this.transform.position + new Vector3(-1, 0, 0), this.transform.rotation);
}
}
any ideas?
"it isn't working"
how are we supposed to know what isnt working exactly
and what is the desired behaviour
because this code doesn't make sense
you are checking if BoxObj is null
then you are trying to spawn null object edit: nevermind
did you debug log it?
to see if it's being called?
where are you assigning BoxObj?
its not
so theres the issue
not being called, that is
yup
yes
do you know what to do?
if(BoxObj == null) this is not true
so it doesn't enter that if, so it doesnt spawn the thing you want to spawn
yes that!
quest systems are very broad topic
depends on the design you want to achieve
there is plenty of tutorials on that
you can make it based on ScriptableObject, interfaces etc
do you know of another way of calling the if
what do you mean by calling the if, you are not calling it
signalling it
you know?
its on the tip of my tongue
"calling" is the only verb i can think of right now
thank you
jesus
i know 🥲🥲
and i noticed
the funny fact is when i do ctrl+z the error is gone . but i just rewrite the function name nothing more and it make it to what was befor then the error gone like poff
oh
i just realised you wrote the mesage
ohhhhhhhhhh
REFERENCE
thats it
i mean referencing the if
do you know another way of referencing the if
you cannot reference if
damn
do you know what a reference is?
sort of
doesnt look like you do
let me get it
{
GetTheCheese();
}
that would reference GetTheCheese
every.
frame.
Not really no
it isnt
Reference is usually referred to well, referencing the variables itself
good news i fixed it and was very lame 🤣🤣🤣🤣
yayyyy
no
i know
that will call GetTheCheese() function every frame
it calls it
you are missing bassic C# terms and knowledge
i wouldnt say mising
i was trying to reply quickly as i dont like keeping people waiting
i didnt think about it
and just
posted the mesage
that is also why i make a lot of typo's
You are most definitely missing the basics, but as long as you're trying to learn them then it's fine. Hopefully you're not just trying to make the next competitive shooter at the same time
i only just learned about (object) == null (only because i didnt require use of that) so i dont know much about (object) == null
i am most certainly not making the next anything
just personal projects
dm me anytime
use SetActive instead of disabling all the renderers
np my man
Could be an issue with duration of animation clip not syncing with the time you're using in script too
Also animation could be looping
also that
oh i see
did you make sure to re-enable them at the start of the anim
Showing clip might help recognise the issue
If your animator is controlling the sprite renderer's active status, it probably cannot be controlled from code
It's possible that blending to an animation that enables the sprite renderer causes it to switch too early, as booleans can't really be blended
Best to use code only for it at first
renderers
yeah i would just have the death in the anim, then use SetActive in a script
I would argue if disabling an object (especially a child object) is part of the animation, it should be done via animation not via script but depends on need i guess
It does depend a lot on the case
If the disabling and enabling matches code conditions very well, it'll be more convenient to do there, as I'd expect dying and respawning to do
If it'd have to closely match the animation keyframes, that'd be hard to approximate in code, for example if blinking in and out during an animation
Exactly , you can forget about which specific point in time you're supposed to enable and disable an object and just worry about when you want to respawn
It's different thing tho if you want to disable object that are not children of animator
i have 2 scenes that i want to toggle between. rather then having 2 scenecan i have one scene with 2 scene?
yh so i have 2 scenes currently one is an arcade the other is a mini game(arcade game) and dont really want to carry all my DDOL to another scene like the player and game manager as they are not needed.
You can use subscenes but it's usually used when the world of a scene is too big, personally I've never used that in my life but you can look it up
and i dont to build the mini game as an ui
use a canvas and ui for the game
why
A minigame can also exist in a prefab if you don't need a whole scene asset for it
Well i could, will all objects work the same, can i use sprite renderer on a ui or will i have to swap things
Whether it's UI or not doesn't make a difference in this case
ok thank you. maybe ill try the UI approach then.
Don't make it UI if you don't need it to be UI
Canvas is a component like any other, it's not concerned with how it's loaded in or out
So look into additive scenes and prefabs and decide which suits you better
awesome thank you
Had an intern make 200 scenes for different levels in the game, i internally cringed so hard
one scene all I need
Prefabs all the way babyy
That's not inherently bad, if there were 200 levels anyway
Scenes and prefabs have very few practical differences
But imagine trying to figure out why scene 130-150-160 crash, while others working just fine
Turns out you just disabled a game object in scene that's enabled in every single scene but since you made duplicates of scene there's no way to confirm every single element is exactly same except for the "new level"
Needless duplication is definitely a mistake, but scenes themselves don't require it
You'll want to reuse prefabs within them anyway
Exactly
Which surprise surprise, intern didn't
Every single scene was duplicate, and levels weren't prefab
The nice thing about scenes is that there's the built in method to load them asynchronously, unlike prefabs, but the drawback is that you can't offset or rotate them if that's required
Wait wut
Offset/rotate?
If you need to build say, a labyrinth from modular rooms, it's practical to have room prefabs and instantiate them at every connection point
But as far as I can tell scenes even when loaded additively can only be in the position they were originally created in
Unless you make an extra parent for all the objects in it and move that, but that's worth the trouble only in rare occasions
Ahhh got it
public GameObject BoxObj;
public GameObject BoxPref;
public bool _Summoned = false;
void FixedUpdate()
{
GameObject go = GameObject.Find("Box");
if (go) {
Debug.Log(go.name);
} else {
_Summoned = true;
}
if (_Summoned)
{
GameObject newBox = Instantiate(BoxPref, this.transform.position + new Vector3(-1, 0, 0), this.transform.rotation);
_Summoned = false;
}
}``` im trying to sset the bool to false so the cubes stop spawning but they wont stop when they start
Definitely desync between "respawn"/enable object
jezus christ
When are you enabling your character again?
why are you doing such things in FixedUpdate
wait yeah
If your animation event is used for respawn, try moving it one or two frames earlier
let me rearrange some thuings
doing any Find-type methods every frame is terrible
Like we said, stick only to animation or code for the enabling/disabling, not both
Find() in general is giving me goosebumps
Copycat
i was replying to you xd
Ahh my bad xd
i need it to constantly check
I see in your animation clip at 1:15 (or end) you're doing something to your sprite renderer, what is it? Spill the beans
why are you doing Thread.Sleep
it's not a good idea
make it a coroutine
IEnumerator
Look up "coroutines" in unity, pretty damn handy tools
also you can extend that code by firing OnDeath event
Most used things after if and loops for me
public UnityEvent OnDeath;
public void Death()
{
//your code
OnDeath?.Invoke();
}
then you can subscribe to that events via inspector (like in button's OnClick)
I would rather have that method be fired inside animation as event 
still can do both
No need to check for delays and all
if he wants to for some reason
but yea it's better to keep things in animation timeline
to be more precise
for example making footstep sounds, its much better to do it in animation events
instead of playing with delays lol
Yea
no, what made you think that
public UnityEvent OnDeath;
write this in your script
then in your Death() method add this
OnDeath?.Invoke();
you will see that you can assign stuff in the inspector
and they will be called when the event has invoked
disable objects, enable objects, call methods from other components etc
idk if im not going to "deep", this might be kinda confusing to you at this level
Events may not be the easiest subject to grasp as beginner 
they are not hard at all, but if you are just beggining then they might be, hard to say 😄
Me personally learnt to use them after 1 year of practicing lol, and still haven't found good use for them in the games we make
at the end preferably
there is a common mistake of people firing the event, before actually doing "stuff"
like for example you have event OnDamageTaken
but you call it before calling the TakeDamage() method from healthsystem
and imagine you have healthbar assigned to that event
what do you suggest
and it's not updating properly
i wanted it to constantly be watching for the destroy
Caching it in a variable
And check if variable is null
use events
ill try iy
never done events before
with instantiating in Update
im more confident with variables
Or yeah, use On destroy call back on the game object
make it proper way
@tepid summit what are you trying to do exactly???
dw, ive got it
i dont understand what do you mean
you are calling OnDeath event in your Death method
now you can subscribe things to that event
via inspector/or code
Lemme break it down for you
-> you touch spike
-> you call death method
Death{
Runs animation
OnDeath?.invoke()
}
MethodSubscribedtoOnDeath()
{
Wait until sprite is disabled
Respawn after x seconds
}
you should really watch some basic tutorials
on animations and animation events
right now it's impoosible for you to understand what are we saiyng
Actually yknow what let's scrap the topic and start from scratch,
Where are you enabling the sprite from?
Is it only in the script or any other animation is enabling it too?
Shouldn't do both
Ok so at start of death animation sprite is being enabled
Death animation lasts 1:15 and it's not looped
You're starting animation and death function at the same time
Death function re enables sprite after 0.5 second correct?
pointless
why
Don't do it that way so then you won't "need to"
Either the animation or the code should be responsible for that, otherwise you'll have an awful time troubleshooting
guys should i learn coding while making a game? or without?
whats more efficient
i wanna learn game development
Depends on what level of coding do you know
it is up to you. it's typically easier to learn c# without also learning the unity engine at the same time. and most unity tutorials don't really cover the more intermediate topics of c#
i know how to use assets and that in unity but i cant really code
yea true
Well I would recommend beginner level c# courses on YouTube
ight
is it easy to learn C
C# without knowing maybe C
or python or any other language
you do not need to learn C in order to learn c#. do not go and learn one language for the sole purpose of then switching to another language to learn
Learning C# in todays world is easier than learning C.
ight yea some people told me to first learn idk python then java then C and C#
but i think
Nah
python and java are pretty boring
c# better starting point
Yeah no
alright
this is incredibly stupid advice
Stick to one language until you actually understand the concept of programming (efficiently)
To be honest, if you learn one, learning the others will be easy.
Beginners often struggle with syntax.
python is a little more intermediate I'd say because syntax is less verbose
yea imma try c# then
i just really wanna learn C# and C++ in my career
thats the 2 that i wanna be good at
is there a way to reference my specific scriptableobjects from other scripts? i cant find a way to do it anywhere
https://unity.huh.how/references
specifically the Serialized references part if it is an SO asset
I would recommend c# over c++ as c# is easier to understand overall , atleast as first language
if you learn the basics of vars,for,foreach,whiles and functions. you can pick up any language. the syntax is not the issue. its the thinking process. you can always google syntax.
alright thanks for the help again
imma stick to it

i think of it like this. say the problem was i had a hundred objects and i need to make sure each of them had a name. then the code break down would be i need an array and a for loop. then google the syntax
this is easy to say as someone who isn't just starting out with programming. let the complete beginner learn a specific language and how to code in general before suggesting they just learn little bits of a language because syntax can be googled
Problem solving skills are developed after you learn the programming core concepts, not right out the gate
this is also good
I think giving suggestions is nothing bad, just depends on the type of suggestion.
As an example, someone who never learnt any programming language.. why would you tell him to start with C instead of C#?
Those guys will get frustrated fast
Like in C# he doesn't have to deal with pointers, he can easily do mistakes and IDE/compiler will tell him
well you say that but for me to become a web developer and get on a course i didnt have to learn the code it was how i break it down. that's how i was excepted
But "Learn Python first then Java" is a really stupid advice.
You can't really expect people to know (Google) how to make a chocolate castle when they don't even know how to melt a chocolate yet
On the other hand, who knows Java well, almost knows C# well.
nothing there explains how to reference a specific scriptable object in particular, it's all just guides of how to reference gameobjects
use a serialized reference
Game object is a type of class
Scriptable object is also a type of class 👀
I try, but how can I do that if i need to refernece the editor class used to create the scriptableobject but i can't because it's in an editor foolder because it needs to be?
anything you expect to use at runtime should not be inside an Editor folder
on account of anything being inside the Editor folder will be included in the Editor assembly which is not included in a build
It's the script to create the scriptableobject, i just need to reference the this specific scriptableobject itself
As a Java developer for years, C# felt so weird in the first couple of weeks. Especially the naming conventions in C# such as using "Dictionary" instead of "Map"
make your variable the same type as the scriptable object then just drag your scriptable object into the slot in the inspector. that's literally it
of course the ScriptableObject's script must not be in an Editor folder otherwise its type will not exist in a build
What is it?
The class names are different, yeah. However, they are very similar in terms of functionality and the syntax of Java and C# is almost exactly the same. (There are small differences which are also version-related)
Yeah that's my problem then, but how do i make it in the first place if it's script isn't in the editor folder therefore i cannot create it using the editor
You can create scriptable objects without having the script stay in editor folder
huh? you don't need to put it in an editor folder just to create an instance in the editor. the editor folder should only contain things that belong in the editor assembly and will not be included in a build
Guys I have a problem with my animation and I was wondering if I can use a script to fix it.
I made a shotgun empty animation where the shell flies off the barrel when you cock it. The problem is, when I transition the animation back to the idle animation, the shell flies back into the barrel. I think what might be a good solution is something to do with scripting the bullet to stay invisible during the transition back, or something like that. I'm relatively new with Unity animations so help please (I can't provide a video in the meantime)
this seems like an #🏃┃animation issue
but you also have another keyframe way past that circled bit
oh ok thanks. i swear i learned that somewhere. im still new to unity so this is driving me crazy sometimes
1:13 is doing what?
You can use a particle system to emit the shells
i'd bet the issue is exit time on the transitions. of course that still isn't a code issue.
@cunning rapids Play it with an animation event
The shell is a physical object
I would put dots at 2:00 same frame with "teleport" player so sprite is enabled as soon as teleport happens
Instantiate it or use a particle system
Doesnt make sense to recycle one shell casing
I'm using the animation tab, how can I make an instance during that?
ah yes, "buggy somehow" is super descriptive. this still doesn't seem like a code issue though and this is a code channel.
Why not? It's entire purpose is to be an animation prop
I don't actually shoot out the shell
after a while of falling, the speed resets for some reason. is this a problem with unity or could it be a part of a script
probably your code. it seems to happen as you pass platforms
Making it invisible while it moves back is also a valid option
ok
Maybe in code somewhere you reset the speed to 0
Oh God I can't believe I didn't think of that. Thanks
I know you suggested it...
Why are you asking if you have a solution
I suggested it making it invisible DURING the transition, not setting the position back in the animation
But that was a pretty stupid suggestion, the latter of them is better
Oh I thought you were being sarcastic at first lol
@cunning rapids Animation events can be useful for that
Though they can be finicky with transitions too sometimes
I believe they fire off if the animation has any influence at all as part of the transition at the event's time
That's the main problem with transitions tho, they completely ignore the final state of objects in the animation
Yeah, though if your method uses AnimationEvent as a parameter, you can check the event's animationClip's weight
To avoid events firing off at say, 0.1 weight
I use an animator and the Play() method
Which is probably set for problem is the future since I can't set any conditions in the future
I think you need an animation trigger for that
Although I could be speaking nonsense since I haven't used the Unity animation system in a while
If you hide the shell while it is moving back, you dont even need to call a method, just animate the enabled toggle of the renderer (or gameobject)
Yeah that makes sense
True, Play() method is not the intended way, rather setting parameters is
Anyways, thanks for your help guys :)
Yeah dont think I ever used Play
Yeah I always see people use parameters and then play using SetTrigger()
Man I kinda wanna get Animancer.
Mecanim seems so restricted
Animator gives you a lot of power to automate things, but that's kinda the only efficient way to use it
And even if you optimize the need of transitions to a minimum, they're still a lot of clicking to make
Are those some plugins I'm unaware of?
Most people don't care about animator state machines (and don't realise they actually need them)
I thought they were some anime website
Animancer is an asset, has a free and pro version. Mecanim is the builtin unity animation system. It used to be an asset
Felt so lost
Based on the context of the discussion it would be a little odd to suddenly switch to anime
That's why felt so lost lmao
Mecanim used to be an asset?
How long ago?
Idk I think I started with Unity 5 and it was integrated into unity then
So yeah a long time ago
Tbf it's more than enough for most indie devs. I mean just the fact you can change the animation tangent is good enough for me
Yeah, my animations are just getting a bit too complex to manage
Thinking of building a custom layer on top of mecanim to support different crossfades, regional "events" etc.
But maybe Animancer can do all that
For more complex animations like walking you can just use procedural, no?
I do use procedural stuff for foot placement etc.
It's just not as efficient or good looking if you only have procedural animation
How so?
Well you have way more artistic control when you hand animate things
var rClouds = _clouds.GetComponent<SpriteRenderer>();
_xClouds = rClouds.sprite.rect.width;```
I have images that are tiled, I want to get their size on X axys without taking the tiled repetitions.
That's true but it's brutally long and complex to animate by hand
I want to move them X amount of spaces before teleporting them back when they reach the border
bounds.size.x?
Wont this give me entire image size?
No, its tiled so moving the entire image will move the tiled no?
It will instead return the actual size of the sprite in thr world space rather than counting tiling
_xClouds = rClouds.bounds.size.x;```
Like this
Welp lets see what it gives me
Try it, maybe it's what you're looking for
Great it gives me NoReff because serialize field for some reason broke
Yeah evrything has it just does not count it as serialized
Give more details of the code
I have deleted and saved it again and now its working after I added it again
Oh alright
Great now all of them unlinked
Dude
I hate unity
Just... give more details
That's strange
2D isn't my field of expertise so idk what's going on here
this warning is because you are not assigning it anywhere in code. this is normal because visual studio does not know that you've assigned a reference in the inspector for one of your objects
Hell, I'd argue Unity isn't my area of expertise
Not exactly a brilliant programmer
is _skybox a local variable now? we don't use = in c sharp?
also stop using GameObject variables. use the component you actually care about
no, it is still a class level variable. it's just private and not serialized. local variables are declared within methods
I will need them later to use transform on them
If you want to set a sky box in a scene just change it in the Lighting tab
No need for a script unless you want to periodically change it
you do not need to reference the GameObject to get its transform
use the type of component you actually need access to in your code
public Transform object;
?
sure if you only need to use the Transform. otherwise use the actual component you care about. every component has a reference to its transform
I just want to set a local variable
like var asdadas = 3;
do you know what is a local variable?
in gamemaker i used them
so this is a script then?
what?
void Update()
{
int variable;
}
this is a local variable
int variable;
void Update()
{
}
this isnt
is c# the best for game development?
why is that
Depends on the game you're aiming for
Minecraft was coded in Java
Java script is yhe best
preferences, project needs
Tf2 in Python and C++
skill
i mean if you wanna ride off road probably not but if you like fast cars its good
exactly the same with gamedev coding language 😉
and one last question and im going. we set a local variable in unity then is it the same logic as in gamemaker that you cant use it outside of that code block?
you can try it and see yourself
that is the purpose of doing a LOCAL variable
so its only available LOCALY
well Im asking because in gamemaker you could use a local variable
outside of the code block
by using scripts
Don't referenced private vars also act as local variables or am I just stupid?
local variables aren't engine specific things
It exists only inside the code block {}
they dont, read what is a local variable
i jus dont understand for what game i need what language you know i just wanna do maybe like a simple game where you can drive cars around a map
i'd start with C# begginre course and Unity after
C++ might be more complex to start with, with header files, pointers etc
okay
where can i find it
on yt?

Making cars in Unity isn't a simple task lmao
Check the pina on this channel
depends
simple racing game is easy to make
i already did it once i jsut downloaded assets
realistic car behaviour? nope
but it had many bugs
go for it then
Wheel colliders and setting the different physics properties of your car can be gruelling for a beginner
Such as myself
he doesnt need to use such things
If it is simple then why did you have many bugs
if he wants to make just a simple game
yea that was the problem my car wouldnt stop and it bugged when driving into like rocks
it feel across the map
but for the first projects
you might wnat to do something easier
like pong game or sth
never said its simple
i said
i want to make a simple one
not a complicated one with realistic driving physique
Unity is overkill for pong tbh
why is that?
ight
weird statement
you can learn how components works, how to make proper connection/references between scrvipts etc by making pong
Learn basic programming structure, terminology, and syntax before worrying about other stuff
then you can extend it by making powerups, fancy animations etc
Unity isn't overkill for anything
that's not related
oh ok
You gotta realize that the language doesnt really matter
there is no such thing as "whats better language for X game"
good luck
Yeah but it's a basic gane for unity unless you want to add cool effects later on
Otherwise Python might be a better fit
I'll counter that by saying depending on what you do it does
Because Python is great for more branches of programming when it comes to terms of security or software engineering
We talking games though
but they meant exactly in the game dev context
Performance is probably the biggest difference between languages
C++ is fast but I just love working with C#
Exactly, my point is that some languages are worse than others when making games or other branches
It's possible to implement Python in games, but usually, C-based languages are used in stuff like gane engines
can you tell me whats wrong? when I press play the image I set doesnt apear in game
I think I did everything correct
I dont see any issues myself
it does not
put ChangeSkybox(0); in Start() for example
Does the skybox component exist already or is it added via RequireComponent?
but it starts from zero
I wonder if reqcomp would cause issues
thats why
doubt it, why would it
its built in i guess in unity?
skybox
If it ran after Awake. Idk, I dont see anything wrong here