#💻┃code-beginner
1 messages · Page 236 of 1
Can you repost those? I dont really wanna scroll up and down lol
Also whats ur problem Hellio?
Where's the player movement script?
I only see sliding
Also use paste sites
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using different materials for the green cap vs eggplant body, or pumpkin stem vs pumpkin body
https://paste.ofcode.org/Gpyu9hF7uqzKX2JUKcvgnz sliding script
https://paste.ofcode.org/mxU2LDvGsfnZ6RV3XrXXPy PlayerMovement script
Assign them a material to them on Blender; when importing Unity Will detect different submeshrs with different materials and you can assing those there
Whats ur problem Hellio?
so should I combine into one object in blender, then?
as u can see in the vid , the player when sliding from any height like in the vid where im sliding from a ramp , the player doesnt go down the ramp and the player floats slowly down until the sliding timer runs out which doesnt look good , well if it was some sort of wizard game it would work i guess lol
Usually yeah,the kind of stuff you are doing is more suited like for stuff that you want to animate later
more examples of the problem
(sorry for the delay in the answer). I'm trying to get to use events now for communicating changes and the getComponent<IHealth>() doesn't really follow that model. I think it's just about: choose one style and stick to it.
The beauty of storing live stats with the scripts is that you see them in the editor. E.g., the Health script can have a field which can be inspected. If I put everything into a separate object, then I would have to program all the inspection abilities.
Honestly i dont know?
I've not really looked into mesh colliders with submeshes, but I'd expect there's a way to combine it all, otherwise I guess you can always make two copies of the mesh (combined and separate) and just use the filter of the combined mesh.
damn 
Sorry brother
I'd say because when you jump, you're setting exitingSlope to true
So this if never happens
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection(moveDirection) * moveSpeed * 20f, ForceMode.Force);
if (rb.velocity.y > 0)
rb.AddForce(Vector3.down * 80f, ForceMode.Force);
}
Then there is no force pulling it down (except gravity)
I'm probably wrong, but test it out
Keep in mind setting velocity and using force at the same time is likely to break at some point
because when you change velocity directly, you override any kind of force being applied
its all good bro
does anyone know why?
Can someone help me with this problem, when i hit the MapBoundary MyRocket is stuck
ngl it might be the problem
lemme see what i can do
Could you share code and the inspector please
Are your boundaries colliders or are they hard coded?
what do you mean
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBallTrigger : MonoBehaviour
{
public GameManager gm;
public FindPlayersInTeamFolder fpitf;
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Ball")
{
Debug.Log(other);
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player1))
{
Debug.Log("Works1");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player2))
{
Debug.Log("Works2");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player3))
{
Debug.Log("Works3");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player4))
{
Debug.Log("Works4");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player5))
{
Debug.Log("Works5");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player6))
{
Debug.Log("Works6");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player7))
{
Debug.Log("Works7");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player8))
{
Debug.Log("Works8");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player9))
{
Debug.Log("Works9");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player10))
{
Debug.Log("Works10");
}
if (other.TryGetComponent<PlayerVariables>(out PlayerVariables player11))
{
Debug.Log("Works11");
}
}
}
}
its not the problem and it doesnt make sense , since it happens with any kind of height as shown in the second vid of the problem
That's my guess. The script is too big, needs some time to analyse tbh
JESUS
yeah lmao
jesus
!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.
What are u trying to do forever?
@queen adder
games
Also justin?
does this error matter?
i dont unterstand your text
comes from this simple code
How does ur rocketship know its touched the boundary?
How do u keep the rocket in bounds of the camera?
ah wait
@noble folio what are you trying to do really
wdym
I mean its ok
Noone and i mean Noone starts out coding and is just perfect at it
It takes time
So again what are you trying to do?
football game
Player Script Infos for Boundary
private bool isTouchingBoundary = false;
private void FixedUpdate()
{
if (!isTouchingBoundary)
{
Move();
}
Rotate();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("MapBoundary"))
{
isTouchingBoundary = true;
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("MapBoundary"))
{
isTouchingBoundary = false;
}
}
And the Boundary Script
using UnityEngine;
public class EdgeOfScreenCollision : MonoBehaviour
{
public float colDepth = 3f;
public GameObject Kamera;
private Vector2 screenSize;
private Transform topCollider, bottomCollider; //, leftCollider, rightCollider;
private void Start()
{
if (Kamera == null)
{
Debug.LogError("Kamera nicht zugewiesen! Bitte ziehe die Kamera in die 'Kamera'-Variable im Inspector.");
return;
}
InitializeColliders();
}
private void Update()
{
MoveCollidersWithCamera();
}
private void InitializeColliders()
{
Camera cam = Kamera.GetComponent<Camera>();
screenSize.x = cam.orthographicSize * Screen.width / Screen.height;
screenSize.y = cam.orthographicSize;
// Erstellen der Kollisionselemente
topCollider = CreateCollider("TopCollider");
bottomCollider = CreateCollider("BottomCollider");
// leftCollider = CreateCollider("LeftCollider");
// rightCollider = CreateCollider("RightCollider");
// Einstellen der Positionen und Skalierungen
SetColliderPositionAndScale(topCollider, new Vector3(0, screenSize.y + colDepth * 0.5f, 0), new Vector3(screenSize.x * 2, colDepth, colDepth));
SetColliderPositionAndScale(bottomCollider, new Vector3(0, -screenSize.y - colDepth * 0.5f, 0), new Vector3(screenSize.x * 2, colDepth, colDepth));
// SetColliderPositionAndScale(leftCollider, new Vector3(-screenSize.x - colDepth * 0.5f, 0, 0), new Vector3(colDepth, screenSize.y * 2, colDepth));
// SetColliderPositionAndScale(rightCollider, new Vector3(screenSize.x + colDepth * 0.5f, 0, 0), new Vector3(colDepth, screenSize.y * 2, colDepth));
}
private Transform CreateCollider(string name)
{
var colliderTransform = new GameObject(name).transform;
colliderTransform.gameObject.AddComponent<BoxCollider2D>();
colliderTransform.parent = transform;
// Stelle sicher, dass der Tag "MapBoundary" im Unity-Editor existiert
colliderTransform.gameObject.tag = "MapBoundary";
return colliderTransform;
}
private void MoveCollidersWithCamera()
{
Vector3 cameraPosition = Kamera.transform.position;
SetColliderPositionAndScale(topCollider, new Vector3(cameraPosition.x, cameraPosition.y + screenSize.y + colDepth * 0.5f, 0), topCollider.localScale);
SetColliderPositionAndScale(bottomCollider, new Vector3(cameraPosition.x, cameraPosition.y - screenSize.y - colDepth * 0.5f, 0), bottomCollider.localScale);
// SetColliderPositionAndScale(leftCollider, new Vector3(cameraPosition.x - screenSize.x - colDepth * 0.5f, cameraPosition.y, 0), leftCollider.localScale);
// SetColliderPositionAndScale(rightCollider, new Vector3(cameraPosition.x + screenSize.x + colDepth * 0.5f, cameraPosition.y, 0), rightCollider.localScale);
}
private void SetColliderPositionAndScale(Transform colliderTransform, Vector3 position, Vector3 scale)
{
colliderTransform.position = position;
colliderTransform.localScale = scale;
}
}
📃 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.
@acoustic crow
so I have some code that reads from a .txt file in the assets folder, will the code still function once I make a build of the game? or is there something else I have to do
when the ball gets into the player collider the player will have the ball
@queen adder you want it , you have it
@cinder crag i'd say put a debug.log in every line at this point lol
Please use one of the websites i linked
why doesnt it work with the yRotation = (yRotation + 360f) % 360f;?
this is what happens when i dont comment it out ^
I also have no Idea what the Move() does
every line of the code?
Also dont just use Debug.Log ??
@queen adder https://gdl.space/xutogizinu.cpp playerscript with all infos for boundary

yeah but im just trying if it works
Are the Debug.Logs not getting called?
no they arent
Ok, not every line, but the usual suspects. Anything that checks and uses the y velocity
Does one of them have a rigidbody attached
but the players one is trigger
ball
how do i actually use it in those scenarios? just do Debug.Log(checks and yese the y velocity);
idkidk
It has a normal rigidbody and not a rigidbody2D right and make sure the colliders are the 3d versions as well
Yeah, just see what is getting called.
yeah they are in the 3d versions
I mean, too big of a script for anyone here to look at. Try trim it down.
Forever are you sure they are collider?
yes
And the Colliders Trigger bool is checked?
smth like this?
only on player
Sure
Who has the OnEnterTrigger Script?
my guess is something on the SpeedControl function
Screenshot ur inspector
me
What?
You mean the Player Gameobject?
Forever screenshot ur inspector lol not you justin
on what
The player gameobject
Justin you disable movement when the player touches the bounds
Also check if the useGravity is really working
And ur football
If it is in the air, no matter what, the gravity should still push it down
slowly losing it
Other is the ball
Which does not have the PlayerVariables script
yes
playerscript?
Not you justin
Ey, just a quicky here; if in a collision check I am checking if the object of collision has a component (for example TryToGetComponent<someScript>()) does it get it get the component even if it is dissabled?
meaning ur if statements never run @noble folio
@cinder crag try the #⚛️┃physics channel too, they are full of people way smarter than me lol
its working
Just in case you missed my edit, other does not have the PlayerVariables script on it
Other is the ball.
PlayerVariables is on the player, and so is the code checking the collision
you can only collision check with colliders, unless you mean another component that's disabled, then yes you should be able to get it
yeah i probably did
ohhh
i delete this but my problem is here when i crash i cant move up or down
thank you
Its because you set the touchingBounds bool to true and you have a if statement saying if (!touchingBounds) Move()
As you soon as you touch the bounds the Move() stops getting called
i dlete this
So since playervariables is on the SAME object as the one checking the collision, why do you even need to check for PlayerVariables?
Just have it assigned to begin with
but the problem is physik
Its still not working?
ohhh ok tysm
Sorry i didnt realize that sooner Forever
No, I think it's because of how the rocket is built because when the wings touch the boundary, the tip can go up and because I'm flying to the left, I can't control the nose so that it flies down again, but I know not how I can do that
I mean, they do collide, what I am trying to say is if they do pass the if statement that is checking for the object to have a certain component even if it is dissabled. Cause judging for the result I am getting I think they still do
sooo I combined objects in blender, exported as fbx, and the mesh collider is properly on the object now... but when I go to pick up the object, it is still being weird
alright everything works now tysm
how can i make this work while also having the yRotation only go from 0 to 360 ```cs
if(yClampRotation)
{
float left = yMidRotation - yClampLeftAngle;
float right = yMidRotation + yClampRightAngle;
Debug.Log("Left" + left);
Debug.Log("Right" + right);
yRotation = Mathf.Clamp(yRotation, left, right);
}
yRotation = Mathf.Repeat(yRotation, 360f);```
the problem is that when i have the yRotation = Mathf.Repeat(yRotation, 360f);
this happens
Weird? what do you mean?
https://docs.unity3d.com/ScriptReference/Mathf.Repeat.html
Note, however, that the behaviour is not defined for negative numbers [...]
the eggplant is only showing its butt at the bottom right of the screen, instead of... looking like an eggplant
But like... move the camera? I don't get the issue XD
You mean like the object origin is off or what?
yeah the object is rotating itself
hello, do you know why is this causing a stack overflow ? ^^
Guys this works the trajectory is fine but its too slow the target moves from its place by the time it reaches and when i increase velocity its trajectory changes, any ideas please?
Show what is Score and Timer
Score is a public long and Timer a private float
Show it.
wait so how do i do it
Make your own Repeat function which supports negative numbers
Rotating itself?
I think I know what you are refering to, but I am not sure, could you send a more descriptibe image?
anyone please 😁
this replaced the stack overflow error ^^'
Oh, so it is meant to be held infront the camera, that's the issue?
yeah xD
Does it work properly for the rest of stuff?
nope
Then... change the script that manages the dragging since it is clearly not working as intended
could you help me out?
yRotation = (yRotation) % 360f;
i did this
it works
also yeah i dont need the brackets
i made a string variable called message but whenever i try to run the code it tells me the variable is assigned but never used
It's right. You do create it and put values into it in these if statements, but you don't read its value anywhere. Perhaps you meant to put it in that print() so it's displayed?
@twin ibex I highly recommend you to watch full harvard courses in Computer Science in FreeCodeCamp, also try to watch different tutorials in Game Dev in YT and you can also check courses in Udemy. You will learn a lot from there you will basically gain some useful information. After gaining that useful knowledge you will be able to work on your own projects and gain experience from there. The best practice to learn Game Dev and programming is by working on different projects on your own and getting errors to solve on your own. That's what I am trying to do as well with every resource I have available. Final and recommended it to get help here whenever you get a confusing bug to fix.
Note that this is only a warning, it will not prevent you from playing the game.
yea thats what im trying to do but i dont understand how to
print("... seconds off." + message)?
thanks it worked cant believe i didnt think of that
Especially when you've done it twice already, on the same line of code
it is only the default sprite i set it to in the editor and not Mgsprite
its inside a function that i made btw
that code makes little sense. Chances of having exacly 0, 1 or 2 are minute
It's very unlikely your random number will be exactly equal to these yep
controller is coming along 👍
but all of them are MgSprite
yeah man i’ve worked so hard on it
You're using the float version of Range so it's returning say 1.2225478554
the controller i wrote took me 6 months.. but i packaged it up and theres not a single project i don't use it on now
ohhh
yeah its gonna be useful for other projects
https://www.youtube.com/watch?v=jmvsCkmhy3E&ab_channel=SpawnCampGames
i was so proud of mine i made a youtube video to immortalize it 😄
In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it?
any ideas?
why would line 313 throw null ref when im already checking its not null
i did ladders but swimming i never got around too..
You need to use Range(0, 3):
- Notice the absence of
fwhich makes these numbers integers (of typeint) - We go up to 3 because the integer version excludes the max value so this will return numbers from 0 to 2.
but if i did swimming mechanic.. i could also simply also turn that into a flying mechanic
well 313 in your screenshot can't throw an NRE because there are no statements on that line. however 311 and 312 both call GetComponent and just assume it's successful
yeah that looks really good
because it does not have an Item component on it
ya thanks i really need to start paying attention 😢
In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it?
any ideas?
thx
I mean, I have a common class to all the creatures but they have subcategories
which perform different functions
In terms of code, any ideas of how should I face it?
what does this error mean?
Thanks
Thanls
could someone help please?
Sounds like you need inheritance. The base creature class should be abstract (so it cannot be instantiated), and each sub-category has its own class that inherits from the base creature class.
Implementing the specific behavior can be done using a method you override in the child class. Which means it should be also abstract in the base class.
So when you have a variable of type Creature and call the abstract method on it, it will select the correct subclass' method automatically
any help here
(the error appears complex because it happens in a lambda expression () => ..., that's how C# translates their names - it's still the same troubleshooting steps as a regular NRE though)
Why does this work but also don’t? Help I want to have a variable of a parent, and when i run the game, it works, but there are those errors
It's raining men NREs
And what about if I want them to have distinctive moves?
but the thing is it works in the game it changes the position like the parent
then something else is affecting it
Each will be implemented in the override method
!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.
Hey, guys! Because I am confused a little bit with the singleton pattern. Which objects do I have to make as singleton and which not and why?
you don't have to make any object a singleton
should I have pokemon-type moves as scriptable objects??
Why?
or how should I implement them
wdym why? there are no requirements to make any objects a singleton. you can make an entire game without using a single one in your project
dont know what this is telling me
I have heard it is neccessary for resource management and it is more efficient sometimes to use it.
it usually helps to read it
why would it be necessary for anything? it's just a design pattern that ensures only a single object of a given type exists at any time typically also with a public static accessor
the error only pops up when i have this script attached and idk why
You don't have to make any singletons. You can opt to make your managers singletons because there should only be one of them - ease of access is a bonus but not a necessity.
and if you look at the stack trace, it's likely pointing to line 23 there, yes? also you are starting so many instances of that coroutine
how can i make it so i start the coroutine once every 4 seconds then and maybe stop it after the pitch changes
you do not need to start the coroutine over and over considering you have a while loop there
but you first need to address your NRE
nre?
NullReferenceException
that error is part of a built in DOTween script
did you even bother looking at the stack trace
dont know what that is mate
did you even bother reading the link i sent to you that explains these thigns
it just says what the error is
did you know that you can read all of the words on a page? you are not required to stop reading at the first period you encounter
They read all the page, just didn't click any links lmfao
lol alright my bad very sorry
yeah i did aswell just didnt know it was called that
The link explains what it is!
my guy, the first trouble shooting step linked on that page is literally titled "i don't understand stack traces"
oh my days lad, i know and understand it i just didnt know it was called a stack trace
great! if you understand what a strack trace is, then you can look at the full stack trace for the error, find where it is ocurring in your code, and resolve it. it's a very easy fix once you know what it is
again, look at the full stack trace
the full stack trace
that is the full thing
no it isn't
hahha
cold
this is like that spongebob episode where patrick was trying to open the jar
🤣 ikr
{
craftingSplash.SetActive(true);
yield return new WaitForSeconds(4f);
}``` maybe im not understanding IEumerators correctly but i assummed that when i call this the rest of the code will not execute untill the 4s are complete. but they dont. Im calling it in a onclick method
i.e ```public void MakeItem()
{
StartCoroutine(Splash());
enter.gameObject.SetActive(true);
closeSplash = true;
ShowItems();
}``` all the underneath of Splash does not execute
coroutines, not IEnumerators
and yeah you are not understanding coroutines
{
craftingSplash.SetActive(true);
yield return new WaitForSeconds(4f);
enter.gameObject.SetActive(true);
closeSplash = true;
Debug.Log("here is the rest");
ShowItems();
}``` only the first two lines work
sorry first line
no debug result
Anyone have any ideas why this isn't working? The way i think it isnt working is that i have a debug.log for its state, and it never goes into moving to pheromone state. No errors though
{
ParticleSystem thisPheromone = other.GetComponent<ParticleSystem>();
if (thisPheromone.tag == "phermoneF" || thisPheromone.tag == "phermoneS")
{
if (currentState == AntState.Looking_For_Food)
{
currentState = AntState.Moving_To_Pheromone_F;
}
if (currentPheromone == null)
{
currentPheromone = thisPheromone;
}
else if (currentPheromone.main.duration > thisPheromone.main.duration)
{
currentPheromone = thisPheromone;
}
}
}```
Then your GameObject is being deactivated or destroyed after you start the coroutine
Or there's an exception they're ignoring
Add Debug.Log to see if this code is ever running and log the if condition variables to see why or why not
If I set the rigidbody to Kinematic, everything works great. Initially it is set to false, and upon collision with a meteorite it is set to true, resulting in the destruction of the rocket. The problem now is that the limit no longer works because there is no rigid body that behaves as if it were dynamic. However, when I choose a dynamic rigid body, even if the gravity scale is adjusted, all the parts start to fall, or it happens that the parts do not move together. Here are all the scripts and a video.
https://gdl.space/utalucucuy.cs PlayerScript (Rocket)
https://gdl.space/xafuwozure.cs BoundaryScript
https://gdl.space/vojajuvoge.cs Rockpart (Wings,Body,Engine,Arrow have that script)
I just logged at the start to check if the collision occurs and it isnt printing. Is there something i need to turn on on the colliders to allow it to work on particles? Or something i need to attach to the particle except just turning on collisions
enter is only called twice here, and set active false in start
Yes OnParticleCollision has very specific requirements
I don't know what that means.
or how it's relevant
would you be able to explain what makes it trigger? Because as far as i know normal collision fields dont work with particles
its called after the wait for seconds. what can canel that out
Did you read all of the notes here? https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnParticleCollision.html
not sure what a "collision field" is
as in OnParticleCollision or OnTriggerExit etc
Again OnParticleCollision has specific requirements and they're all spelled out in the docs I linked. Read all of it.
Hey, I need some help with sprite renderer. I have a Player2D prefab asset and a Ship prefab asset. I'd like the Player2D prefab asset to use the SpriteRenderer that comes with Ship. As it stands:
public class Player2D
{
private SpriteRenderer spriteRenderer;
public Ship ship;
void Start()
{
spriteRenderer = ship.GetComponent<SpriteRenderer>();
}
}
Naturally this doesn't work, as there's still a SpriteRenderer assigned to Player2D. I genuinely have no idea how to do it :^( I should probably use the spriteRenderer in some way but not sure how.
Can someone give me some guidance for a second? Im pretty lost on how to fix the errors here, I have a random spawn for my enemies so i set it up to be stored in the script so it can be used in the patrolling script but it keeps being seen as an input for one, im getting errors for line 25 and 48 of the patroller code (first is patroller, second is spawner)
https://hastebin.com/share/ugeramehiw.csharp
https://hastebin.com/share/atafamugiv.csharp
Try to Instantiate the prefab i.e // Instantiate the Ship prefab Ship shipInstance = Instantiate(shipPrefab, transform.position, Quaternion.identity); spriteRenderer = shipInstance.GetComponent<SpriteRenderer>();
How do I then assign it to the SpriteRenderer of Player2D?
PatrollingEnemy, L25: There was no active and enabled object with a MazeGenerator script on it, or its .startingNode did not have a value at the time this code was executed.
Error on line 48 is directly linked to the error on line 25. Fixing the first will fix the other
is DOTween the best approach to animate a hammer taking out the individual nails on these boards
Push
Is there a way to turn of the physics of a collision with a particle and gameobject so they pass through eachother but still record the collision?
Generally speaking? Not really, no.
But "best" approach is dependant on the skills of the developer.. the general best aproach would be to actually animate it properly, you'll have a much better look.. however, if you can't do that animation, then the best approach for you is the way you can implement the best
Is this for me?
obviously not, it's a question .. and it has nothing to do with your thing
No..
is there any easy way to stop a rigid body from sticking to a wall without using a physics material
since i dont want my character to slide down slopes
Yes, give me 2 seconds, I also have the rigid body problem today. I have to see what I've done
Give me 5minuts
@dire tartan can you send the script
ive built out this scroll wheel inventory system... and im trying to brain storm a way to allow gaps in it... like only populating as u pick things up
https://www.spawncampgames.com/paste/?serve=code_960
i have zero idea about how to do this... except possibly requiring a <List> vs the Arrays im using now
any tips/pointers?
example: i still want them to stay in the correct order, but skip the ones that havent been acquired
my movement script?
That script with the Object who have the Rigidbody
if u can put the material on the wall instead of hte player
If the capacity is fixed then yeah you can use an array, and keep the empty slots as nulls
yeah that works but if the player is walking into the wall it sticks
and then just do a loop of the array to get the next index of a weapon i have
ya, it'll be fixed.. as its just weapon pickups..
you could also do a raycast to know when ur on a slope... and can change the material ur using for ur character only then
private void FixedUpdate() {
MovePlayer();
CheckSurfaceAngle();
}
private void CheckSurfaceAngle() {
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, playerHeight * 0.5f + 0.3f, WhatIsGround)) {
float slopeAngle = Vector3.Angle(hit.normal, Vector3.up);
if (slopeAngle > 45) { // Assuming 45 degrees as the limit for walkable slopes
// Logic for steep slopes (e.g., prevent sticking to walls)
rb.useGravity = true; // Ensure gravity is applied
} else {
// Logic for walkable slopes
rb.useGravity = false; // Optionally stop gravity to prevent sliding down slopes
// Apply movement here or in the MovePlayer method, depending on your game's physics needs
}
} else {
rb.useGravity = true; // Apply gravity if not grounded
}
}
Try this @dire tartan add this
in your script
Yeah it's the easiest, checking for a populated slot is a simple arr[index] != null
Nice AI code
when is not working remove it , i give my best for help but im not the best
Hi
shouldnt be a performance problem as its only gonnna get called when u go to swap weapons
i wouldn't be giving ai code to people as solutions unless ur positive it'll work
if theres any problems in the code.. they'll be coming back for solutions
that code wouldn't work anyway.. as his problem happens WITH gravity
it works but if i keep moving forward into the object i stick
its not a gravity problem.. its a force problem
yea.. taht code doesnt solve ur issue
but its on the right track..
how would i go about fixing my problem?
as i mentioned earlier.. u can make a function check if ur on a slope.. if u are on a slope set the physics material to the material with friction...
if theres no slope under ur feet set teh material to one without friction
Can anyone help me fix this error?
Code:
private void OnTriggerEnter2D(Collider2D collision)
{
ParticleSystem thisPheromone;
if (collision.gameObject.tag == "food")
{
if (currentState == AntState.Moving_To_Pheromone_F || currentState == AntState.Looking_For_Food)
{
//Debug.Log("Collision Enter FOOD");
currentState = AntState.Moving_To_Food;
if (currentFood == null)
currentFood = collision.gameObject;
}
}
if (collision.gameObject.tag == "pheromoneF" || collision.gameObject.tag == "pheromoneS")
{
thisPheromone = GetComponentInParent<ParticleSystem>();
Debug.Log(thisPheromone.tag); //Line 248
}
}
Error:
NullReferenceException: Object reference not set to an instance of an object
Ant.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Ant.cs:248)
too many alex's
fr xd
this is happening b/c ur checking the collsion object's tag for a certain thing...
oooor.. maybe not..
what line is line 248
Yeah cause i wanna check its the right type of object by if it has the tag
Assets/Ant.cs:248) <-- shows u the line number
ahhh.. soo yea.. thisPhermone doesn't have a tag variable
thisPheromone is null because the ParticleSystem on the line above isn't found
if u want to check the tag.. u need to get its gameObject and check that for the tag
Thats weird because it should have particle system
tag is a property on partical system
is it?
im trying to do collider checks on particles so it follows it down the gradient and particle collisions wasnt working so now im trying with an empty gameobject as the child of the particle and doing collision checks with that and its parent
u dont have to get the gameobject first?
it wouldn't compile if that was the case, and the docs I linked to show it as an inhereted property
Can you only create xml files within the built game, and not the Editor?
ya, i see now.. interesting
does this look like it was made with a Tween animation?
because that is what i am aiming for
yeah but i mean the animation lol alright cheers
couldnt be bothered getting further into the game to get the hammer xd
:)
Use it on a field
Creating an enum does not make a field, it's as if you created a class in a class.
You need something like ```cs
[Space(5)]
public ClimbingStage clibmingStage;
(create a field of the enum type)
- naming conventions: enum values should be in PascalCase:
Start,Waiting, etc.
um can someone help me for this script
IEnumerator Reload()
{
IsReloading = true;
Debug.Log("Reloading...");
animator.SetBool("Reloading", true);
yield return new WaitForSeconds(reloadTime - .25f);
animator.SetBool("Reloading", false);
yield return new WaitForSeconds(.25f);
currentAmmo = maxAmmo;
IsReloading = false;
}```
so basically it says that the last bracket is not found
how come
i dont see anything interfereing
Maybe after the block, do you have a } to close the class?
If it's the end-of-file, the error cannot be reported further than the last character, your } here
everything is closed
Post the entire script in a paste website
📃 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.
@short hazel i cant it says i got too much words
Never heard of anyone encountering this error
Unless your script is 10000 lines long there should be no problem
Do you have to create the actual xml files outside of the editor (in like the Registry Editor and/or File Explorer)? Or can you create them from within Unity? Does creating them only work in the built game, not the Editor version?
Try another website, it might be down and reporting false errors
what does this error mean?
interactZoom is static, so you access it by using the class name directly: CameraZoom.interactZoom
You do not need a variable to access static stuff
alright cheers
how do i send it
Hit the "Save" button first, then copy-paste the URL
it does
No
Not in the code you gave
The very last } closes IEnumerator Reload()
The class
my movement script is 1200 lines and im like half way done
holy
should i be seperating this into different scripts?
like the code is easy to navigate so im not sure
I would probably separate them into different components with individual functionality.
Yes
hello, im having trouble with my ground check raycasts returning true too early. heres the raycast and the frame where it changes the state from falling to grounded. souly based on if this code returns true.
{
int hits = Physics.OverlapSphereNonAlloc(groundCheckSphere.position, capsule.radius, groundedResults, groundedLayers);
return hits > 0;
}```
Can someone help me? Im really lost for words now... I've been staring at this for hours and I really can't figure it out whatsoever.
public class Weapon : MonoBehaviour
{
public GameObject bulletPrefab;
public float fireRate = 0.5f; // How often this weapon can fire
private float nextFireTime = 5f; // When this weapon can fire again
public float bulletCount = 1;
void Start()
{
nextFireTime = Time.time; // Initializes nextFireTime when the game starts
}
public void Fire(Transform[] spawnPositions)
{
// Check if it's time to fire again based on fireRate
if (Time.time > nextFireTime)
{
if (bulletCount == 1)
{
Instantiate(bulletPrefab, spawnPositions[1].position, spawnPositions[1].rotation);
}
else if (bulletCount == 2)
{
Instantiate(bulletPrefab, spawnPositions[0].position, spawnPositions[0].rotation);
Instantiate(bulletPrefab, spawnPositions[3].position, spawnPositions[3].rotation);
}
else
{
foreach (Transform spawnPosition in spawnPositions)
{
// Instantiate bullet at the position and rotation of each spawnPosition
Instantiate(bulletPrefab, spawnPosition.position, spawnPosition.rotation);
}
}
// Update the nextFireTime to be the current time plus the fire rate
nextFireTime = Time.time + fireRate;
}
}
}```
The problem lies in index being outside the bounds of array, but the problem only started happening when I attempted to use `Ship` prefab as reference in `Player2D`.
Player2D
void Start()
{
//Set screen orientation to portrait
Screen.orientation = ScreenOrientation.Portrait;
//Set sleep time to never
Screen.sleepTimeout = SleepTimeout.NeverSleep;
missileCountCurrent = missileCountMax;
missileIsRecharging = false;
if(ship == null)
{
ship = Instantiate(ship, transform.position, Quaternion.identity).GetComponent<Ship>();
}
SpriteRenderer shipSpriteRenderer = ship.GetComponent<SpriteRenderer>();
SpriteRenderer playerSpriteRenderer = GetComponent<SpriteRenderer>();
if (shipSpriteRenderer != null && playerSpriteRenderer != null)
{
playerSpriteRenderer.sprite = shipSpriteRenderer.sprite;
}
transform.position = new Vector3(pos.x, pos.y + 0.2f, pos.z);
}```
Am I accessing the array the wrong way? Is it possible I simply just didn't reference the Ship prefab correctly?
public class Ship : MonoBehaviour
{
// Ship specific properties
public Weapon weapon; // Weapon
public Transform[] bulletSpawnPos; // Bullet spawn positions
I assume the error is in the Fire method of the Weapon class
You're accessing spawn pos at index 3
you only have 3 elements in the array on the picture
Oh yeah it did fix it, but the projectiles still won't come out
Debug what it hits.
I just happened to change the variable as you specified it (there's a variable responsible for projectile count)
problem is... the ship is still not shooting despite everything being the same code before encapsulation
ya code lacks debug.logs
should be plastering them if you're running into an error like oob
i think i got it, i had to test the position and move it accordingly. It looks a bit weird and probably could change the radius to help, idk it works now
^^ debug helps so much with state machines. I only put them in enter and exit. update is too much
Yeah I relied too much on debug mode in the past, Unity isn't so good with it, that's on me to be fair
So yeah, you should add debug logs as well.
I'm trying to read a serialised binary file of an array, but when I try to deserialise it says that it "cannot implicitly convert type 'object' to type 'int[]'" and that an explicit conversion exists, and asks if I am missing a cast. How do I convert object to int[]? Never had to deal with this before...
show the relevant code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class BinaryArray : MonoBehaviour
{
public UnityEngine.UI.Text textbox;
int[] number = new int[3];
public void Start()
{
number[0] = 1;
number[1] = 2;
number[2] = 3;
string filename;
FileStream myFileStream;
filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
myFileStream = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryformat = new BinaryFormatter();
binaryformat.Serialize(myFileStream, number);
myFileStream.Close();
}
public void FixedUpdate()
{
string filename;
FileStream myFileStream;
filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
if (File.Exists(filename))
{
myFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryFormatter binaryformat = new BinaryFormatter();
/!\ number = binaryformat.Deserialize(myFileStream);
}
myFileStream.Close();
else
return;
}
}
problem at /!\
well first off, stop using BinaryFormatter. it is a security risk
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
you remove that code entirely and use a better way to serialize deserialize
Thing is it's for an assignment and prof wants us to use binary
but if you don't mind potentially exposing your players to malicious code being executed on their devices, then just cast to the type you need
How would I do that
just (int)?
cannot implicitly convert type 'int' to type 'int[]'
rolls eyes
if you want to be snarky, then just read the error
¯_(ツ)_/¯
Int is not an array of ints
have you bothered trying it
Did you try?
fair enough
also unrelated to the error, but deserializing in FixedUpdate is a yikes 😬
lemme
why?
would update be better?
why would you do either? why would you want to read and deserialize the data every frame
that is a fair point actually
I'm trying to create event channels through scriptable objects (like shown in the Unity devlog for Chop Chop). To simplify my life, I want to create a template channel that I can instantiate for differnet types, so I don't have to write out the code. It doesn't seem to work. Am I am doing something wrong, or is this not supported in unity?
Basically, upon instantiation, I want to create an SO with UnityEvent<int> or another with UnityEvent<MyScript>.
im trying to get into vr dev, but when im importing the room, it appears all pink
this is the guide i use: https://learn.unity.com/tutorial/vr-project-setup-1?uv=2020.3&courseId=60183276edbc2a2e6c4c7dae&projectId=60183335edbc2a2e6c4c7dcb#60521ebbedbc2a73ff60372c
what would be the most optimal way of calculating ladderMoveDirection? (direction to add force to) cs moveDirection = orientation.forward * y + orientation.right * x; slopeMoveDirection = Vector3.ProjectOnPlane(moveDirection, slopeHit.normal); ladderMoveDirection = ; cs [Range(-1,-90)] public float upperLookLimit = -88.5f; [Range(1,90)] public float lowerLookLimit = 88.5f;
i also want to use the upperLookLimit and lowerLookLimit
i dont need the side direction - x
just like the way im looking between upperLookLimit and lowerLookLimit
im not sure
Considering Unity doesn't like serializing generics, I doubt this would work without explicitly adding the generic type / constraint
Updated code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class BinaryArray : MonoBehaviour
{
public GameObject textbox;
GameObject numberOutput;
int[] number = new int[3];
public void Start()
{
number[0] = 1;
number[1] = 2;
number[2] = 3;
string filename;
FileStream myFileStream;
filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
myFileStream = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryformat = new BinaryFormatter();
binaryformat.Serialize(myFileStream, number);
filename = Path.Combine(Application.persistentDataPath, "binarr.bin");
FileStream myFileStream1;
if (File.Exists(filename))
{
myFileStream1 = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryFormatter binaryformat1 = new BinaryFormatter();
number = (int[])binaryformat1.Deserialize(myFileStream);
GameObject myCanvas = GameObject.Find("Canvas");
for (int tempNumb = 0; tempNumb < number[2]; tempNumb++)
{
numberOutput = Instantiate(textbox);
/!\ numberOutput = transform.SetParent(myCanvas.transform, false);
}
}
else
{
myFileStream.Close();
return;
}
myFileStream.Close();
}
}
At /!\ it says this:
I got absolutely no idea why
The method does not return a value . . .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointFollower : MonoBehaviour
{
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializeField] float speed = 1f;
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
so i made this simple side looking code but how do i add a limit to it???
Well... did you assign waypoints?
i think you need to specify more
i guess
Yes I assigned everyone 2 waypoints
All objects that are moving work perfectly fine and are assigned properly
Type t:waypointfollower into the hierarchy search, check every object in it
Could also do an early return if waypoints has nothing in it
The hierarchy of unity....
Keep track of the rotation in Euler and clamp that value. Then use that value to set the rotation.
more simple please i dont really understand
I'm not sure how to make it more simple. What part do you not understand?
the clamp and euler part
Ty, Arigatō
if I have DontDestroyOnLoad() enabled a GameObject, do I still need to make scene changes additive for the scene that contains the GameObject?
DDOL is a scene
To clamp, means to limit a value in a certain range.
https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
Euler is referring to Euler angles. Have you not heard of them?@clear seal
You add objects to it, not enable it on objects
oh, I see, and that scene will never get destroyed when you load a new scene?
And no, DDOL does not get unloaded
awesome, thanks
Correct
i did but they kinda confuse me like the math and quaternion stuff
Euler angles is what you learn at school. It's how humans measure angle most of the time.
ohhhhh
we just call it angle for us lol
That could mean multiple things
Angles can be measured in radians too.
Euler is specifically one type of angle
well as far as i learn at school(7th grade) angle are just like degrees
No. Angles can be in degrees or radians
Is there any way to mute all music and sounds coming from my scene while im testing my game without having to go and uncheck all Audio Sources?
That SHOULD have been taught around then as well...
prob my misunderstanding from english to french i prob just know them but dont know how they are called in englidh
¯_(ツ)_/¯
Just angles. Angle is an "umbrella" term. It is not specific
private AudioSource audioSource;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
color = GetComponent<SpriteRenderer>().color;
audioSource = GetComponent<AudioSource>();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Coin picked up");
audioSource.Play();
Destroy(gameObject, audioSource.clip.length);
Debug.Log("Coin Deleted");
}
}
No sound played on pickup? Audioclip works just fine if played on awake
im trying to get into vr dev, but when im importing the room, it appears all pink
this is the guide i use: https://learn.unity.com/tutorial/vr-project-setup-1?uv=2020.3&courseId=60183276edbc2a2e6c4c7dae&projectId=60183335edbc2a2e6c4c7dcb#60521ebbedbc2a73ff60372c (yes i use 2020)
Perhaps a render pipeline issue. Perhaps an issue specific to vr, dunno.
Try in #🥽┃virtual-reality
Is... using this kind of "recursion" right? Cause something tells me this is so wrong for some reason...
Not kind of, it is recursion
It is meant to be used like that then?
Picking a random choice, if it's not available, try again
Sure, makes sense
But I would have a max tries
you definitely dont need to do it like that, that could just be a while loop. or store a collection where you only have valid selection
Recursion is fine too
It is better to use a while loop for this?
yes
recursion is used more for solving data problems, but really recursion isnt needed unless you are doing functional programming. Iterative solutions are better and faster
I mean, she likely has a list with only a few things, unless there's tons of gameobjects calling this function itll never incur any noticable difference. Iteration is usually better in these instances tho but her solution seems to be just fine now
It could easily be an infinite loop as is
Also, I am pretty sure the thing I am doing should be stored on a scripteable object, but not sure how to do that actually, or if it even matters that it is instead an empty object in scene that stores it
You could just as easily do that with a while loop. That's not a fault of recursion
Never said it is?
I thought thats what you implied, nevermind
Just that the code AS IS, is not great
Gotta add something like a hard stop to end the loop
It is meant to be a pool of several prefabs of different rarities, this script is supposed to be called by another one to tell it what it should spawn
Seems fine, like he said just make sure you have something to break the loop.
So it probably needs to be optimized to be called with certain frequency and with some decent data to manage
If you want to change to a while loop as well that could work. I would go with whichever makes the most sense at the moment and change later if needed for scalability or performance
Is there a way to prevent Unity from logging this whenever I compile?
It wouldn't be logging anything by default so perhaps you've got a script or asset causing it to log that.
if you scroll in the log, does it give you a script location that is triggering that log?
Hi yall, can someone explain to me why it doesn't display the value of points properly? I update the points in two different scripts, the original one and the coin script but when I print out the value of points in the original script it shows the updated version but for some reason the updated version doesn't show up on the screen
The updated version includes what the coin script changed
Post the code to an external site and paste the saved link here !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.
Is there only one Points object
And can you show the points script
Looks like the Gameobject.Find does not work in that case, you should make a public property in that script public PointsCounter currentScore; and apply it through the inspector
Yea or currentScore is null
If the value no longer updates likely the score object is no longer available.
okay
Guys I got it to work thanks
Ok, I changed the actual pool from where the powerUps are being drawed to only include availiable ones so it should be more efficient now. I am kinda worried for how I should handle stuff like, maybe in the future I want some powerUps to be avalible after some kind of achievement/unlock.... And I not sure my code can handle something like that right now
And I kinda want to address that now that changing it would be way less convoluted
Like, if a certain powerUp is avaliable is set on a bool on the powerUp itself, which makes it so... I cannot actually change it from the prefab, how shoud I manage this?
Should it just be stored somewhere else that I can change?
Cause I cannot assign a reference to a prefab to a script and modify parameters from it before it is instantiated right?
Could you not just add more at runtime should they unlock more?
What do you mean?
so i want to make my charachter crouch by making it small but how do i do that without the child to be affected?
I think transform has an overload to affect children?
Do you mean property? Transform is not a method, thus does not have overloads
Edit: oh, do you mean GetChild() ?
overload is ?
Like adding powerups to the list at runtime. If you unlock an achievement then adding it to the list of available powerups
Same method name, different signature
Nah, ignore me, I may be completely off. I though some of the transform methods did have an overload to affect children
But I cannot find it so I guess I dream it XD
Sry for spreading missinformation I guess
ima watch a tutorial
Guys this works the trajectory is fine but its too slow the target moves from its place by the time it reaches and when i increase velocity its trajectory changes, any ideas please?
is there an obvious reason why setting velocity works, but using MovePosition doesn't work? (for rigidbody2ds)
or do you think it would be my other code interfering
Parent/child relationships are through the transform. Of course there are methods in the Transform class that affect children. But "affect" is rather vague, so I'm not sure exactly what you mean
Nah, forget about it I am probably wrong I though you could do something like... Scale(1, false) to prevent it from affecting children
If I want to zoom in on an item when inspecting, should there be a new camera? or just move the main camera towards xyz? but problem is, I am using a character controller that is with the camera and moving the camera might move the characters also, and how would the code look like?
and if it is a new camera, would i make many cameras for each item?
Cinemachine is what you would want to use
i tried watching tutorials and none were responding to my needs
not even close
:(
It allows you to set up virtual cameras, and then just activate/prioritize the virtual camera you want the real camera to use. Cinemachine will handle the rest.
okok c: thank you steel
i just fixed my error with the pink parts on models
i was using the wrong 2020.3 version
I just did this the other day actually, it's as easy as changing which cinemachine is the priority camera iirc. Youll see it in the settings. It's an awesome package
If you have trouble you can ping me since I just wrote something for that a few days ago
for future reference, try to stay away from GameObject.Find(). its a pretty expensive method and its just better generally to have a reference set to the object
same thing with .GetComponent<>()
Hi.. This is a movable platform that I got. Whenever my player steps on it my player remains stationary but I want his feet to stay grounded like a plant on that blue platform and move with it instead of drifting as if it's made out of ice
Is there a way to generate stubs for all the methods I need to implement for an InputAction map
You'd need to apply the platform velocity to the character.
i tried to implement a vCam in place of my main cam and now i lost the ability to rotate my player :/
how can I set my imported sprites to automatically be 16 pixels reference with compression and point filter on?
easiest is probably use a preset https://docs.unity3d.com/Manual/Presets.html
if you want it to be fully automatic you have to do a bit more work i think
how do I go about passing the _gameGrid reference in GameGlobalScript to the static class GameTurnManager? it needs to be accessible for AdvanceTurn and many other functions yet to be written.
[ExecuteAlways]
public class GameGlobalScript : MonoBehaviour{
[Header("GameObjects")]
public GameObject _gameGrid;
void Awake(){
GameGridManager ggm = _gameGrid.GetComponent<GameGridManager>();
// set up game grid
ggm.Startup();
ggm.TestPlayerCreate();
ggm.CreateGrid();
}
}
public static class GameTurnManager{
public static Dictionary<int, Player> Players {get; set;} = new();
public static int CurrentTurn {get; set;} = 0;
public static Player CurrentPlayer {get; set;}
public static void AdvanceTurn(){
CurrentTurn += 1;
int PlayerIndex = CurrentTurn % Players.Count;
CurrentPlayer = Players[PlayerIndex];
foreach(GameTile tile in _gameGrid.Tiles){
}
}
}
Don't know the whole context, so it might be a bad suggestion, but:
GameTurnManager.AddGrid(gmm);
Like, why is it static? Where's AdvanceTurn called from? Why does it need the grids? Too many questions and no answers...
Advance turn is called from a ton of other prefabs script component as they are interacted with. It's static because I never need more than 1 turn manager and the code that will be calling all the methods of GameTurnManager will be cleaner
"being called from a ton of other prefabs script components" doesn't sound clean at all.
it needs the grid class because each time the turn is advanced it needs to iterate over every GameObject in a list within GameGridManager
Sounds like the opposite of clean. And you're helping make it so by giving everything a global access to it.
how do I implement someting where a car (or any mesh) gets rotated when I click on it and go back to its original rotation after, and assign an ID if it is a car or a broom or a carpet, if it is a car, it will be rotated 90 degrees from x, then back to the original value after clicking again, then for the broom, it will be rotate by 45 degreese in y, then back to its original value, then for carpet, rotated by 180 degrees in z, then back to its original value, the ID would be used so that i can just hook it to an object to tell how it would rotate when click, I am using this for learning purposes 
Then let the game grid manager provide it the grids.
Sounds like a pretty simple thing to do. What do you have so far?
it looks like this now for the interactable objectspublic UnityEvent onInteract; public int interactableID; public Vector3 defaultRotation; public Vector3 toggledRotation; i have the raycast thingy in the other script for interactor
but i dont know how they would work
i have the idea but cant put it into code
how are you all guys
how so? if there are a lot of objects that can be interacted with each turn, and once any one of them is interacted with they just call GameTurnManager.AdvanceTurn(); thats pretty clean right?
these gameobjects are dynamically created and destroyed by the GameGridManager class
each game tile prefab has this on it (stripped out code unimportant to this example):
public class GameTile : MonoBehaviour{
//bunch of data stored here
}
void OnMouseDown(){
//code for handling how this tile has been interacted with
GameTurnManager.AdvanceTurn();
}
I was thinking of putting something like interactableID: toggleRotation 1 = 90,y,z, 2 = x,45,z 3 = x,y,15
then maybe assign the default rotations underneath like interactableID: defaultRotation 1 = 0,y,z, 2 = x,0,z 3 = x,y,0
but that wont work i think
I see. So you increment the turn after the player interacts with any of the tiles. This is not very intuitive. I'd rather raise an event that the game manager is subscribed to and let it handle advancing the turn logic, but that's fine.
You can just pass the grids from the game manager to the turn manager.
In fact, I'd just make gameManager hold an instance of a turn manager class, so as to not make it static.
Not sure what not sure what that represents? What is the toggleRotation?
Are you trying to provide different rotation for different IDs?
seems intuitive enough to me, at least with how I need the game to handle turn advancement. I'm fairly new to unity so I'm not familiar with what you mean by "raise an event the game manager is subscribed to"
there would be a lot of cars and brooms in the game i am planning to make, I plan to assign an id to them so they know how they would rotate if they are cars, brooms, or carpets when they are interacted in the interactable code, but still not sure if this is the best approach
this is a part of the interactor code to interact with the interactable (interactable will be where i assign the default rotations and id)
{
if (interactable == null || interactable.ID != hit.collider.GetComponent<Interactable>().ID)
{
interactable = hit.collider.GetComponent<Interactable>();
//Debug.Log("New Interactable"); //something to check debug logs
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
interactable.onInteract.Invoke(); ///this is where I would replace with the transform thingy
}
}
}
}
}```
Events are not a unity concept. They're a programming pattern. In C# you'd usually use delegates for events:
public event Action InteractedEvent;
You can subscribe to events in your tiles from the game manager and handle the logic on the event.
You can read more here or look up events in unity context:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
ok I'll look into that, for now you said just pass the gameGrid to the GameTurnManager, can you give me an example of the syntax for this? Everything I have tried so far doesn't work becuase GameTurnManager is static
You can have a scriptable object or something holding a dictionary that maps IDs to your desired rotation and then get the rotation from the dictionary and use it.
I think I already gave an example in one of the first replies
Here:
#💻┃code-beginner message
can you help me make a simple project using that? if ok 
I can help you direct in the right direction.
okok, I will try 
how can we create a dictionary? should it be on a new script, and should every item have the dictionary script? can I just put it in the interactable script
If you want easy access to it, having it in a scriptable object or a singleton might be a good idea. Otherwise, you'd have to have it on every component that needs access to it(or pass the reference around).
As for creating it, you can check the documentation. They have some examples too:
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-8.0
I don't think thats what I'm looking for, The class GameTurnManager needs to just reference the gameGrid GameObject in the same way GameGlobalScript is. GameTurnManager has no method .AddGrid(), and ggm is defined in another class entirely
That's the thing. Create that method.
//In GameGlobalScript Start or wherever you want to pass in the grid
GameTurnManager.AddGrid(someGridReferenceOrListOrArrayOfGrids?);
i dont know what the terms mean for scriptable object or singleton, but I do have a camera with the interactor script, and the interactable layer and an interactable script to assign those with interactable in layer, which or where should i put the dictionary thingy (also, are dictionaries scripts also?)
If you need it only in your interactor script, then it would be fine to create it in that script.
thank you dilch, I will try making a code, I'll show later ok 
Oh I think I see what you're saying now. In GlobalGameScript Awake() call GameTurnManager.Addggm(gmm)?
Yes. Doesn't have to be in awake. Should be somewhere when you already have references to the grids.
dilch, is this ok? void Start() { rotationDictionary.Add(1, new Vector3(90, 0, 0)); rotationDictionary.Add(2, new Vector3(0, 45, 0)); rotationDictionary.Add(3, new Vector3(0, 0, 180)); }
not sure if correct
Looks fine so far.
Thank you, this gets me to where I needed to be for now. I will definitely look into Events and setting up a game manager
{
rotationDictionary.Add(1, new RotationData(new Vector3(90, 0, 0), new Vector3(0, 0, 0)));
rotationDictionary.Add(2, new RotationData(new Vector3(0, 45, 0), new Vector3(0, 0, 0)));
rotationDictionary.Add(2, new RotationData(new Vector3(0, 0, 180), new Vector3(0, 0, 0)));
}``` is this better? i want it to go back to the original position after (i dont know if this works)
or is there a better way
Btw, your GameGlobalScript kinda sounds like a GameManager. Would add a few changes, but overall it seems like that's it's purpose.@kind sentinel
If your default rotation is always 0 0 0, then maybe there's no need in that?
I guess so. But maybe you should cache that in a script belonging to a rotated object
I dont know how it works but, will it work? it wont mess up?
is it ok to have methods with same names?
targetObject.Rotate(rotation);
///In target object
void Rotate(SomeType rotation)
{
lastRotation = transform.Rotation;
//Your rotation logic
}
void Unrotate()
{
transform.rotation = lastRotation;
}
```@modu._
Yes. This is called method overloading.
oh okay thanks
ah wait, I think I found a problem in my previous code
if I set many things with the same id
would that mean when i click something with similar id, everyone gets rotated?
I don't see any rotation related code in the last snippet, so 🤷♂️
okok, I will try
They need to have different parameters though
yup i know
But yes, method overloading is a thing and that's actually already built into some of the stuff you use (Debug.Log for example)
Theres a few ways, theres a website that ive been linked to a few times, ill see if i can find
it
here we are
If I declare a Class A a = new Class(); at the top of script. And there's function AA() return a;
The question : Will it allocate memory to store "a" when each time call the function AA to return a?
What exactly are you not sure about?
No. It would just pass the reference to that object.
SerializedFields are the most efficient one? Huh, usually the easiest solution isn't the best one
Maybe but atleast you arent using .Find() then everything is well
I always thought GetComponent would be faster
You can always test
Oh.Thx.I think I was messed up with something
im still confused on how to code, I want to master it
but no matter how many tutorials, I feel like I am not learning, I only retain 20%
Can someone explain to me why my enemy won't move after hitting a collider for a wall?
https://hastebin.com/share/deriruqeza.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I think it might have to do with my rotation but im not sure how to fix it because i've tried 3 different methods atp
are there tips to learn better? if ok 
You should analyze your current understanding and actively look into topics that you don't have full understanding of.
If you give concrete examples of what you don't understand, we might be able to point you in the right direction.
Also, going over structured courses, like the one on unity !learn could be useful:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I will do my best, thank you dlich, lazy
Btw,Can I do this, I have a private "networkObjectsMap".Can I use function to get it like this and access it in other script? For performance reason?Do I?
ah, I cant put gifs 
Everyone learns at their own pace. At the end of the day it's a skill, and it takes quite a while to get "good".
I think it's best to pay mind to "techniques" more than explicit implementations.
Understand WHY someone is doing something a certain way in a tutorial.
As opposed to just copying.
That being said, some tutorials are not conducive to that type of learning.
You can. You can also make a property to access it.
public Type PropertyName => privateFieldName;
A lot of the go-to Unity tutorial channels can be... strange.
I c!
Blackthornprod's early videos always irked me.
blackthornprod 
Those are fine and kind of fun
I know he got into some drama over one of them recently.
Im still having issues with my coroutine just does not seem to wait for 4s and hit anything underneath it
So i thought the issue might be the button i was originally calling it from as i deactivate it. So instead i created a new function called SplashScreen and called the coroutine from there just incase it was a deactivate game object issue.
Add an OnDisabled in the script and log something correspondingly. Then see if it's being printed.
you do realize that the End Splash will print before the yield don't you?
Yes i understand that the rest of the code would run. i was just adding any text just to double check
So, there is nothing wrong with your code, so it must be a problem with the object that is running it
show your full console tab
OnDisable is never called
Are there any errors maybe?
Hmmm... Are the latest changes even compiled?
Add a log at coroutine start
Yes, log before and after the yield also add an OnDestroy method to the script and log that
there you go, sorry i have to collect crafting materials each time to open crafting
Share the whole script. I want to see the on disabled method
yh two secs
Hello
Are you setting time scale to 0 perhaps?
Dose anyone know how to make a menu screen on unity
Watching YouTube tutorials or courses isn't as efficient as picking up a good book and learning programming that way
what line did you see that to
can you change the name of the IEnumerator
I didn't. I'm asking you.
maybe theres a method or class with the same name
yes but you need to learn the basics
Time.timeScale. Are you setting it somewhere?
What are the basics
no not on this script,
Do you do it in some other script?
yes i could see that objects stop animating when he opens the crafting menu
could be a suspect
Can you print the value of Time.timeScale when starting the coroutine?
yes when i pause
Isn't this a menu? Are you pausing the game through Time.timeScale before opening the menu?
Do you know how to make a menu screen
and the game is in pause mode
just search for some online tutorials, there are plenty
what runs when you do this craftingSplash.SetActive(true); ?
Ok, well, WaitForSeconds isn't gonna work then.@honest haven
when timescale is 0 then the wait for second wont work
That shows the pop up in the screen shot. just shows what you crafted
Well the more accurate thing to say is WaitForSeconds takes into account the timescale.
Yes, bugger. i need that to pause the player, any ideas for a work around
comment out the timescale and try again
but does it pause the game?\
I think it likely did
that's it then, craftingSplash.SetActive(true); pauses the game so the yield wont run
mmmm singletons
lol yeah only using singtons for crafting menu, game manager and crafting manager as there is only one
iz k
What lazy shared. But ideally,you shouldn't use timescale for pause.
Wait what's your suggested alternative?
For pausing in general, not specifically his issue.
did you use any comma between declaring variables?
Relatively
The game logic should be build with a pause feature in mind, controlled by some game manager. Game systems should be checking for pause before running.
Thanks
actually my stuffs is working is just i didnt know how to show and hide the TextMeshProUGUI
Is making a 2d game more difficult than 3d or the same
Blegh. Time.timescale go BRRR
Unity and Unreal have the biggest user base and libraries so I just went with it
like a selext option for dev mode to do custom service
Very little difference, code wise
I tend to use both time scale and an isPaused bool in a manager for pause
Code wise ya art wise OH BOY
i tried with EditorGUILayout but i abit mess up
I personally think you should try 2d or 2.5d first
3d needs model
Or go the paper mario route.
I am trying to make a 2d fighting game
ye we have plenty sprites (aka assets for that)
I got it all planned out
I find snatching 3d models kinda dumb because your game would easily turn into a jumble of unrelated mess
Just use primitives 🤷♂️
But let’s not get off topic for the channel, it’s a code channel.
2.5d is the way to go if you want some height in your game, handling height in 2d is easily nightmarish
cant it's a video tutorial but it's the same as his
That was a late response😅
I don't even remember your issue.
if(currentGun.carryBulletCount > 0)
{
currentGun.anim.SetTrigger("Reload");
if(currentGun.currentBulletCount >= currentGun.reloadBulletCoumt)
{
currentGun.currentBulletCount = currentGun.reloadBulletCoumt;
currentGun.carryBulletCount -= currentGun.reloadBulletCoumt;
}
else
{
currentGun.currentBulletCount = currentGun.carryBulletCount;
currentGun.carryBulletCount = 0;
}
}
In this script, I've fired all 10 shots, and I've got to load 10 rounds from the ammunition 23 left, and it should be 23-10 = 13, but I've got all 23 rounds loaded in the magazine
I can't find anything wrong with that coding. Did I miss anything?
Sorry! Had a class and then study
should this
if(currentGun.currentBulletCount >= currentGun.reloadBulletCoumt)
not be carryBulletCount?
Public intel reload Bullet Coomt; // Number of bullet reloads
public intent current BulletCount;// the number of bullets left in the bullet hole
public int maxBulletCiunt;//maximum number of possession bullets
public int carrybulletCount; // number of bullets currently owned
if(currentGun.carryBulletCount >= currentGun.reloadBulletCoumt)
makes more sense with the rest of your code
can you force the transform of an object to be const (immutable)?
theres some mysterious codes that trying to modify the position.y of a gameobject in scene
and i cant find the code
is that not what happens when you mark a game object as static?
so , if i can force the transform to be a const, i can induce an error which terminals will tell me what is modifying it
ok i gonna try it
not sure it will throw an exception though, probably not
its getting annoying it took 2 hrs already
it turns out that the spawn position is modifying by other scripts
the code are scattered all over the place
sounds like very bad design
lemme give u an example
when handling server errors, you often have certain codes right?
each code is responsible for certain server error and maybe its handling
like http 404 is not found
its more like
case xxx
//do something
.... and keep going
we have these scattered across 10 scripts
ouch
i asked my supervisor, why we scattered them everywhere
- some error code are exclusive to certain scripts, like the handling requires some local variables
- if u stuff all 100 error code into one place it is too long to read
but i found out , only 2-3 handling are exclusive, other 95+ errors can be gathered up
so its more on "stuff all 100 error code into one place it is too long to read"
yep, sounds worse than 'bad design' sounds more like 'no design whatsoever'
theres no design actually, A in charge of this, he wrote there, then B take over and write more code there
Excuse me.
How to get a component from a different game object without doing public GameObject object;
and object.GetComponent<Class>(); ?
And drag the game object in the Inspector ?
C and D and E keep going
there are several options, all of them bad
You can directly do public Class mycomponent; and drag the object with the component in the inspector
if he doesn't want to drag the game object I would presume he doesn't want to drag the component either
I just wanna access a variable through a get set property to do some stuff ._.
But since these scripts don't be in a same game object so ...
let me give you 2 choices.
- Find the game object then getcomponent on that object
- Find the Component directly.
As I said both of these options are bad
f.y.i, using the word 'just' should be banned when talking about programming
also why are you pinging me into a conversation, you should know by now that that is against server rules
I'm so sorry, I "only" want you know what message I'm replying to
Why using the word "just" is illegal ?
I did not say it is illegal, I said it should be banned. Why?
- It shows a complete lack of understanding of the complexities of the question asked
- It shows the user is expecting the solution to be 'easy'
damn i found it
spent 2.5 hrs, found a breakpoint to add my bandaid code
problem solved
Still got a lot of refactoring to do though imo
so whats the bandaid :
lets say because of some faulty code, objA stopped at 0,10,0 , but you want it to stop at 0, 9 ,0
Ok I understood
so i just gonna find a breakpoint, and do
transform.position = new Vector3 (x,y-1,z);
i did similar things there
why does your project have 5 people coding the same module and no thorough planning
the project im working on is from cocos2d
6yrs ago, the team decided to migrate it to unity
(0,-1,0)
at that time, no experience unity devs in the team, so all codes are messy
and faulty
6 years abandoned?
nope
so basically, the first dude came in, write the code down, when he left, second guys came in, top it with more code on the original place
3rd guy, do the same thing, and keeps on and on
recipe for disaster, good luck with that
there are no standards for what code, what strucutre
basically u see what did ur ancestor do, and you do the same
its called tradition lmao
I think standards of a team should have functions with comments of what the function does, params, expected output
I'd say that's overrated for small teams working on an internal project 😅
we only have documents to tell what code and what system do xxxxxx
but we dont have a standard like , where the code should belong
well Im a solo dev so I cant really understand why projects hires so many different people
so if you have 20ppl worked on the code, you have 20 kinds of codestyle
So how do I access a variable that's in another class and in different Game Object ? :(((
like var A , some ppl tend to put it on manager, some ppl tend to put it in other gameobject
Getcomponent
just do a data manager for any object with big chunk of data
you shouldnt mind too much about premature optimization early on
"inject" the component through editor or code - call its getter for the data that you want 🤷♂️ (or maybe I'm missing some details on why that's not the choice?)
I already told you
or drag and drop
make the variable public
do you guys actually not read the questions?
reading takes time, and we're kinda lazy, but with good hearts! 😅 ❤️
why dont you want to make it public in the first place
you could do find or a GameObject Manager
But you said it was bad
yes, but it is the only solution to the your question as asked. So you need to ask yourself do you want to do it that way or do it the 'normal' way, but that is down to you not us
Im not sure if this question fits in this chanell but i wanted to ask what are actually headers, I dont quite understand the concept.
like [Header("")]? its for seperating sections of code by naming them
yea,like that, thank you
in editor specifically
prettify the inspector. other than that they have no purpose
I didnt notice it in the insepctor until now
why is main camera in the vr project setup not showing
it just shows under everything and not where i put main camera
Wdym by "under everything"? Show screenshots?
is there a way to get specific animation of an animator using name (string) without having to loop over all animations in animator
Hey so Im a bit baffled over a problem. Essentially, I have a prefab with a script attached to it to allow for shooting, but it only works if I use the prefab from hierarchy which for some odd reason is in red, and nothing happens if I reference it directly from assets
sounds like you are not Instantiating
what is the best way to learn unity and C#
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thajnks
Can someone help me out please?
I have a missile system, which moves an object from starting point to an ending point. I want to have multiple animation curves (X, Y, Z) that changes they way the object flies from A to B. Also, there is a scale. Scaling means how much the curve values (displacement along the up axis) are scaled. However, I can't make the missile to follow the curves for some reason. I tried to change Y Cruve and set scale, but it only changed the height of the total path. MissileManager -> Move has the function for this.
https://gdl.space/evivugirup.cs
https://gdl.space/uwanuzurik.cs
Either put some logs or step with the debugger through the code to figure out what's going on.
I have some kind of a planet that I would like to be covered with these hexagons, I figured I could use "transform.lookat" to get the correct orientation for them, but how would I cover the whole thing automatically?
You won't be able to neatly tile the surface with hexagons, but it'll work if you leave decently sized gaps
There is a way for sure... and it involves having a few pentagons... I'm sure Google knows
Yes something like that in the screenshot where I placed those manually
e.g.
I'm not sure about the math to calculate the points to instance on.
https://stackoverflow.com/questions/9600801/evenly-distributing-n-points-on-a-sphere
This looks promising.
I thought maybe spawning circles of different radiuses and spawn those hexagons along the circles
Idk if that makes any sense
Yea that looks pretty cool
a link from the hex bible: https://www.redblobgames.com/x/1640-hexagon-tiling-of-sphere/
Never heard of the Fibonacci sphere algorithm
I wish I had more time to study math cuz I suck at it
or something from SO which seems to explain the process of getting the thing: https://stackoverflow.com/questions/46777626/mathematically-producing-sphere-shaped-hexagonal-grid
Okay I understand that tiling a sphere with hexagon is impossible but it doesn't need to be math-perfect
my point is - look online, there's plenty of info about it 🙂 I'd help, but I haven't done it myself
aaaand yeah, that would have a few pentagons... but do you care? people sometimes "mask" them in some way
Using an icosphere and spawning a hexagon on each triangle could work too
Since this is supposed to be a planet maybe I could have them as the polar caps or something
Actually shape like this is actually pretty pleasing to look at
Maybe just triangles are enough
that would take me a week to code
the math bro ☠️
Yea ikr
and then the debug part
I could just copy shit but I like to understand the math behind whatever I'm doing
I haven't tried it myself 😅 shouldn't be too bad (plus there should be a lot of info about all the stuff online...), but I can't say
I'll go ask ChatGPT to write it for me, lets see how that goes 😂 (don't do that at home!)
found it
blender tho not unity
but still
math tends to be language agnostic 😛
a week to code a mechanic? thats ez sauce..
well, ChatGPT gave me this awesome alien ship formation
it's not exactly a sphere of hexes, but I appreciate it! 😄
not so easy for mesh generation, especially if you're implementing your own data structures
such sphere, much wow!
hello, im having problem translating this from position to rotation
Vector3 dampingFactor = new Vector3(
Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping * Time.fixedDeltaTime)
);
Vector3 acceleration = (((referenceObject.transform.position - gameObject.transform.position) * Stiffness) - Vector3.Scale(currentVelocity, dampingFactor)) * Time.fixedDeltaTime;
currentVelocity = Vector3.Scale(currentVelocity, dampingFactor) + acceleration;
currentPos += currentVelocity * Time.fixedDeltaTime;
gameObject.transform.position = currentPos;
