#๐ปโcode-beginner
1 messages ยท Page 514 of 1
if you're talking about the Client Network Transform that doesn't change how the system fundamentally works, only the movement
oh boy..
A small-scale cooperative game sample built on the new, Unity networking framework to teach developers about creating a similar multiplayer game. - Unity-Technologies/com.unity.multiplayer.samples....
this one
Hi I can't seem to figure out why my OnDrag() method is not working
show code
yes this makes the transform client authorative, it doesn't change how its still server authorative system. Anyway. Haven't worked with physics movement so something you may want to ask on the netcode discord pinned in #archived-networking
nt much we can from here, did you put a collider ? etc..
How do you put Colliders on 2D UI elements?
ohh OnDrag I confused it with Monobehaviour method nvm
do you have an Event System gameobject ?
Ohhh I see, sorry i thought that it is always created automatically and forget about it
tbh that looks pretty hard
what would be performance better, world space ui rotating towards player's camera or screen space ui setting it's position to object's position
Thx anyway then
they're both performance heavy once you start instantiating them
pool them and you should be okay with either one
Overlay iirc is always slightly more performant than world
wdym??
oh nvm this is just 1 UI i wouldn't worry, i was assuming you meant other types of UI like healthbars / texts around your world
just make it how it looks best to you then, don't worry about performance those can be easily localized so its not that much impact
for example I only need 1 world canvas (player is holding interactable tablet to inspect items)
switching it to other data read from SO, but its the same canvas
which lesson is this 
it is a difficult subject, albeit you can still learn it, I was just stating what human fall flat does in accordance to movement.
Essentials > Mission 4 > "More things to try"
If they ever ask me to use GPT again (or any other AI), I think I'll explode
Omg what ๐คฏ
They recommend AI? ๐ซ
I believe there is a better tutorial on unity by Imphenzia IIRC
EXPAND for Time Stamp Links -- This is the most basic Unity tutorial I will ever make. If you are brand new to Unity, or if you want to make sure youโve covered the basics, and if you want to learn how to write your first C# script - this is the video for you!
Over the course of 2 hours, I go through the User Interface, Game Objects, Transforms...
Most fun part is they recommend ai to generate a script that slowly rotates directional light
For experts. IG expert would waste more time chatting with ai than writing such script
instead of talking to an ai just look on google and you will most likely find whatever you need
I believe it's there just as curiosity. On the learn site they should encourage doing everything by yourself
So I'm trying to make something similar to Human Fall Flat without active ragdolls cus it seems to be too hard. Right now I'm trying to make ragdolled player stand up (rotate) by forces. How can I do that?
My scripts:
PlayerMovement: https://hatebin.com/nbbmviywid
PlayerCam & MoveCamera: https://hatebin.com/kdermrhkac
float maxVelocity = 5f;
Rigidbody localRb;
void Start()
{
localRb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float x;
float y;
float z;
x = localRb.position.x;
y = localRb.position.y + 1f;
z = localRb.position.z;
float localY = -1 * (localRb.position.y - (localRb.position.y + 50f));
Debug.Log($"Y to aim: {localY}");
Debug.Log(localRb.velocity.y);
if (localRb.velocity.y < maxVelocity)
{
Debug.Log(localRb.velocity.y);
localRb.AddRelativeForce(0, localY, 0);
}
}
What you're describing sounds exactly like what an active ragdoll is, what do you mean without active ragdolls?
Using existing configurable joints will be the easiest as this behaviour is built in, otherwise you'll have to do some quaternion math and have a target rotation. Calculate how far the object should rotate towards that target and then add your torque
how can i check if hitObject contains any script that extends or implements Interactable class
void HandleInteraction() {
if (!canInteract) { interactable = null; return; }
RaycastHit hit;
if (!Physics.Raycast(cameraHolder.position, cameraHolder.forward * interactionDistance, out hit, interactionDistance)) { interactable = null; return; }
GameObject hitObject = hit.collider.gameObject;
Interactable hitInteractable;
if (!hitObject.TryGetComponent<Interactable>(out hitInteractable)) { interactable = null; return; }
interactable = hitInteractable;
if (Input.GetKeyUp(interactable.getInteractionKey())) {
interactable.Interact();
}
}
using TryGetComponent like you're doing now
fr? thanks also should i implements Interactable or extends Interactable
neither, it's inherits Interactable
ohhh thank youu
unless you are asking how to do so, in which case look at the current code and see how you are inheriting MonoBehaviour
okayy, thankss
Implements and extends is java btw, not c#
yeaa i realized that they're both kind of simmilar
also if class Interactable already inherits MonoBehaviour then i should only inherit Interactable in pickable class?
public class Interactable : MonoBehaviour {
}
public class Pickable : Interactable {
}
yes. you can only inherit one class. but when you inherit Interactable you are also inheriting MonoBehaviour because Interactable is a MonoBehaviour
okay thank youu
I don't really know unity much so I'm trying to find a simple way of doing Human Fall Flat character
dumb question, is there a way to hide all the variables from inherited class in the inspector but leave it shown in the inspector for the parent class
why would you be inheriting the class if you don't want access to those?
i want access to those but only in the script, not the inspector
There is no simple way, you either have a ragdoll or you dont
then you'd probably need to create a custom inspector for the inheriting class
i want to make Pickable class to be able to pick things up but don't want to add Interactable script each time to the object and setting the event to pick up the object so i wanted to inherit the class to call picking up the object whenever the interaction is called
hmm okay thanks
can't I just make for now 1 cylinder that aims to get up each time it falls? or something else simple?
so you want Pickable to be an Interactable but you don't want that object to have an Interactable component? then what is the point of actually inheriting Interactable
Sure, but that's wildly different from human fall flat, to the point where you cant even make the same concepts
hmm maybe there's some tutorial with full code and everything?
thats not what i meant, like i want to do something like this but i don't want the variables from Interactable to be shown in the inspector because i'll override them in Pickable
public class Pickable : Interactable
{
public override void Interact() {
if (!this.canInteract) return;
//Pick up here
}
}
you don't override variables.
i just didn't add it yet
right and you can't add that at all because that's not a thing
wdym??
i mean that you do not override variables like i already said. that is not a thing. you just assign a different object to it
so basically i can't override the variables but i can override the methods?
correct. and that is only methods that you explicitly mark as virtual because this isn't java
oh yea ik that, but what do i do with all these variables that i don't use anymore? they're just shown in the inspector, like i can change them but i'll still return something else
why would your class have variables that it does not use
i just wan't to override GetInteractionKey and Interact method so it's always picking up the object with KeyCode.E. I mean it only inherits the class so other scripts can call Interact and show the Interaction UI
Hello, would anyone be able to help me figure this out. I have nodes that I am using for A* pathfinding, I want the NPC's in my game to increase the cost of nodes so they don't get pathed through but when I do that, it breaks their movement (due to the increased costs) is there a smart way to do this? I currently have all the NPC's on a layer and use layers to calculate node costs.
at this point i think you should go through some basic c# courses and general OOP principles. you seem to be treating the language like java but it has a lot of differences from java.
hmm, okay thanks
No not really. This isnt a simple topic at all, there's tutorials out there which will get you setup with configurable joints but honestly the whole thing is very hard. Fine tuning the joints alone is a pain
ok so I shouldn't try the Human Fall Flat idea
๐คทโโ๏ธ if you want to make a game similar to it that's up to you. Im not trying to stop you, it's also not a bad way of experimenting with rbs and joints. It's just really tough to setup and get working how you want. If every part of the object isnt a rb, they wont react in the same way as human fall flat. I've tried the same before, got the joints setup, hand movements, etc, but it was all just so clunky. The walking was horrible too
Then you realize human fall flat is boring alone and it only works cause of multiplayer
!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.
you're also missing the using directive. right click the error in your IDE and use the quick actions to add the correct using directive
if you do not see it in your !IDE then get it configured ๐
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
go through all of the steps to configure it
screenshot your entire IDE window with the solution explorer visible
close visual studio, regenerate the project files, then open it again
no, close it. then regenerate the project files. then open it again.
there is a button to do exactly that in one of the locations you had to do something in when configuring visual studio
did you follow the instructions i just gave you?
or even look at the instructions the bot linked?
great! then go through that and find that regenerate project files button and click it
Do you see a button in this screenshot that says "Regenerate project files"
depends on your keyboard layout
Capital \
there are over a dozen qwerty layouts. it still depends on which one
in us and uk qwerty it is shift+\
using System.Collections.Generic;
using UnityEditor.TerrainTools;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class WaterManager : MonoBehaviour
{
private MeshFilter meshFilter;
private void Awake(){
meshFilter = GetComponent<MeshFilter>();
}
private void Update()
{
Vector3[] vertices = meshFilter.mesh.vertices;
for (int i = 0; i < vertices.Length; i++)
{
vertices[i].y = WaveManager.instance.GetWaveHeight(transform.position.x + vertices[i].x);
}
meshFilter.mesh.vertices = vertices;
meshFilter.mesh.RecalculateNormals();
}
}
what part of this code makes the waves go up and down slightly?
or is there nothing?
Im guessing the part where it loops through every vertex and gets it Y value and changes it to some arbitrary value
so pretty much the code in Update(), what was the premise of this question?
when i set the scale to 1, it fixes the issue
heres the other script which the other script uses the "GetWaveHeight" float
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class WaveManager : MonoBehaviour
{
public static WaveManager instance;
public float amplitude = 1f;
public float length = 2f;
public float speed = 1f;
public float offset = 0f;
private void Awake()
{
if(instance == null){
instance = this;
}
else if (instance != this)
{
Debug.Log("Instance already exists, destroying object!");
Destroy(this);
}
}
private void Update()
{
offset += Time.deltaTime * speed;
}
public float GetWaveHeight(float _x)
{
return amplitude * Mathf.Sin(_x / length + offset);
}
}
what in this code would i have to multiply by 10
in the original code it was intended to just be 1x1
i have changed the size to 10x10
Anyone have any tips how to recalculate pathfinding for dynamically changing node costs for example if the player moves in the way of the path calculated via A* how to tell the AI to calculate a new path
you would just call your pathfinding function again and to the position you want on the grid/navmesh
A* should calculate new paths depending on if the node moves or not anyway
oh sorry I didn't read your message fully, A* should just calculate the path automatically if any of the node costs changes, I don't know if the built in navmesh system in unity does though, it probably does but I have not tested it
Well, start with reading the errors. What's the first error say?
it says im missing a directive or assembly reference, but i feel confused because i was following along with my professor in class 
What type is throwScore
What, specifically, is the error
this is what it says about them
So, what is a throwScore?
You cannot apply indexing with [] to an expression of type IEnumerable.
ohh okay i see
Reading the error explains the error
im sorry i wish i had better answers for you guys. im not sure yet the types all i know is hes trying to teach us how to keep track of the points from throwing a bowling ball at pins
So that would be an int iโm assuming?
What is throwScore supposed to be
what kind of thing
youre probably right
im so sorry im not trying to be stupid i just genuinely have no idea im so sorry
You can't just have no idea what it is, you're the one writing the code
If you literally do not know what type the variable is, why not simply remove it entirely? If it doesn't have a known purpose, it doesn't need to exist
the context of the situation is i watching a recorded class and this is what he was teaching me and i wasnt sure about what it is at all so im just writing what he was giving me, im not sure about everything yet. but while his was working in the recording mine wasnt
then compare your code against theirs and see what's different, and understand that difference
digi reading their pencil to record a mark in the tally
So, instead of trying to think "What did I do differently" try taking this opportunity to learn what code means instead of how to fix this specific failure at reading
So, tell me, what is throwScore
What does it do
why is it there
If it's a recorded class I'm probably not going to get definitive proof, I can't go look at the video. I can just be really, really certain about it
From what youโre saying, itโs likely to be an integer..
You could have player invoke event on movement / position changed ?
Hi guys, long story short I am trying to practice car controllers and mechanics and for some reason, Unity is recognizing forward Input as -1 and backwards input as 1. This is essentially messing up my game because when trying to add audio when reversing / accelerating it is flipping the sounds because it thinks I am reversing when driving forwards. This is not about what keys are being used its about how it effects the scripts and how the game recognizes inputs. I have tried fixing this for a couple hours and even used chat-gpt but nothing can flip these values. Hopefully you guys can help. Btw, sorry if this is a stupid question, I am new to development. Thanks!
To be more clear, I want it so when I drive forward. I want the gas input to = 1 and when reversing I want the gas input to = -1
Input.GetAxisRaw("Vertical");
hows ur audio code look?
even used chat-gpt but nothing can flip these values
this is not saying much ๐คฃ ... chat-gpt is regurgitated junk most often
Thanks for the reply. Quick question, could it be the asset I am using that causes the problem?
Its as if the game thinks the back of the car is the front and vice versa
when I try -Input.GetAxis("Vertical"); it just flips the forward and backwards keys. I need it to actually flip the number
It really all seems to lead back to my original pathfinding code not being the best. My moving object is part of a layer with a higher cost (NPCs) and that is messing everything up. I guess I need to find some way to ignore the objects own collider when it's calculating the path
or smarter logic when it comes to setting up nodes / costs
Or maybe I just don't make the NPC's increase path cost and instead add some sort of steering or replusion or something to get them to not run into each other
If anyone has any advice on how to make A* pathfinding that also avoids collusions with changing node costs would love to hear it
The collider on my NPC's is a polygon 2d one so it makes 8/9 of the nodes that the npc takes up as npc 50 cost nodes and the one in the top left corner a 2 cost node so they always go to the top left as well :/
show the code and what variables ur talkin about
void CheckInput() { gasInput = Input.GetAxis("Vertical"); steeringInput = Input.GetAxis("Horizontal"); slipAngle = Vector3.Angle(transform.forward, playerRB.velocity - transform.forward); float movingDirection = Vector3.Dot(transform.forward, playerRB.velocity); if (movingDirection < -0.5f && gasInput > 0) { brakeInput = Mathf.Abs(gasInput); } else if (movingDirection > 0.5f && gasInput < 0) { brakeInput = Mathf.Abs(gasInput); } else { brakeInput = 0; }
This is my movement script
and the audio is where? what variable do u want to output for each case?
heres the full CarController script https://paste.ofcode.org/BntVBwWGaXfPDBcXv49LhP and heres the full audio script https://paste.ofcode.org/vsppkDLpfwBxKis8jsCeLQ
Its a bit hard to describe because im just learning game dev
But essentially, because the game engine thinks acceleration is actually reversing. The audio script thinks when I am physically driving forwards with the car model, it is actually reversing. And when I reverse, the game engine thinks I am driving forwards thus playing the acceleration audio.
And the issue is, I have no idea why vertical "Up" input is being registered as -1 input when typically it should be 1 input
in tilemap how do i make for example a water tile make it so the player cannot walk through it like a wall barricade
do i use tilemap collider 2D?
it def shouldnt be
Could it be the model I am using perhaps?
Maybe the front of the car is actually the back?
I just downloaded the asset to practice with
Its really strange lol
I'm just gonna try reverse engineer the code to the best of my ability, thank you so much for the help though ๐
yes, put collider on its own tilemap(needs tiles painted) just for collisions / denied areas
also not a code question
this is less of a how to code question and more of a "what the better way to do this" I have a scene with a list of levels, and i have two ways of assigning the level to each. I can 1. Manually assign it, currently theres only 7 so it will be easy, but i want like, 40+ in the future so it will be annoying to reassign things.
2. Give all of the texts with the levels the same tag, and use FindObjectsWithTag to get an array of all of them and make each one pick its order in the array. Each text object already has its own script on it to calculate what i need to say
2nd option doesnt even really sound like it'll work nicely, im not sure the order of that function is even known. you'll still be going through the trouble of creating text objects for each level. at that point you might as well just assign the scene at the same time
imo a better way, have an array of the scene names. then create the text at runtime for each string in the array, and assign whatever is needed at the same time
assigning the scene names can also be done very easily with SceneAsset and taking the name in OnValidate
idk where i am
yeah that could work. tbh im just gonna manually assign it cause i can't be bothered to do complex stuff, thats a future me problem
what i described is honestly pretty easy, the hardest part is setting up the UI so that the generated text objects are where u want it to be
trueeee butm im far too lazy. Im just gonna add a comment to do it later
hey quick questoin, when you instantiate a prefab can you choose the parent?
Yeah, its the second parameter
Instantiate(Object original, Transform parent);
oh cool
so, i wanna think im just making some sort of silly mistake here that i can fix, but it really looks like unity is just objectively wrong with its math here?
Integer vs float
what exactly is the issue though
should it not be logging a float, since im explicitly casting it as one?
Cast one of the numbers as float
the float still is just set with the calculation done with two integers. as jammingend said, cast one to float
*** = (float)currentammo / max ammo
ah yep that fixed it
thank you so much <3
I had the exact same issue yesterday so
๐
lmao awesome
But it should be an integer, anyways, right? ๐
or are you able to shoot partial bullets ๐
Just jkin, I guess its for some visual ammo representation or similar?
oh nono im using this to scale a little indicator meter for ammo on the gun
its just a simple project for uni so im modelling everything in engine with prefabs, so i have it like this
yeah, exactly
The percentage is being calculated.
@lapis yew ๐
I have an image and I am breaking it into smaller cells.
Cach cell is stored in a Dictionary <Vector2Int>, <Texture2D>, then I iterate through the dictionary to recreate the grid.
Each cell has a prefab with a button, and the cell has a TerrainType class that has a variable to store the image.
So while iterating through the dictionary I pass the texture to the button but when I go to check the variable in the Cell.terrainType.splatMap class the texture doesn't match!
Debug says:
Generated and stored textures for cell 0,0. Splat texture name: splat_0_0
then:
Creating cell 0,0 with splat texture: splat_0_0 (and it's true because the texture in button is correct!
but the Cell.TerrainType.splatmap has 47.21 (which is the last cell)
Why?
Can somebody tell me what is going on?? ๐คฏ
The code is fine... I guess, because the in the cell I take the TerrainType.splatMap and I assign it to the background of the cell and the texture is correct:
{
public TerrainType terrainType;
public Vector2Int pixelReference;
[SerializeField] private Image buttonImage;
[SerializeField] private RawImage backgroundImage;
public void SetTerrainType(TerrainType terrain)
{
terrainType = terrain;
if (terrainType.splatTexture != null)
{
backgroundImage.texture = terrainType.splatTexture;
}
}
}```
I guess that could be a Unity's memory issue.
What is TerrainType?
A subClass
public class TerrainType
{
public BiomeType biomeType;
public Color color = Color.black;
public float height = 0;
[Space]
public Sprite sprite;
public TerrainLayer layer;
public Texture2D splatTexture;
public Texture2D heightTexture;
}```
And how do you generate your buttons? That code is probably the one failing, because you seem to overwrite something in the loop
especially your terrainType = terrain is generating a reference to terrain instead of a copy, so you might change the terrain object later on and your terrainType gets updated with each iteration in your loop
{
RectTransform gridRectTransform = grid.GetComponent<RectTransform>();
float cellWidth = cellPrefab.GetComponent<RectTransform>().sizeDelta.x;
float cellHeight = cellPrefab.GetComponent<RectTransform>().sizeDelta.y;
int numCellsX = Mathf.CeilToInt(gridRectTransform.rect.width / cellWidth);
int numCellsY = Mathf.CeilToInt(gridRectTransform.rect.height / cellHeight);
for (int y = 0; y < numCellsY; y++)
{
for (int x = 0; x < numCellsX; x++)
{
Vector2Int cellCoord = new Vector2Int(x, y);
Vector2 cellPosition = new Vector2(cellWidth * x, -cellHeight * y);
if (!splatTextures.ContainsKey(cellCoord) || !heightTextures.ContainsKey(cellCoord))
{
Debug.LogError($"Missing textures for cell {x},{y}");
continue;
}
// Dictionary Recover
Texture2D splatTexture = splatTextures[cellCoord];
Texture2D heightTexture = heightTextures[cellCoord];
Debug.Log($"Creating cell {x},{y} with splat texture: {splatTexture.name}");
GameObject newCell = Instantiate(cellPrefab, grid.transform);
newCell.name = $"cell_{x}_{y}";
TerrainType terrainType = mapGenerator.GetTerrainTypeFromTexture(splatTexture);
terrainType.splatTexture = splatTexture;
terrainType.heightTexture = heightTexture;
Cell cellComponent = newCell.GetComponent<Cell>();
cellComponent.pixelReference = cellCoord;
cellComponent.SetTerrainType(terrainType);
RectTransform cellRect = newCell.GetComponent<RectTransform>();
cellRect.anchorMax = new Vector2(0, 1);
cellRect.anchorMin = new Vector2(0, 1);
cellRect.pivot = new Vector2(0, 1);
cellRect.anchoredPosition = cellPosition;
}
}
}```
Did you debug log your terraintype when assigning in your cell to see, what numbers you get there?
And also logging this mapGenerator.GetTerrainTypeFromTexture(splatTexture) might be important, as maybe this one gets you the wrong type or something. You really gotta log more into your separated classes to actually get the correct updates that are being set
Ok, I'll do a couple of tests.
See.. the code is correct (tha's the debug):
WorldGrid: Creating cell 0,0 with splat texture: splat_0_0
WorldGrid: Assigning Splat Texture to TerrainType splat_0_0
Cell: cell_0_0, TerrainType assigned with splat texture splat_0_0
but the terrainType in the cell_0_0 still have the splat_41_21 which is the last cell. and not only the cell 0_0 but all the cell from 0_0 to 0_41 and forward until the texture didn't change the color because it's an island.
should this interface be named IInteract or IInteractable
public interface IInteract {
public void Interact();
public void SetCanInteract(bool canInteract);
public bool GetCanInteract();
public KeyCode GetInteractionKey();
}
{
instance = this;
}```
why doesnt this produce an error?
why would it?
only one = in the if statement
oh didn't realize
it's because ur assigning instance to be null
if the assignment is considered true, then it'll set the instance to this
how am i assigning it if its in an if statement?
check out this article https://stackoverflow.com/questions/11359433/if-statement-with-equal-sign-and-not-in-expression
A single equals operator is an assignment operation, and will evaluate to whatever value was finally assigned to the variable. If the value assigned was not an integer 0, then the result will be "true" for any conditional statement, so the result is not "always true." The compiler should give you a warning if I recall correctly
but i dont get a warning, which is what i expect
IInteractable would be more appropriate
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
some general guidelines in this link above
Inside a loop this could be enough to be sure that the variables get reinitialized?
Texture2D splatTexture = new Texture2D((int)cellSize, (int)cellSize);
splatTexture = splatTextures[cellCoord];
Texture2D heightTexture = new Texture2D((int)cellSize, (int)cellSize);
heightTexture = heightTextures[cellCoord];```
i assume instance is a monobehaviour here,
https://docs.unity3d.com/ScriptReference/Object-operator_Object.html
the implicit operator here is the reason theres no error, it can convert instance to bool
ah that makes sense, thanks
What's better to use or what you prefer and why
Example:
Here we define all through Header and drag and drop our class' RigidBodyComponent through Inspector
[Header("Refs")]
public Rigidbody rb;
void FixedUpdate()
{
some code with rb
}
or this all within code
private RigidBody rb;
void Start()
{
rb = GetComponent<RigidBody>();
}
void FixedUpdate()
{
some code with rb
}
And who knows should I start with learning netcode first or that's too complicated for beginners?
Directly assigning the reference in inspector is better when you can. The 2nd case I'd consider if it was guaranteed there is a RB and theres a ton of different objects youd have to drag/drop in. Or you add this component during runtime meaning it cant be dragged from inspector.
Also yes multiplayer is too complicated for beginners and even intermediate devs
i much prefer the second option since you dont have to remember to manually assign stuff all of the time, but both are equally normal
@astral falcon I've fixed the issue! ๐
but I'm not sure how ๐
Texture2D heightTexture = heightTextures[cellCoord];
GameObject newCell = Instantiate(cellPrefab, grid.transform);
newCell.name = $"cell_{x}_{y}";
Cell cellComponent = newCell.GetComponent<Cell>();
cellComponent.pixelReference = cellCoord;
TerrainType terrainType = cellComponent.terrainType;
TerrainType mapTerrain = mapGenerator.GetTerrainTypeFromTexture(splatTexture);
terrainType.layer = mapTerrain.layer;
terrainType.height = heightTexture.height;
terrainType.splatTexture = splatTexture;
terrainType.heightTexture = heightTexture;```
in short looks like that the method mapGenerator.GetTerrainTypeFromTexture(splatTexture);
which returns an object of type TerrainType whic was the class that I show early was doing some mess with memories. so I've made a new instance of TerrainType `TerrainType mapTerrain = mapGenerator.GetTerrainTypeFromTexture(splatTexture);
`
on every loop cycle, and then took the terrainType from the cell and assigned each value one by one. Quite a mess, but now it's working fine.
What we learned:
-
Direct references can avoid conflicts: Especially when working with Unity objects like textures or ScriptableObjects, it is important to understand how references are handled in memory.
-
Debugging with Unity requires patience and continuous testing: Sometimes Unity issues involve internal resource management and reference assignment, so step-by-step debugging is often the best way to solve them.
๐
Still cant get my list to be correctly sorted... i never worked with sorting, so i dont know what to do...
I grab sprites from a folder with Ressources.LoadAll. They are all named "Level 1" up to 11. But they are somehow saved in this binary format, like shown in the pic.
i tried "previewSpriteList.Sort((a, b) => a.name.CompareTo(b.name));" on the sprite liste and more nothing does a thing
That's how alphabetical sorting works. If the names are always "Level X" then you can do previewSpriteList.Sort((a, b) => int.Parse(a.name.Substring(6)) - int.Parse(b.name.Substring(6)));
oh wow thank you. perfect answer โค๏ธ
Whats the convetion order of variables in a c# class? (e.g static variables always on top)
There isn't really a convention for that afaik, but most people have variables on top, methods at the bottom, properties above methods, static and constants above fields.
Lol, still this issue?
Your sorting is correct, this is how sorting works
I already told you to just make a loop from 1 to 11, and to then load the images based on the index that it's on
Also, please share your !code already so that I can just write it for you
๐ 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 also told you the substring approach days ago, so idk why you didn't just look for given answers then
Note that it's very hacky as I explained then
hey yall, quick question -
so i'm trying to do this super simple thing where player presses a button, and a particle effect that i've attached to the player plays
however there's this weird issue where the particle effect just stops existing when i run the game, i get an error that there's no particle effect attached, even though in the screenshot i have it attached
There is no particle system attached to the player
Did you instantiate the gameobject with the particle system?
What does your code look like?
you're calling GetComponent<ParticleSystem> on the Player object which does not have a particle system
Also, as it's serialized just don't try to assign it in code
if I have a UnityAction test, can I clear all event handlers of that action in such a way that will allow me to add new listeners?
UnityAction is just a delegate, just assign it to null to clear its listeners. if you mean a UnityEvent, then it's basically the same thing but you just invoke its constructor
or UnityEvent has the RemoveAllListeners method which removes all non-persistent listeners (persistent listeners are the ones added via the inspector)
public class orange_text : MonoBehaviour
{
public GameObject orangetext;
public TextMeshProUGUI textMeshPro;
public void Start()
{
orangetext.SetActive(false);
}
public void OnMouseDown()
{
orangetext.SetActive(true);
}
}
Heyy how do I make orangetext inactive again when clicking once more?
use !orangetext.activeSelf rather than the true literal
orangetext.SetActive(!orangetext.activeSelf);
it tells me 'GameObject' does not contain a definition for 'isActiveSelf' ๐ฅฒ sorry I'm an absolute beginner and basically frankenstined that code by accident
note how i didn't type "isActiveSelf"
my bad
ohhh ok thanks!!!
stop crossposting as said here #archived-code-general message
yes you are
posting in unrelated channels is crossposting
what?
you are talking about cinemachine
not URP
You've been told to stop cross posting multiple times now. Dont be surprised when people dont wanna help if you wanna ignore rules
posting in 3 code channels is what then?
that does not make any difference
if someone knows they will help you in #๐ฅโcinemachine
wait you got help from spazi
Are there any good methods of sorting a 1 Dimensional list of objects, each having "x" and "z", (x increasing left to right) & (z increasing from bottom to top) ??
example of what the array could look like: [{-1, 0}, {0, 1}, {1, -1}, {0, 0}, {-1, -1}, {1, 1}, {0, -1}, {1, 0}, {-1, 1} ]
and the sorted array would look like this:
[{-1, 1}, {0, 1 }, {1, 1}, {-1, 0}, {0, 0}, {1, 0}, {-1,-1}, {0,-1 },{1, -1}]
so when placed into a tile pattern it would resemble the numbers in a regular coordinate system.
:
[{-1, 1}, {0, 1}, {1, 1},
{-1, 0}, {0, 0}, {1, 0},
{-1,-1}, {0,-1}, {1,-1}]
There must be some fancy math to sort this... or mabye not... idk plz help :))
hope its understandable :)
by the looks of that it's just a simple case of adding 1 to each number
forgot to mention, that the numbers can be higher or lower, but always within 3 of eachother
what i have displayed here is just the very center point
so you want to find the lowest number and make it zero. then use the same difference on all the numbers
so -3 becomes 0 and all other numbers are adjusted by 3
yes exactly
then it's a very simple algorithm
2 for-loops? each sorting their own rows and columns??
no, one for loop to find the difference number required, one for loop to put the entries into the array
when I start editing code in Microsoft Visual Studio it is erasing all letters after my edited portion. Anyone know how to fix this?
Like in a singular line of code it is starting to overwrite it if that makes sense
Insert key on your keyboard
press insert
amazing easy solution THANK YOUUUUUU
Hey mates, wondering what's your approach to version control, I'd like to work from multiple computers, I'm not sure if github for instance is suitable for projects including multiple asset packs. It would work for the scripts but I guess the other files are too big, but also need to be synced across machines
you can use github version control and pay for it or use git LFS which is recommended for large files
you can also host git yourself if needed, but you need that machine to be on to use it
i use github desktop, and just push to main every time i am done on one pc.
then on other pc i just press fetch origin, and get the changes down locally
i am working alone on it, so i dont need to think too much about merge conflicts or anything
what do you mean by pay to it? I mean, ideally I'd like to avoid spending money to store the code
unless you want more than 100mb of commit which I believe you have to pay for
but if you are solely storing scripts, you will be fine doing it for free
Oh, maybe then I need to split my first commit in several ones?
LFS has free tier but limited
100 mb / file i think it is
any git hoster will make you pay for the 100mb limit anyway and for git LFS as well since its integrated for git
but yes splitting commits is a good option
why would you be syncing asset packs across multiple machines anyway when each machine can just download them
Hi there
Sometimes I need to modify models or scripts of the asset packs
so you save the changes not the whole packs
I'll try to push as it is rn maybe it just works ๐ซข
use full sentences
im using transform.rotate to turn it using mouse
I guess Library, debug, logs and idea folders can be excluded, right?
but its not moving according to where its looking
Please write your question in one message so it does not get broken up. You can hit Shift + Enter to add a new line without sending the message
gitignore
okay
you should use the unity .gitignore
show !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.
you are most likely using Vector3.forward instead of transform.forward
one is global one is local
oh?
did I guess correctly
wait i will send codd
im new to unity
using JetBrains.Annotations;
using Unity.VisualScripting;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] float moveSpeed = 7f;
[SerializeField] private Vector2 mouseturn;
[SerializeField] private float mousesens = 3f;
[SerializeField] private Animator anim;
[SerializeField] private Transform NeckBone;
CharacterController charcont;
private float downpull = -0.05f;
private void Awake()
{
charcont = GetComponent<CharacterController>();
}
private void Update()
{
Vector2 inputvector = new Vector2(0,0);
if (Input.GetKey(KeyCode.W))
{
inputvector.y = +1;
}
if (Input.GetKey(KeyCode.S))
{
inputvector.y = -1;
}
if (Input.GetKey(KeyCode.D))
{
inputvector.x = +1;
}
if (Input.GetKey(KeyCode.A))
{
inputvector.x = -1;
}
inputvector = inputvector.normalized;
mouseturn = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
transform.Rotate(Vector3.up * mouseturn.x);
//NeckBone.transform
if (charcont.isGrounded)
{
downpull = -0.05f;
}
if (!charcont.isGrounded)
{
downpull += -9.81f * Time.deltaTime;
}
if (inputvector.y != 0)
{
anim.SetBool("isWalking", true);
} else
{
anim.SetBool("isWalking", false);
}
Vector3 movedir = new Vector3(inputvector.x, downpull, inputvector.y);
charcont.Move(movedir * Time.deltaTime * moveSpeed);
}
}
start by posting the code maybe ?
oh yeah on the money, you are using global vectors, instead use the transform of the object instead
You're going to need to provide more context than that. What are you trying to do and what is it doing instead
also IIRC you can do Movedirection = transform.forward * y + transform.right * x;
umm which one exactly. u mean im rotating global??.. or like using global to move
you are using global vectors to move yes
!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.
that if statement is scary..
Redacted by the CIA
you should probably use an actual movedirection vector instead of manipulating it using keycodes as stated here #๐ปโcode-beginner message
x and y are inputs such as x = Input.getaxis("Horizontal"), y = Input.getaxis("Vertical").
this kind information must be kept away from the general public
this will help ig
is this a UI Button ?
do you have an event system in the scene
omg please use Links
as described in the bot message for posting code
am I mixing up the x and y axes?
its correct ig
this is backwards z * y instead
yup, thanks
forward * z + right * x
im blundering, forgive my mistakes
you have to save before you send the link ๐
You didn't actually put any code in the link
you are forgiven bwuaha 
Okay, what calls RemoveResources
verify that RemoveResources gets called by putting Debug.Log
the logic is fine. If the button isn't clicking or calling that function, you likely do not have Event System
yes this helped
finally it moves where its looking
Glad it worked ๐
thanks very much
when what is clicked
did you see the event on it ? OnClick
Okay, so this is calling the function OnShopClick with the string parameter "village"
you "think"? Why not check
You can see what that function does when you pass it the value "village"
How about you tell me what this function does when you pass "village"
You already are
that's not the question here
the function is called with the string value "village"
So, what does this function do, when passed the value "village"
Okay, so, what actually takes the resources
and what calls RemoveResources
this is already an overcomplicated system you put yourself in lol
yeah but now you need to connect the two
this doesn't care if you have resources or not it will just spawn whatever (in this case "village")
onshop click needs to run some validation logic that you do in the button
ButtonClick -> DoIhaveEnoughResources For this -> Subtract amount / Instantiate
i guess not making non-interactable can work to skip some if statements but you still need to Remove the proper resource according to the resource you bought
Well, first think about it in terms of words. What do you want to happen when the button is pressed?
use pen and paper it helps a lot tbh
Okay, so the button just removes resources?
Click button lose resources?
So, it sounds like you want it to do more than just subtract resources
Explain the entire purpose of the button
What happens when you click on it. The entire process
Okay, so, the button is only enabled if you have enough resources, so that's not related to clicking.
When you click on it, you want to remove some amount of resources, then instantiate a prefab.
So, put the "Spawn a prefab" thing in this function, and have your button call this function
This script already has you setting all the resource costs for a specific thing, just give it a field to drag in the prefab
This entire script is redundant. Just have the script that defines the resource costs also spawn the objects
Then there's probably something you didn't share
So then you were calling RemoveResources somewhere and never showed it
But also do this anyway
did you try googling "restart the scene in unity" because when i do it there are a lot of results
you could probably use loadScene
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
its ok it didnt offend me ๐ but if your question is this simple then you can just google it
Yo
Can anyone think of a way to have collisions without rigidbodies?
I'm setting a mesh's position manually through code
That is
manually setting transform position
I just want it to not be movable in that direction if it detects a collision
i was thinking about doing raycasting
but can anyone think of a better alternative?
can you speak in complete sentences instead of spamming 8 messages that could have easily been one
This is the basics of any non rb movement system. Theres tons of tutorials out there, and even free assets like kcc which do this
Youd realistically use a capsule cast instead of raycast
Kinematic Rigidbody+ trigger collider
That would be my first guess, but i wouldn`t know how to stop movement in a specific direction one the collider triggers
You didn't mention that as a requirement but sounds like you just want CharacterController then
Sorry about that, but what i`m trying to achieve is essentially for the cube not to be able to move further in that direction in the Z axis when it collides with that wall
I'm not sure charactercontroller would be the way to go if i have multiple of those in a single scene
What's wrong with multiple in the scene?
yep this is the basic use case for CharacterController
I'm not sure, i just assumed it would be easy enough to achieve without character controller
well for it to work by u dragging it like that it'd need a rigidbody
I mean I guess, but it's also easy to hammer in a nail without a hammer
why wouldn't you just use the hammer?
but moving thru code.. a CC should be fine
KCC is great.. even if u dont end up using it..
lots to learn from just browsing thru the code
Well
I was hoping i wouldn't need to scrap what i've written so far, but might as well learn something that could be more useful
dont scrap it..
keep it around.. u can always go back to it.. or use pieces of it.. or go back and look at it after u've learned other ways..
might still be benificial to u
hi im having this problem
the problem is that when i use this code:
if (LeftHandGrip != null)
{
animator.SetIKPositionWeight(AvatarIKGoal.LeftHand ,1);
float smoothTime = 5.0f; // Ajusta la velocidad de suavizado
handLeft.position = LeftHandGrip.position;
handLeft.rotation = LeftHandGrip.rotation;
}
if (RightHandGrip != null)
{
float smoothTime = 5.0f;
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
handRight.position = RightHandGrip.position;
handRight.rotation = RightHandGrip.rotation;
}
its suposed that Right hand grip or left hand grip is a object inside the weapon that parent to the player when he get it
for example
void get weapon(newWeapon){RightHandgrip = newWeapon.right hand grip]//this is an example i now that the code dosent have sense
the right hand grip is the target of a Two ik bone constraint
if somebody can help me,let me know it because i dont get any solution in other place
First !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.
Does anybody know how I can stop this callback thing? Iโm trying to add water in my player but every time I do that it says call back. What do I do? Pls help me
I ainโt got time for you. Iโm blocking you.
Okay, but then you aren't going to hear when I say that you didn't even include what "Call back" you are talking about ยฏ_(ใ)_/ยฏ
I donโt know how call backs work mines a render one or something
Your photo literally shows nothing of value for anyone to answer your question
9000 !
You know, if you had sent a screenshot of your editor window instead of a poorly aimed grainy photo, someone might have actually seen your error message
Honestly, you just come here to beef with people itโs crazy. Iโve never seen you not respond to one of my texts. Do you live on discord like bro ๐
I answer questions. That's what I do
Youโre not answering my question lol ๐
you just told me you didn't want me to ยฏ_(ใ)_/ยฏ
I didnโt say that ?
I never said that that I didnโt want you answering my question. I just wanted to block you cause youโre annoying. Like thereโs a difference.
Oh well. Blocked now, guess you'll have to figure it out on your own ๐
hey digiholic if you wanna help somebody, you can help me๐ ๐
please?
Did you know thereโs a thing called other people? Iโll just try that one. ๐
!code, and also I'm not entirely sure what the problem is, I'm guessing it's the spinning offscreen arm?
๐ 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.
yes
๐ 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.
๐ 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.
Bro didnt know how to use code
Did you try reading the bot
sorry im noob at english
anyways im using this code but inside late update
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i try my best
Yes, like that. So, it seems like either LeftHandGrip or RightHandGrip is rotating. You're setting handLeft and handRight's rotation directly to that object's. What objects are those
this is a example of what object are those
It is added depending on which weapon you choose.
this a example inside a musket
So, does RightHandGrip, Cube.001, or M16 rotate?
So, the hand is going to copy the current world rotation of that object, every frame
and that cube is the magazine
yes
So if the HandGrip object, or any of its parents are rotated, it's going to change the rotation of the hand
And, actually, since it's IK, changing the position of the hand might also be changing the rotation of the arm. I can't quite tell through the gizmos if the hand itself is rotating in your clip
is it facing the right direction and just moving? Or is it actually rotating along with the arm?
yes its facin the right direction
So, it's probably the position that's the problem and not the rotation
the arm didnt seem to respect that and only keeps moving ignoring the position and rotation of the weapon grip
hi! i was wondering if there's a way to add scripts/components to tiles in unity's tilemap system for the use case of (for ex) placing enemies down as tiles, creating triggers (in tile format) etc ~ I'd love to be able to slap a camera trigger down similarly to the way it works in lonn for celeste
i see,and
position of the weapon grip isnt the problem
I dont know anything about tilemap as i havent worked with it but from some quick searching it seems like tiles are a intermediary asset? From my understanding it means that its closer to a texture or other types of assets that mostly act as art or properties for gameobjects to use (somebody correct me on this as im new to unity too). If you want to make your own script for a tile, you would have to override functionality from the TileBase class (from what ive understood). Maybe this helps: https://docs.unity3d.com/6000.0/Documentation/Manual/tilemaps/tiles-for-tilemaps/scriptable-tiles/create-scriptable-tile.html.
^ hopefully somebody with real experience on tilemap can help out with this. This is just what i found from some digging.
Compute shader (FFTSpectrumViewer): Can't find kernel (0) variant with keywords: CHANNEL_BLUE CHANNEL_GREEN CHANNEL_RED. Does anyone know why I'm getting this error in the snipped code (FTTSpectrumViewer) provided in the hastebin. The error comes from the dispatch line on the computer shader
https://hastebin.com/share/esiwejezur.cpp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So, I recently coded an error popup, and for some reason it's giving me a null reference exception when it's built, but not in the editor.
Image 1 is in the build, Image 2 is in the editor, three is the console during the editor, 4 is the Script for the error popup.
You probably should output the stack trace too
yeah i dont know how tho
Also, you can connect the editor to the build to see errors in the console.
whats it called in the script?
wait actually? how?
stackTrace. It's a parameter of the callback you're using.
ah perfect
thankyou
Build and run a dev build and select to connect it in the editor console. The "Editor" drop-down should allow that.
hmmmm alright. I'll go look that up thanks ๐
oh yeah it totaly is. That's what happenes when you forgot to rewrite the code you copied
for some reason this BoundsInt.Contains function returns false every time. any idea why? i couldn't find pretty much anything on BoundsInt documentation wise
i hope this is the right channel for this also
In what way would this value be within the bounds? The y is only -2 in inspector and you have -3 in the function call
i must be misenterpreting soemething about bounds then
would starting at -2 and going down 2 not encompass -3?
Actually im not sure if you can have negative size like that
https://docs.unity3d.com/ScriptReference/BoundsInt.html
You can print out the min and max for each xyz
okay, starting to regret this error popup. i have a new error popup
where is line number?
yeah exactly
oh thats right i made a dev build
lemme get a screenshot
yeah i fixed it by just doing a if (percent != nul)
you probably want TMP_Text rather than Text
but i still dont understand how it's null, it assigns itself at the start and theres no objects with percentage reader that dont have text
nah its just normal unity text
i know i should change it, but like half my text objects are tmp and half arent
Did you debug when this method runs? Add a debug in start and your method
i mean, i dont really need to. It's just the percent reference in the first Method. My guess is that something calls the first method before this script calls start. The != null thing works so ima just leave it like that
๐คทโโ๏ธ it takes 30 seconds to do. You should solve your race condition instead of this null check.
race condition?
just a bandaid to bigger issue
null checks usually *
basically just saying that you have an unexpected ordering to how your code runs. solve that
I guess at least, just like assign it in the inspector that get rid of the order issue
honestly the whole thing would be solved too if you just plug in the reference in inspector, rather than doing get component
yeah true i guess
TIL about "lazy instantiation"?
private Text _percent;
private Text percent => _percent ??= GetComponent<Text>();```
https://docs.unity3d.com/ScriptReference/Object.html
The null-conditional operator (?.) and the null-coalescing operator (??) are not supported with Unity Objects
yeah, you can only use that with C# objects, not unity objects . . .
still interesting.. i tend to stumble on all kinds of wacky syntax here lately
though, you can still lazy instantiate . . .
just found out about using ! after a variable to suppress null errors
does that one work?
that i don't do myself, so i'm unsure . . .
even if you dont use ??, and you're checking for null, for component references this is weird to use. i cant imagine many cases where you wouldnt be able to just assign it in inspector or do get component in awake or start
that tells compiler " I know for a fact this isn't going to be null"
i only ever use it in Awake or Start (in case I forgot to assign it) . . .
unsure if this is what you meant?
actually, i lied. i use it in Reset because that gets called in the editor. it'll ensure smth is set . . .
which one is the max?
https://docs.unity3d.com/ScriptReference/BoundsInt.Contains.html
A point is contained in the bounding box if its x, y and z components are greater or equal to BoundsInt.xMin, BoundsInt.yMin and BoundsInt.zMin respectively, and less than BoundsInt.xMax, BoundsInt.yMax and BoundsInt.zMax respectively
2nd i believe
good heavens i cannot type
IM having some issue with this error The type or namespace name 'GridTileBase' could not be found (are you missing a using directive or an assembly reference?)
am i missing something?
GridTileBase? can you screenshot the error
try send the !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.
no, GridTileBase.cs
OHH ok ok thank you
Mornin' all,
I'm refactoring my code at the minute (consolidating a bunch of stuff). It's all working as expected except for one teeeeeeny little aspect.
https://hastebin.com/share/ugefecixaz.java
The Indicator that appears around the ship should appear around the targetted object (In this case Asteroids), and I'm not sure where the error is in the code (It's the exact same code that I was using elsewhere and it worked perfectly, and just can't see where I'm going wrong).
Can anyone see the issue please?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Interactable interactable = currentMouseoverObject.GetComponent<Interactable>();
You declare this but don't use it anywhere in your code
Ah yeah, that's not needed just yet (It's to grab the data that fills in the UI elements of the popup message).
also, you should consider using TryGetComponent even if you're using layer filtering
Okay, yeah that makes sense. Thanks.
Well, you're looking for the gameobject from the hit to apply the target reticle over, so if that's what you're getting there it should be the target of that
This is what's confusing me. I'm grabbing the 'target object' and the 'interactable' script fine (the cursor sprite changes as it should, the cursor sprite is assigned on the interactable script), so I'm not understanding why the rectTransform of the indicator isn't changing its position based on the currently 'rolledover' asteroid.
So WorldToScreenPoint is returning the same value for any interactable I'm guessing?
Like I said, it was working fine before I moved this functionality from the playerController to my MouseController script. I've obviously changed something that's broken it, but I can't see in the code where. lol.
Yeah, I'm trying to make my 'interactable' script 'Generic' so that it works for any object (there will be 4 different types of object that the player can rollover eventually)
The Interaction script works perfectly btw. It's the rectTransform positioning that isn't working. It just stays with the ship. ๐
Right, so are the values from worldtoscreen changing depending on where the cursor is right
in that case it points to those rectransform.positon then
Yeah, was just double checking that.
I've debugged 'mouseoverIndicatorScreenPosition' and it changes as expected.
Oh for gods sake. lol.
Sorry, I just figured it out and I am a collosal Penis. I'd assigned the wrong thing in the Inspector (The parent container and not the actual image object.
Parent doesn't have a rectTransform.
ah ok I was going to suggest making a primary rect transform with local over world coordinates
I dont remember worldtoscreen being a vector3 either but it does use the z for the depth
Yeah I did look at the docs and it's Vector3, confused me if honest. But I guess it makes kind of sense if it's looking for a vector3 to convert?
Thanks for taking a look anyhow, sorry it was me being an idiot. lol.
if you have problems with that later, may be worth zeroing out the z
if you're not doing transparency on the UI by the transparency queue
Sorry, no idea what that means.
usually you can sort by z-depth with transparents, but canvas and 2D modules have ways to force what is rendered over each other
Aaah, yeah I get ya. Yeah tbh, I'm kinda doing all that manually with the hierarchy placement etc.
so technically it first sorts by queue, then if everything is at the same queue then it sorts by depth
Use CompareTag instead of equality
I got this little piece of code which replicates the forward and backward movement of w and s on mouse scroll up and down - works wonderfully for its purpose, but recently it was pointed out to me that some users expected scrolling in the camera to behave differently; namely for it to instead zoom in on the area of the screen the mouse cursor was in specifically
think the way google maps works yknow?
and Im kinda having a hard time coming up with what the would even look like mathematically
any pointers would be much appreciated
The basic idea is that you save the world position where the mouse cursor points, zoom, check what position is now under the cursor, and calculate the difference between the old position and the new position. Then you move the camera by that amount to the opposite direction which puts the old location back to under the cursor.
Would I check the world position of the cursor against a plane through origin in case I have no natural ground or walls to hit? I'd have to ray cast, right?
Yes, you need a plane
how do i use new vector3 without getting that ambigous error thingy
im very new to unity i need some help
Show the error message and the code that goes with it!
Show your code and the error please?
hold on im having a very difficult time screenshotting on imac
Don't screenshot !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.
It usually happens when you try to add a Vector2 and a Vector3, and C# can't guess which + to use, because both V2 and V3 have an addition operator
But I want to confirm this is the actual issue
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
sorry if its a bit bad
ah ok
oops wrong reply sorry
You're only creating the Vector3 with only 2 parameters, you need to use all 3 (x, y and z)
If you're using 2D, use Vector2 instead.
Nope
i also did the samething it didnt work
You have two using directives, both have a Vector3 in them
The System.Numerics one isn't compatible with Unity, remove it
Oops. I didn't even look at those. My bad.
ahhh
wait
OHHHHH
how do i send in text next time i think i remember thers a way to format it
!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.
Guys i wanted to make sudoku is there a way to make it without using DFS or backtracking? Is it even possible?
is changing gameobjects from another scene can affect your code in other scene i have this game where answering the question right the game continues and when collided again it stops but then after customizing some design in another scene when the player answers the question right the game continues but when colliding it still continuing
I am currently trying to fix my blackjack game, I have completed the code but it does not work for some reason. I do not know if it's something wrong in my GameManager https://hastebin.skyra.pw/yicoyeqinu.pgsql but every time I hit "deal" it works fine. But when I click "hit" it does not determine the winner or loser ( for the dealer or player), cards keeps appearing every time I click "hit" until the game crash
it's pretty obvious handvalue is not being incremented
I have trouble working with the new input system
I would like to make crosshair appear smoothly when the right mouse button is clicked/"GetKeyDown"
and smoothly disappear when it's released/"GetKeyUp"
smoothness is easy so don't mind static value, but I'm struggling for few hours on how to get keydown/up functionality from the new input system
started for keydown, cancelled for keyup
and make sure that your input action is enabled
Hello,
I have this script right here, where a particle system should face the opposite direction of a Rigidbody (car) entering a water object.
Could anybody explain why the particle system instantiated in the script (see below) does not face that direction?
public class WaterEffects : MonoBehaviour
{
[SerializeField] GameObject splashVFX;
[SerializeField] string carTag = "Car";
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag(carTag))
{
Quaternion rotation = Quaternion.Euler(-other.transform.forward);
Instantiate(splashVFX, other.transform.position, rotation);
}
}
}
transform.forward is not expressed in euler angles. it is a direction and is normalized
Use .LookRotation(-other.transform.forward) to construct a quaternion from a direction
Btw, you can set Transform.forward directly too
So whatEverTrans.forward = -other.transform.forward should work too
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
yeah, I have been trying to fix it. Either I have done something wrong or I do not how to do it, here is the logs
would you need the other scrips to help me further?
then maybe you should post the playerscript code
the notes are not in English, sorry for that๐
you obviously know how to use Debug.Log so why not debug this?
int cardValue = deckscript.DealCard(hand[cardIndex].GetComponent<CardScript>());
I will give it a try
should have done that before coming here
Thanks ๐ซก
I've tried but only performed seems to trigger anything
when in OnEnable method I write aim.context.performed it runs ToggleAim exactly once upon keydown and exactly once upon keyup
once I swap performed for either started or canceled I do not run ToggleAim method
I think I have been rash to jump straight into input system without any preparation
But on the other side I've been reading the documentation for it and yet I don't understand it well
Do you guys have any youtube video explaining such actions in the new input system? I'll really appreciate it!
You need to use performed and canceled if I remember correctly
correct, which is also what steve suggested to them
although they are only subscribing to started here
performed is GetKey though, multiple calls
Started is for some cases where the action is long, like a button with the Hold modifier: pressing the button invokes started, when held for the required amount of time invokes performed, when released invokes canceled
If you have no modifiers, it should be performed (key down) and canceled (key up)
I've tried to use both in the onenable and created separate methods to be run by started and canceled
but I have not received any log in console when I've done it this way:
Also log stuff inside OnEnable directly. The script needs to be on an active and enabled object for this to run
is the action even enabled?
well the performed runs twice, once on keydown once on keyup
canceled and started are ignored
is this even the correct way/place to call them?
Frankly speaking I don't have knowledge to be certain about it, sorry
But I believe I have the action enabled through action map
At least the documentation says it should be alright this way
Are you using a mouse or a gamepad to test this out? The action supports both
Mild inclusive or moment
The second key difference is that only Performed is used and will get triggered on every value change regardless of what the value is. This is different from Value where the action will trigger Started when moving away from its default value and will trigger Canceled when going back to the default value.
"A or B?" - "Yes"
yeah, it took me a second to understand it the way you intended
at first I interpreted it as "are you even using any of these?" :x
That works
Thank you very much!
idk what you are referring to when you say "that works" as i did not give a suggestion, i was simply showing why you were not getting started or canceled invoked
I wonder why it's in passtrhough by default though, seems like it comes from the standard assets one
Especially when you can configure the press point (ie. how far you need to press the trigger down on gamepads) to trigger the action
it does say that the functionality of different action phases depends on the input action types
so I've changed passthrough into button and it works as intended
It's because of pass through
Pass through only does performed
Sorry lag
Yeah it seems so
boxfriend pointed me in the right direction
even if he didnt intend to do so he helped me to fill out my knowledge to resolve this small issue :)
Thatโs in the new update?
They changed the Input manager ?
no, that is the input system. which has been around for like 6 years now
Nvm lol
Does anyone happen to know why this error keeps showing up? I recently updated my game to a newer version of unity so that is most likely the issue, but I'm not really sure where to even start for this error besides the error taking me to the GridEditorUtility script. Additionally the error pops up when I make changes to random scripts. For example, I change my enter room controller script and after saving this error pops up. I can still play my game and it doesn't seem to be affecting anything in my game, but I'd like to get rid of it xD
The Internet suggests
Right click on the Scene tab and close it, then right click on any other tab and open the scene tab again.
Either that or the near clipping plane or some other inspector value for the camera may be inappropriate.
gotcha tyvm ^^
I dont understand this error, the script is attached to the gameobject. Am i suppose to assign "gamneoBEJCT" TO anything.
I am trying to make it so when my player hits the ground with the tag "ground" then the boolean "is grounded" is true
you are using the variable type not the variable name
2hat do u mean
exactly what I said
So am I suppose to be using the name of the gameObject
no, you use the name you associated with the type Collision2D
Collision2D is a variable type, like int or string or Vector3. Don't use the type, use the variable of that type
maybe brush up on some C# basics
Lol I think I have been coding for too long and need a break
hey, I tried to do that just now with some help from my friend (he helped me with the debug.logs before) but i got errors and all that and just changed it back how it used to be, hence i am still stuck..
you do understand that your DealCard method is returning zero
so there is an issue in my shuffle or deck set up?
that is not what I said
share the code for DealCard
how do i make a bunch of gameobjects with a tag do something at the same time
good way or simple way?
both ways please
good way is using events, simple way is FindObjectsWithtag and for loop
oooooooo
i have a question, is there a way to retrieve parts that are in a group
so you are calling DealCard with
hand[cardIndex].GetComponent<CardScript>()
and you return
cardScript.GetValueOfCard();
so the problem must be there. Share the CardScript code
this is called Debbuging btw, a very good skill to learn
You're going to have to be specific about what you mean by "parts" and "group"
a function to make a bunch of gameobjects that are in a gameobject to do something at the same time
yes, I will try to learn it from my friend once he got time
and there we go
public int Value = 0;
public int GetValueOfCard()
{
return Value;
}
so the Value of 0 will be returned unless you have changed it in the Inspector of the gameobject with this script on it
Which objects? And what do you mean by "in" a game object
i dont know how to explain, i will learn about this later
In order to select a set of objects you first need to decide which objects you want to select
just so you know, GameObjects don't actually do very much, it's the scripts/components attached to them that do the real work
oh, thanks I will give it a try
just a question, if i change the value for a card, won't the same card always appear, for example ace will only appear on that card i changed the value on?
I have no idea of your setup but from what I see each card has it's own CardScript attached so changing one should not change all
great, I will give it a try and hopefully it works
tbh, you should understand your own game a great deal better than you appear to
i should, but i have been following a tutorial for this one that's why I am stuck. I did also try what you told me to do but no one wins or lose
did you change the Value in the inspector of all of your cards CardScript components
yea if i did not do it wrong
what's my mistake?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class move_one : MonoBehaviour
{
public Image one;
public GameObject Canvas;
float i = 255;
float t = 0;
private void Update()
{
t += Time.deltaTime;
transform.position = new Vector3(transform.position.x, transform.position.y + Time.deltaTime * 50, transform.position.z);
if (t > 1f)
{
one.color = new Color(255f, 255f, 255f, i -= 100 * Time.deltaTime);
Debug.Log("a_changes");
Debug.Log(one.color.a);
}
if(one.color.a <= 0)
{
Destroy(Canvas);
}
}
}
so that CardScript is attached to the Ace. What about the other 51?
the color changing part
Color should be Color32
i added all my cards to my gameobject "Deck" but i can't change their value from there
why not
unless its their name
it's here right?
So the CardScript you just showed is in a prefab
its the cards that are on the table which will appear when u click "hit" so it was not the 52 card i guess
that is not what I asked.
I am somewhat confused how you ever expected every card to have the correct value
yeah๐
you appear to have a fatal design flaw in your game
something like that would I say, the cards does not switch its like the they appear somewhat close to the position they were meant to be at
that is irrelevant to this problem
So I'm working on a school project and I want to ask if anyone here is good at using unity and C#. The project has to do with simulating a 3d rocket from data from a model rocket. Im just asking if anyone can help me as I just installed the unity editor today so DM me if possible.
how do i convert an int to a byte
thx
So, there is no problem with the game not recognizing when you get a number close to 21, but it's something related to the cards?
looks like your shuffle is wrong anyway. should be
for (int i = cardSprites.Length-1; i >= 0; i--)
{
int j = Random.Range(0, i+1);
Sprite face = cardSprites[i];
cardSprites[i] = cardSprites[j];
cardSprites[j] = face;
int value = cardValues[i];
cardValues[i] = cardValues[j];
cardValues[j] = value;
}
why dose this make ยดone` blink sometimes
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class move_one : MonoBehaviour
{
public Image one;
public GameObject Canvas;
byte i = 255;
float t = 0;
float t2;
private void Update()
{
t += Time.deltaTime;
transform.position = new Vector3(transform.position.x, transform.position.y + Time.deltaTime * 50, transform.position.z);
if (t > 1f)
{
t2 += 2 * Time.deltaTime;
i -= Convert.ToByte(t2);
one.color = new Color32(255, 255, 255, i);
/*Debug.Log("a_changes");
Debug.Log(one.color.a);
Debug.Log(Convert.ToByte(Mathf.RoundToInt(t2)));
Debug.Log(t2);
Debug.Log(i);*/
}
if(one.color.a <= 0)
{
Destroy(Canvas);
}
}
}
okay, do i need currentindex = 1; under or not?
your float to byte conversion is wrong for Color32
Also this should be
public int DealCard(CardScript cardScript)
{
cardScript.SetSprite(cardSprites[currentindex]);
cardScript.SetValue(cardValues[currentindex]);
int val = cardScript.GetValueOfCard();
Debug.Log($"Card {cardSprites[currentindex].name} Index {currentindex} Value {val}");
currentindex++;
return val;
}
So you know wtf is going on
well how do i fix it?
of course, if not I would have said so
idk - you're doing some weird stuff here. It depends on what you're trying to accomplish here
what are you trying to do?
thanks, I will try to run it
actually this should probably be 0 not 1
C# indexes arrays from 0
not very helpful, the stack trace?
it took me to the shuffle that you gave me, cardSprites[i] = cardSprites[j];
I have changed nothing and now it works
my bad, I've updated the code above
now it works, but now i only get aces and i got one 7
so show the console, that's why the debug.log is there
show your code for shuffle
right now compare that to mine
ah, did not see that
one of the "covers" appeard intead of a card
And you still have not learned to look at the Debug info in the console to see why?
sorry it's late ๐
so you tell me, which card was dealt
ok, so maybe that is why you had currentIndex=1 in shuffle because zero was not a valid card
yes
and I was supposed to know that how?
that's on me, mb
So Value is still not right and I noticed you made the same mistake in GetCardValues as you did in Shuffle
cardValues[1] = num++;
oh
also your for is from 0 and it should be from 1 if the first card is not used
okey, that's changed. But it's weird, there is still no winner or loser
so show me the logs, do I have to ask every time
so dont you see that Value is still 0 for every card?
yes, but i could not find in inspector where to change the value of each card
ffs do you not understand your own code. It is being done in GetCardValues
oh let me take a look on that
Thanks for being helpful, the game works now. Much appreciated
Please do take a couple of days to learn how to debug. It will make your life (and mine) so much easier
I will do that, thanks again mate
So after updating to Unity6 when I create new monobehavior scripts for a duration my console gets spammed with warning messages. After a little loading however, the warning messages stop. I was wondering what is causing this issue?
why cant i spam click my button anymore
``using System.Collections;
using UnityEngine;
public class SpawnCards : MonoBehaviour
{
[SerializeField] RectTransform[] cards;
Animator[] cardAnimators;
void Start()
{
cardAnimators = new Animator[cards.Length];
StartCoroutine(CardSpawn());
}
IEnumerator CardSpawn()
{
yield return new WaitForSeconds(0.5f);
for (int i = 0; i < cards.Length; i++)
{
cardAnimators[i] = cards[i].GetComponent<Animator>();
cardAnimators[i].SetTrigger("Spawn");
yield return new WaitForSeconds(0.1f);
}
}
}
``
this spawn code i have aint workin how i want it to idk why, i want the cards to spawn one after the other but they all spawn together in one. i use an animation handler so they all have the same animation
int currenCard;
IEnumerator CardSpawn()
{
yield return new WaitForSeconds(0.1f);
cardAnimators[currentCard] = cards[currentCard].GetComponent<Animator>();
cardAnimators[currentCard].SetTrigger("Spawn");
curentCard++;
StartCoroutine(CardSpawn());
}
try this @north oar
I believe the most common cause of buttons no longer working is another object being in front of them and blocking the raycast. It's worth checking out if turning off other GUIs fixes it.
its working i just cant spam it
hey yall so i was making a game and at one point unity froze and i dont want to close it cus i did not save the project and i dont want to lose everything cus im making it for 4 hours
i tried it and nothing happened when i started it
wait
wait u forgot loop
so can someone please?
Have you checked what's the default animation for those cards?
when u make the loop "for" it will set all triggers at the same time
it works if dont make the sprite it spawns spawn at the position of the mouse
the default animation is nothing i just have it connected to exit and then i made a seperate trigger for the actual spawn animation
Hello! how can I find compare a index within a string? for example if I have a string " Hello world" I want to get the 4th letter within that string, with is " o " and "h" being zero
string[4]
@keen dew Ive tried that but its telling me that I cant convert a " char " to a "string"
string temp = password[2];
password being a string aswell
password[2].ToString()
Yeah but password[2] is a char like it says
... that makes sense to me now
You'll get an answer easier if you ask directly about the actual problem
damn sometimes I feel extra stupid, thanks for sorting it out for me
You would be better off comparing with a char 'o' not a string "o"
You can treat strings like an array of chars.
why the fuck does the image start blinking and my button stops working when the last line is not a note
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class move_one : MonoBehaviour
{
public Image one;
public GameObject Canvas;
byte i = 255;
float t = 0;
float t2;
public Camera cam;
private void Update()
{
t += Time.deltaTime;
transform.position = new Vector3(transform.position.x, transform.position.y + Time.deltaTime * 50, transform.position.z);
if (t > 1f)
{
t2 += 2 * Time.deltaTime;
i -= Convert.ToByte(t2);
one.color = new Color32(255, 255, 255, i);
/*Debug.Log("a_changes");
Debug.Log(one.color.a);
Debug.Log(Convert.ToByte(Mathf.RoundToInt(t2)));
Debug.Log(t2);
Debug.Log(i);*/
}
if(one.color.a <= 0)
{
Destroy(Canvas);
}
}
private void Start()
{
cam = Camera.main;
//transform.position = Input.mousePosition;
}
}
Presumably because you ignore the Z axis and assume world space is the same as screen space
Screenshot your camera's transform
Let's say we have vector A: (0, 0, 0) and vector B: (0, 0, 1).
Would this mean that the distance between A and B is one "unity's unit" in the z direction?
Trying to clarify/understand what unity's units are
Yes
Well, assuming both vectors are meant to represent positions in unity's coordinate space
Vectors are just unitless collections of numbers
Yeah, that's where my question originates from
is there a way to change the position of the trail renderer since its not aligned with the character
Put it on a child object positioned where you want it to be
U are too good for this world
why don't you describe what you are expecting to happen that isn't happening, or what is happening instead rather than assuming anyone here can read your mind and know what you wanted to actually happen
thats a good point
what i wanted was for the color of one to fade out and then delete it, but for some reason it starts blinking for a bid and then gets deleted
it seams like the more instances of one i have the worse it gets
so you've got multiple instances of whatever this object is all modifying the single instance of your Image component
unless you've explained that really poorly and/or left out some context
First of all hears my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class move_one : MonoBehaviour
{
public Image one;
public GameObject Canvas;
byte i = 255;
float t = 0;
float t2;
public Camera cam;
private void Update()
{
t += Time.deltaTime;
transform.position = new Vector3(transform.position.x, transform.position.y + Time.deltaTime * 50, transform.position.z);
if (t > 1f)
{
t2 += 2 * Time.deltaTime;
i -= System.Convert.ToByte(t2);
one.color = new Color32(255, 255, 255, i);
/*Debug.Log("a_changes");
Debug.Log(one.color.a);
Debug.Log(Convert.ToByte(Mathf.RoundToInt(t2)));
Debug.Log(t2);
Debug.Log(i);*/
}
if(one.color.a <= 0)
{
Destroy(Canvas);
}
}
private void Start()
{
cam = Camera.main;
//transform.position = cam.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0,0,10);
//transform.position = Input.mousePosition + new Vector3(0,0,10);
transform.position += new Vector3(Random.Range(-90f, 90f), Random.Range(-90f, 90f), 0) + new Vector3(0,-110,0);
}
}
and what i was expecting to happen is that the a of one.color would slowly get lower after t was more then 1, until it fades out completely and it gets deleted along with the canvas the Image is in but for some reason it doesn't fade out but instead starts blinking and the more i I spawn of it the more it happens but it allso happens when there is only one
the blinking is not on/off/on/off but more like a wave
you should look into using Color.Lerp instead of manually subtracting like that. Print your values and you might see what is going wrong. for example, place this log after the i -= line: Debug.Log($"T2: {t2}, T2 as byte: {System.Convert.ToByte(t2)} i: {i}", this);
How do i share my code if its too long again? Sorry.
!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.
Thanks.
Oh. Here it is. https://hatebin.com/szwheqfuhc
Im going to paste what i wrote on the general chat here for context if thats okay. I have a character which automatically moves to the right, and if it collides with a wall it changes direction to the left. When they jump they can slide on the walls to make like a, slide + jump and reach to other places. I have a problem tho which is, if the player is sliding and they dont jump, once they hit the ground they wont change directions, they can still jump but you will get stuck to that wall. forever. The player has a Physics 2D material with no friction and no bounciness.
Am i missing something? The walls and the floor have a box collider 2D, and the player does as well.
this is so much easier and better thx
you could probably shoot a small raycast down only when Wallsliding and if it hits the ground then change direction, then just remove the else in the OnCollisionEnter2D
Thanks. Ill try that.
since that else basically does nothing because you will only either be on the wall or the floor and if you are on the wall and the floor the Ground code will be called and not the wall code
How do I stop the transform of a gameobject from changing when it becomes a child of another gameobject?
if (WeaponUsed == true)
{
if (VariablesSaved == false)
{
_attackDelay = AttackDelay;
_whenColliderOn = WhenColliderOn;
VariablesSaved = true;
}
AttackDelay -= Time.deltaTime;
WhenColliderOn -= Time.deltaTime;
WeaponCollider.SetActive(ColliderActive);
}
if (AttackDelay <= 0)
{
WeaponUsed = false;
VariablesSaved = false;
AttackDelay = _attackDelay;
}
if (WhenColliderOn <= 0 && ColliderActive == false)
{
ColliderActive = true;
WhenColliderOn = _whenColliderOn;
Debug.Log("Turn On Attack Collider");
}
if (ColliderActive == true)
{
HowLongColliderActive -= Time.deltaTime;
}
if (HowLongColliderActive <= 0 && ColliderActive == true)
{
ColliderActive = false;
HowLongColliderActive = 0.2f;
Debug.Log("Turn Off Attack Collider");
}``` why does the debug.log code run twice?
it turns the attack collider on then it turns it off then on and off again
Check the documentation for SetParent
im just getting more and more confused with this, i debbuged it even more, now sometimes it runs once sometimes it runs twice
turning my fps down to 1 causes it to run 3 times -_-
i just changed the time.deltatime to time.fixeddeltatime
what function is this in
When i do this the player disappears when they jump on the moving platform...
So, since you're not keeping the player's position, it's probably moving somewhere else when you make it a child of this
I set it to true and it still goes small...
Position stays, not scale
You should probably follow the rule of thumb of not scaling any object that has children
Then you won't run into this issue
So i just changed the sprite object instead of the gameobject as a whole and it fixed the issue
Is there a way to blit part of a texture onto a part of another texture?
There seems to be no BlitRect method in Graphics and there doesn't seem to be a Bitmap or Image api
I am trying to draw all my textures onto an atlas
Is anyone here familiar on how to set up kinematic collisions
is there a function to do something when an game object is out of the camera
yes
This is for frustum culling however. If you want to take occlusion culling into consideration you need to use the culling group API
is there a way to use the if function without using the {} and it wraps the entire script in the void
no, using no brackets means the if statement only covers 1 statement. and its not a "void" its a method or function
is there a function to disable components
component.enabled = false
it doesnt show
ah nvm i figured it out
help why wont my canvas move ive been trying to add text but it always appears at the top right'
can anyone help tell me why my text is so low quality
ok i solved all of those
but why isnt my button working
if i click on it it doesnt do anything
i dont understand what can i do to fix this ??
Unity has an internal exception. Often you can't do anything about this but to update your Unity version, but if this exception persists it could be caused by your code
In this case, likely editor specific code
A stackoverflow is often caused by bad recursion
someone help me on my button ui it wont work
So idk, perhaps find related code if this keeps happening
If you want help, you share the related !code and explain what is "not working"
๐ 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.
What stops working? The jumping?
I suggest you debug playerCollider.IsTouchingLayers(groundLayer) first. This likely always returns false
I haven't used IsTouchingLayers myself, but does the ground actually have the correct layer assigned?
Also, I assume the player has to be partially inside the ground for this to work
I would guess that the collider is never in the ground since you'll have two colliders preventing that
What you can do is create a new collider that does go beneath the player, and check that instead
im making a code for when u click a button it restarts the scene
Alright, considering you still haven't shared anything I'll assume you don't need help
i have NO clue how to implement a jumping mechanic with the animations, in my 2D platformer. Does anyone mind getting in call and helping me out?
If I write something like this, does the second line run before or after awake/start for the newly instantiated object?
newObj.variable = variable;```
Awake will have run before Instantiate returns
As will OnEnable
Start will run after all of this
possibly next frame
something which, tbh, you could easily have verified for yourself
is it a better idea to
1: Start with a hard programming language then learn the easier ones after
2: Start with an easy one then progressively move onto harder ones
1 I would say
start with C
All programming languages are the same
Depends on what your final goal is. If it's making games in unity you don't really need to learn anything aside from C#.
I can't imagine a goal that would require you to learn many different languages in succession
nobody would believe my final goal
but i think i'd need more than 1 programming language
try us
tech company, aerospace company and possibly others
but i wanna learn unity bc i'm also passionate for the videogame industry
That's sounds like many different goals.
Maybe start learning languages these companies actually expect you to know then.
As for unity you only need C#.
that'd pretty vague, it will depend on what part of the companies you work for
i dont wanna work for companies, i only would want to start them
idk why but i dont like working for others
what you want to be an Elon clone?
no i think i just have similar interests
then, as Praetor said, C is definitely the place to start followed by C#, C++ and Rust
Ok thanks for the advice
Then you'd need to be more of an economist(or whatever) and less of a programmer.
Because I've never heared of a one-man aerospace company.
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
"putting a semi colon at the end"
You're already ahead than most ๐
Regarding the new input system, has the proprieties of PlayerInput been removed? I'm trying to access the property .action and .SwitchCurrentActionMap() but I can't find them. Every tutorial I see about switching action maps relies on them but I can't seen to get it to show up. What am I doing wrong?
probably you are trying to access them using the class name rather than a variable of that class type
I believe so, I'm using the PlayerInput class that is generated by the editor's Input Actions
thats not the playerInput component
completely different thing
the generated c# class is just an easy access to the Actions of that PlayerInput
I have been working on implementing a solution for this targeted zoom in; here's what I have now:
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance1;
Vector3 point1 = new Vector3();
Vector3 point2 = new Vector3();
if (plane.Raycast(ray, out distance1))
{
point1 = ray.GetPoint(distance1);
}
transform.Translate(Input.mouseScrollDelta.y * 0.2f * Vector3.forward);
Ray ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance2;
if (plane.Raycast(ray2, out distance2))
{
point2 = ray.GetPoint(distance2);
}
Vector3 difference = point1 - point2;
transform.Translate(difference);
}```
it definitely does *something* to nudge the camera into the area of the screen the mouse pointer is in but in practice the offset is not consistent with where the mouse is positioned relative to the objects in the scene. worried Im missing something obvious or that casting against a plane is just not a viable solution for my case
so what should I reference instead? Is there a second PlayerInput hidden somewhere?
the theory as I understood it was, get a point in the scene from mouse position, do a normal forward zoom in, compare the mouse position in scene after the zoom to where it was before and offset the post zoom camera position by that difference
like i said you're confusing playerInput component with generated actions from those inputs. You need to reference the PlayerInput if you want the props/funcs from it
sorry I still don't follow, aren't they the same? Because I only have 1 PlayerInput in the whole project
no the generated C# class is just a wrapper class to the PlayerInput component
PlayerInput handles all the stuff like switching Action maps etc
the generated c# class just gets the actions
but how do I reference it instead of the generated C# class?
[SerializeField] private PlayerInput playerInput
But that's what I am doing ๐ญ
and you're trying to access through playerInput instance?