#💻┃code-beginner
1 messages · Page 543 of 1
theres 3 that control the sate like for example when it turns into the attack state and theres one that sets the target to attack and then theres one that set the attack output
There should be one source of truth about states. Other scripts just react to it. is that what you mean?
Have you debugged these three with the log messaging or debugging I specified, and are you 100% sure that it definitely sets these animation states?
you mean transitions?
yes
Hi. quick question. I need a line of code, what add to this script for keep moving a player yValue position after click
using UnityEngine;
public class aabbaa1 : MonoBehaviour
{
float xValue = 0f;
float yValue = 0.1f;
float zValue = 0f;
[SerializeField] bool moveup;
void Start()
{
moveup = false;
}
void Update()
{
if (Input.GetKey(KeyCode.E))
{
transform.Translate(xValue, yValue = 0.1f, zValue);
moveup = true;
}
}
}
just use Vector3.up
thanks i will try this
hi i got a question
public class TowerProjectiles : MonoBehaviour
{
public GameObject projectilePrefab;
public Transform firePoint;
public float range = 5f;
public float fireRate = 1f;
private float fireCooldown = 0f;
private Transform target;
private LineRenderer lineRenderer;
public bool showRangeInGame = true;
```
here i set the projectileprefab for the defense tower
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float speed = 10f;
public int damage = 10;
private Transform target;
public void SetTarget(Transform newTarget)
{
target = newTarget;
}
void Update()
{
if (target == null)
{
Destroy(gameObject);
return;
}
Vector3 direction = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
if (direction.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
transform.Translate(direction.normalized * distanceThisFrame, Space.World);
transform.LookAt(target);
}
private void HitTarget()
{
Enemy enemyManager = Object.FindFirstObjectByType<Enemy>();
if (enemyManager != null)
{
foreach (var tempEnemy in enemyManager.GetTemporaryEnemies())
{
if (tempEnemy.spriteRenderer != null &&
Vector3.Distance(tempEnemy.spriteRenderer.transform.position, transform.position) < 0.5f)
{
enemyManager.ApplyDamage(tempEnemy, damage);
}
}
}
Destroy(gameObject);
}
}
the code works but want the prefab to be visible
Hey. i need help in something
how can i make a players material change with a button?
what script should i add? i have no idea what lines to use.
Did you do a Google search before asking here?
That first link is pretty interesting
Somebody with the same question. They just didn't know how to iterate between them
Want to know how to easily do that?
Hello! When I try to change the current scene from my game I have the error message:
"Scene 'MainMenu' couldn't be loaded because it has not been added to the active build profile or shared scene list or the AssetBundle has not been loaded.
To add a scene to the active build profile or shared scene list use the menu File->Build Profiles"
I'm using this method: "SceneManager.LoadScene("MainMenu");"
My projet look like this
I tried to add the MainMenu scene here but I don't see the MainMenu scene anywhere
Someone can help me please ^^ ?
open the MainMenu scene and click the "Add Open Scenes" button
Oh god thx! So easy I was 1hour on this thing xD Sometimes unity UI is a bit hard to understand ^^
yeah, this thing is specially strange to use, no idea why you can't simply select scenes there
You can drag drop scenes there tho
Uhh I got a map from the asset store and I don't know how to add the whole map to the game, it's now in my project thing
Why are the trees pink now 😭
whats the syntax for
foreach(var thing in [x, y])
The map wasnt made for your rendering pipeline, you need to convert the materials
cuz that one doesnt work
For x in y
Foreach is different
Idk what rendering pipeline means and idk how to convert the materials
not what i need
foreach(var thing in new { x, y }[])
?
It's unclear what you want here, please be more specific
perhaps you should explain yourself because [x, y] is pretty meaningless
and some C# basics lessons would seem to be in order
If the point is iterating a joined collection, then you probably need
foreach(var thing in x.Concat(y))
for (int i = 0; i < 2; i++)
{
GameObject? thing;
if(i == 0) thing = x;
else thing = y;
//stuff
}
It would help if you explained the actual issue you're trying to solve instead of explaining through cryptic garbled code
Don't ask how to do the solution, ask about the actual issue
From this it seems like you might want to invoke behaviour based on if you work with an even or odd number, but I doubt it
do you mean
GameObject[] gos = new GameObject[2];
...
foreach (GameObject thing in gos) {
// Do Stuff
}
why do i bother
Don't know what you want us to say
Explain the issue instead of relying on AI
What are you trying to do that requires this?
ok, and how are you gonna get data into your new array?
foreach(var thing in new[]{current_board.base_board, ball})
yeet_up(thing)
is what i needed
Are you actually using it for just 2 elements or are there more?
and now i have it
and here
GameObject[] gos = new GameObject[2];
it's already there which if you are iterating over it is where it should be in the first place instead of creating an array on the fly
im just using it for two elements yes
more or a "learn how to for future me" tjan anything else
I don't see why you would iterate two hardcoded elements instead of just calling yeet_up twice
Alright. Tbh I never thought of constructing an array in the foreach loop's header
But as long as you send tiny snippets of code and AI I don't think it really matters anyway
is a common pattern where im coming from
tho thats more cuz its inbuilt syntax
for(var/thing in (x, y))
That's a tuple, though
its a list
() makes a tuple, [] makes a list
Regardless () would make a tuple
even assocs are lists
Even in C# it would
Just fyi, because even your code doesn't do that
Modern .NET does allow [] to define collections
But I still don't see why you bother allocating an array for two known elements when you can just call a method on them directly
I'd love to help if you actually shared code
internet on laptop is kill
somehow
Well, explain the issue
Why do you need this?
The current code looks like overcomplication but I assume the point is for something bigger
I added a pipeline and converted but some parts are still not rendered while some are, idk how to do it welp
They probably use custom shaders/materials that the converter couldn't handle
Show the material of one of the pink objects
This does not show the material.
You need to select one of the objects with a renderer on it
They should all be children of this BLD_Bridge_A object
Then open its "Materials" list and double click on a material
Ohh that's what you mean
Well this is one
Wrong one
Done
whats the non-blocking version of thread.sleep()
there isn't one; putting a thread to sleep stops it
what are you trying to actually do?
need to wait some seconds for particles to finish and sleeping pauses the particles too
you can use a coroutine to perform an action after a delay
no they dont return a promise
oh yeha that should do it
thanks
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float speed = 10f;
public int damage = 10;
private Transform target;
public void SetTarget(Transform newTarget)
{
target = newTarget;
}
void Update()
{
if (target == null)
{
Destroy(gameObject);
return;
}
Vector3 direction = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
if (direction.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
transform.Translate(direction.normalized * distanceThisFrame, Space.World);
transform.LookAt(target);
}
private void HitTarget()
{
Enemy enemyManager = Object.FindFirstObjectByType<Enemy>();
if (enemyManager != null)
{
foreach (var tempEnemy in enemyManager.GetTemporaryEnemies())
{
if (tempEnemy.spriteRenderer != null &&
Vector3.Distance(tempEnemy.spriteRenderer.transform.position, transform.position) < 0.5f)
{
enemyManager.ApplyDamage(tempEnemy, damage);
}
}
}
Destroy(gameObject);
}
}
public class TowerProjectiles : MonoBehaviour
{
public GameObject projectilePrefab;
public Transform firePoint;
public float range = 5f;
public float fireRate = 1f;
private float fireCooldown = 0f;
private Transform target;
private LineRenderer lineRenderer;
public bool showRangeInGame = true;
```
the tower handles the spawnpoint and should handle the prefab where the projectile script is bind too but can t get it working to see the projectile in the game itself😅
like the connection between those 2 files isn t great but dunno how to fix it
Using Enemy enemyManager = Object.FindFirstObjectByType<Enemy>(); doesn't make a lot of sense
what if there is more than one enemy?
Also why would something with an Enemy script on it be an "Enemy manager"?
Wouldn't that be a completely different script?
it focuses on 1 at a time
I would expect Enemy to be a single individual enemy
But there's no guarantee that the Enemy it picks with that call is the same thing that its Target is
Why don't you just use the Target?
dunno tought this could work too and it works with the ui and damage just don see the prefab towards the enemy
red lines are just debug lines for the range of the towers 🙂
biggest bug for me right now is making the prefab appear i assigned
it doesn't make any sense, and it is not going to work once you have more than one enemy at a time
unless you've named your scripts very poorly
which it seems like you might have
which script(s) are on the enemies?
What does the Enemy script actually do?
in which case you desperately need to fix the names of these classes
It seems more like something that manages enemies
it focusses on 1 enemy at a time and the switches on when it is out of range
but that's not what the code will do, unless Enemy does not actually represent an enemy
i got an enemyspanwer and (wich controls spawnsettings)
And that object has... which scripts on it
Enemy is definitely not an enemy, yeah
and enemy wich does the rest with the enemy
it has a list of "temporary enemies"
This thing needs to be renamed to EnemyManager or something similar
yeah correct got both in 1 🙂
"both"?
temporary and then normal enemy in that script
but what has that to do with the fireball projectile? cuz my naming convention might be cursed but the rest works?
The reason you can't see the projectile is because you did this:
transform.LookAt(target);```
this is not correct in a 2D game
in a 2D game this is going to make the sprite rotate like in Paper Mario
and be invisible because you're looking at it on the impossibly thin paper side
to rotate it towards the target you would just do this:
transform.right = direction;
LookAt is similar to transform.forward = target
but the "forward" direction in 2D points into the screen
hi can someone help me? i've made this full body fps by using fps controller by unity, changing the capsule with a 3d model from mixamo and adding triggers to the code for animation. i've attached the main camera to the head of the 3d model, apart from the eccesive head bobbing, my character always go towards right, (probably because of the animation), even if im just pressing w (like in this footage) can someone help me please? thanks
ah, target is another Transform
you need a direction to the target transform
such as...
target.position - transform.position;
and then you need to set transform.right, not transform.forward
Did you not read what I said
transform.right = direction;
you already HAVE the direction variable
There's a reason I wrote direction and not target
I made an error here
but needs to be 2d right?
it was 3d made it 2d
you still call LookAt
transform right handles that now?
Like this
huh but i have that
it was the root motion option
you could have left it where it was
LookAt was literally overwritting anything you wrote above with that. transform.right = becomes useless
No it actually needs to go underneath that if statement
because if it's above, you will get an error when it's too close
the position in the code of where LookAt was is fine, but LookAt was wrong
done
so what could be wrong no with the prefab not visible in the game?
That was what the whole conversation about LookAt was about. It should be fixed now
If it's still not visible you need to investigate further. Run the game and pause it and look at the inspectors of the objects and see what's wrong.
The projectile could be behind another sprite for example
But without seeing your project it's hard for us to say based on code alone. We need to see the scene setup.
like where's the actual sprite renderer for the fireball?
i don t have that one then?
I'm making a 2d endless runner game (totally not a google dino clone) and I have the script set the high score to the current score if the current score > the previous high score. The only problem with this is that I use ```cs
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
to restart the game after I die and this resets my high score to 0. Is there any way to preserve this integer even when resetting the scene or am I gonna have to figure out a new way to restart the game?
Here is the relevant piece of code in case it's needed:
```cs
if (collision2D.gameObject.CompareTag("Obstacle"))
{
Time.timeScale = 0;
deathScreen.SetActive(true);
finalScore.text = "Score: " + currentScore;
if (currentScore > currentHighScore)
{
currentHighScore = currentScore;
highScore.text = "High Score: " + currentHighScore;
}
If you don't have a SpriteRenderer then the object will obviously not be rendered
But I suspect you do have one
it's probably just on a child object inside the prefab
You would need to store your score in a DDOL object
k thanks I'll look into it
You need to pay attention to the sorting layers and order in layers of all your 2D sprites. That is how the drawing order is determined
how do i yeet an obj
if they're all on Default and 0 then it is just random which will draw on top
i wanna animate some objects accelerating along an axis
but it on 5 didn t see it tho have used it before for the small stones on the tilemap
Hardcoded animation or do you want to use physics?
hardcoded animation
You could use an actual animation or just modify the object's transform.position
center to pivot and changing order layer to 5 didn t seem to matter tested both aside from eachother
you also can do some Tweening @flat sphinx
(just interpolating position)
was my first thought (the latter) but i dont know how to lerp
as for animatinos idk how they work
You could simply have a float speed, every frame use speed = Mathf.MoveTowards(speed, targetSpeed, delta) to change the speed (accelerate), and move the transform to some direction multiplied by speed
Mathf.SmoothDamp is also a decent option depending on what you need
(Or Vector3.SmoothDamp)
Hello guys, first time here! Just made a 2D movement system based on the player following a circle, but I am trying do find a way for the player to "dash" towards the circle 🤔. I have a tiny video of the game for anyone willing to help 😄
show setup and !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.
also dash can either be based on distance, time or both..
navarone do you know why the fireball pixels don t spaen on my screen? 
spawn the fireball, pause the game, select the spawned instance in hierarchy view and press F to focus on it in scene view, see where it is
Look at its position in the inspector
so yeah freaking me out
probably an order in layer issue like Praetor pointed out
is it being rendered under other stuff? Change the sorting layer
but it put it on 5
make sure the order in layer is high enough
show me the gizmos for the move tool
looks like the child fireball is very far from the parent
aka the visuals are wayyy further than parent moving
where can i find that?
the move Tool in unity (W key ). when you show gameobjects so we can see the pivots but looks like child is way far, look at the position, it should be 0,0,0 from parent
I read the doc and tried DontDestroyOnLoad(gameObject) on the player's script (this is where the score is currently stored) but the high score is still being set to 0. Should I be storing my score on a different object?
should i put it to 0 0 0 then?
first pic was the child
yes child should be 0,0,0 from the parent as i said
but the parent should also be 0 0 0 or only the child?
the parent can also be 0,0,0 doesn't matter, that gets assigned when you do Instantiate anyway
the child is the main importance, it should not be that far away from parent, especially if its the visuals
well so resize the child visuals?
is scaling ok or is that bad?
you should probably turn off compression/filtering on sprite
looks bad on pixel art
looks blury
where can i find that?
click the sprite asset in the project view, in the inspector you should see it somewhere at the bottom
IMO the scale is also way too big, the pixels are like more than 10x larger than in the other sprites
Inconsistent pixel size gives a really unprofessional look
im not a proffesional you can tell and don t make my own assets jost a hobby project
Yeah, well, you asked if it's ok or bad.
you could potentially scale down and make it look nicer by "zooming" back in with the Pixel Perfect component
im blind lol give me 10 min
doesn t seem to be a sprite?
Hey, I created json config for the unity gradient.
It works fine for the most part, but there is 1 small issue.
When I assign it to the vfx graph's gradient, it looks odd.
The issue is with the gradient mode.
As can be seen in the first picture, it's correctly loading the mode from config, here's the conversion code too:
/// Implicit conversion to <see cref="Gradient"/>
public static implicit operator Gradient(ConfigGradient g) => new()
{
alphaKeys = g.AlphaKeys.Select(key => (GradientAlphaKey)key).ToArray(),
colorKeys = g.ColorKeys.Select(key => (GradientColorKey)key).ToArray(),
mode = g.Mode
};
But when I assign it to the vfx gradient, even tho it shows Blend (Perceptual), it looks wrong.
Picture 2 is what it looks like when assigned, picture 3 is what it looks like when switched to something else and back to perceptual, basically how it should look like.
It's also not just a visual thing as it's applied to the vfx graph in the wrong way too.
Thanks in advance!
It's hard to say. There's more to it than just making something DDOL. The player object should probably not be the thing, no. You also need to make sure if you're using DDOl that you don't end up with two of the objects in the scene after reload. Having a centralized score manager or game manager might be a good idea.
Look into DDOL singletons
in the project view?
where is that then?
Timo im sure you can find the project view if you put some effort in
but this is the project view right?
Just used the same script for rotating the triangle for rotating an empty GameObject towards the red ball, using the green ball as a target for the "Dash"
{
Hovering = false;
}
public void HoverOn()
{
Debug.Log("1");
Hovering = true;
}
so i have this script where when a mouse hovers over a button it should make a bool true or false but well it isnt working for the bool but it is for the debug
so you have the position/dir you want to dash towards already?
show how you call HoverOn and HoverOff, and how did you test the bool
using the event trigger and i know that the bool is not on or off because in the inspector it isnt switching
instead of debugging something kind useless like "1"
Put Debug.Log(Hovering)
inside each function after the assignment, and see whats registering. It could be switching without you noticing
Yeah, for now im just using tranform.position, wanted something less subtle
Maybe something that could colide with a wall in the way
well if you want to do it towards a specific position use something like MoveTowards maybe ?
If you plan on using collisions you should probably be using velocity/rb.position instead
I am already using MoveTowards to move PlayerTriangle towards the MovementCircle(red), and transform.position to move DashAim(EmptyGameObject with green circle) to move it to PlayerTriangle every frame
So, the position of the triangle is already changed every frame, dont know how to apply a "dash movement" over that without screwing up the PlayerTriangle movement
About MovementCircle, im using it so the player speed doesnt add up while moving in more than one direction
when i hover over the button it gives me two debugs false then true
show the actual code
so the bool is true ? or you looked at wrong order
narrow down now which functions are calling it
turns out i did a mistake
yes 99% usually is a user mistake when something not work as intended lol
i set up the event trigger wrong but know i fixed it
now ima see if its working
its working but now i will see how to make it do what i want it to do
using System.Collections.Generic;
using UnityEngine;
public class FollowScript : MonoBehaviour
{
public GameObject Target;
public GameObject dashTarget;
public Vector2 dashPosition;
float moveSpeed;
public float Dis;
Vector3 mousePosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
RotateTriangle();
MoveTriangle();
}
void RotateTriangle()
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
transform.up = direction;
}
void MoveTriangle()
{
PlayerMovement cs = Target.GetComponent<PlayerMovement>();
moveSpeed = cs.moveSpeed;
transform.position = Vector2.MoveTowards(transform.position,Target.transform.position,(moveSpeed - 1) * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && ((Input.GetKey(KeyCode.W))||(Input.GetKey(KeyCode.A))||(Input.GetKey(KeyCode.S))||(Input.GetKey(KeyCode.D))))
{
dashPosition = dashTarget.transform.position;
transform.position = dashPosition;
}
}
}```
yeah you should not be teleproting it with transform.position =
use a rigidbody and Velocity
you need a bool / switch statement if you plan on taking over the movement to do a precise currentpos to dashPos
or maybe run it in a coroutine too
Anyone know how i can stop the pipe from getting destroyed if my player has collided with something resulting in the game being over?
https://hatebin.com/zkeyyiypvm
you have a timer to automatically destroy the spawned pipe, the player has nothing to do wiht it
Destroy(pipe, 4f);
dont do this
Destroy(pipe, 4f);
use a Coroutine which you can stop instead
or just let the pipe destroy itself if it goes out of screen, timer isn't reliable
or wrap a gameover check around the Destroy command
that wont work as it's a delayed invoke
ooh ok, i gotta stop watching bad tutorials to figure stuff out that i dont understand lol
bump
how do i use a coroutine and where do i put it to destroy it once its off screen?
you first go and read the Coroutine documentation
you dont need a coroutine , just check if the pipe is outside the screenview
nah that wont work, he said he want to stop the destroy on game over. it could be that the camera is also stopped
he doesnt need the timer to destroy in the first place
oh yeah than it makes sense!
the pipe only destroying itself outside screen kills 2 problem in 1
Hi,I am using UI ToolKit and would like to ask how to set up Dialog to display at a resolution of 200 * 100 on a 412 * 917 screen? Just like the green area.
which Is why I said Coroutine
yep i would also work with a distance check instead timer. it is just innacurate
currently what im trying to do is just make a flappy bird like clone so its just my player jumping in place and the pipes spawn in on the right, move to the left and get destroyed. And if the player collides with anything it calls my gameover method in my GameManager script
no need to distance check either, eg
Vector3 viewportPosition = Camera.main.WorldToViewportPoint(pipe.position);
if (viewportPosition.x < 0)
{
Debug.Log($"{pipe.gameObject.name} has exited the left side of the view.");
}```
timer is ok what if you decide to have pipes that speed up and slow down? now timer breaks
ooh true
no , did not mean timer i mean distance check or viewport. timer is really inaccurate after a certain amount of time.
i wuold not rely on it.
where would i put that, under the spawn pipe method or update?
Generally asking, is there a significant benefit to using Arrays over Lists?
depends on many factors, size being the most important
do your pipe have a script ? you can put it in the pipe script itself Update
cache the camera probably
Just Tried this
{
if (Input.GetKeyDown(KeyCode.Space) && ((Input.GetKey(KeyCode.W))||(Input.GetKey(KeyCode.A))||(Input.GetKey(KeyCode.S))||(Input.GetKey(KeyCode.D))))
{
//dashPosition = dashTarget.transform.position;
//transform.position = dashPosition;
horizontal = dashTarget.transform.position.x;
vertical = dashTarget.transform.position.y;
myRigidbody2D.velocity = new Vector2(horizontal * moveSpeed, vertical * (moveSpeed + 50));
}
else
{
PlayerMovement cs = Target.GetComponent<PlayerMovement>();
moveSpeed = cs.moveSpeed;
transform.position = Vector2.MoveTowards(transform.position,Target.transform.position,(moveSpeed - 1) * Time.deltaTime);
}
}
i have a prefab with my PipeMover script on it https://hatebin.com/eknvqjnhmc
Just got
NullReferenceException: Object reference not set to an instance of an object
FollowScript.MoveTriangle () (at Assets/Scripts/FollowScript.cs:45)
FollowScript.Update () (at Assets/Scripts/FollowScript.cs:25)
great and we know what line 45 is how?
and the one i sent before was a pipespawner script on an empty game object
myRigidbody2D.velocity = new Vector2(horizontal * moveSpeed, vertical * (moveSpeed + 50));
so myRigidbody2D is null
yeah its fine toss it in update
would probably cache camera in update
private Camera cam;
void Awake() => cam = Camera.main
would i put the destroy in that also under the debug.log line?
and in the if statement do a check to see if the game is over?
if you want its already in that if statement no?
for moving
oh yea, just put the movement and the destroy under the same if?
guys i need serious help...my wheels keep running away and my bike floats away
idk what settings to show so please lmk
im also using wheel colliders
alr i got it working now thanks
This is a #⚛️┃physics question
Ask there and include screenshots of your hierarchy setup, related compoent settings (rigidody, wheel collider) etc.
thank you
And show related code too
I'm trying to call a function from another script in the script that I'm currently coding. I referenced the gameObject that the other script is on, and I used .GetComponent<MyScript>().MyFunction(); to try to get the reference of the function in the other script but I just can't find a way to call that function. How do you do this?
soo u used
theOtherObjectYouSaidYouReferenced.GetComponent<YourScript>().YourFunction();
that should would if the script is indeed on the other object... and has said function
and the OtherObject is indeed referenced
System.Action myAction = theOtherObjectYouSaidYouReferenced.GetComponent<YourScript>().YourFunction;
myAction();
ah ok
ahh like caching just the function for later
but I don't know how to call that function that I referenced
Yeah if you don't put () you will get a reference to the method
With () you will call the method instead
neat..TIL
oh I get it now
as SteveSmith mentioned, you call it just like you would a regular method, or use Invoke . . .
any reason u'd cache individual methods and not the entire class?
seems like more flexibility with the later
i call this () invocation. without it, you're not invoking or calling the method . . .
generally I use this is If want to pass the method as a parameter to another method
ohh makes sense 👍
possibly for callbacks . . .
indeed
if you want its execution in line within code or after code from another method . . .
You also often see it when you subscribe to an event: cs SomeEvent += MethodToCallWhenEventIsRaised;Note how there's no () because you dont want to actually call/invoke it here
it's great in, for example, a Coroutine if you want a callback at the end of the coroutine execution
private void DrawCenteredButton(string buttonName, System.Action onClick, bool enabled)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = enabled;
if (GUILayout.Button(buttonName, buttonStyle))
{
onClick?.Invoke(); // <-- aye, i have done this before.. i just forgotten
}
GUI.enabled = true; // Re-enable GUI
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
#endregion```
What if I just do this
if (collision2D.gameObject.CompareTag("Obstacle"))
{
gameManager.GetComponent<GameManager>().Death();
}
to call the method when I hit an obstacle?
whats gameManager at the beginning?
sure, that works
gameManager is a gameobject that has the GameManager script attached to it
names are a bit confusing ig
oh.. u know u can assign the GameManager script instead right?
GameManager gameManager;
then gameManager.Death();
but thats only if its available to do so with
I tried but it didn't let me drag the script in the inspector
then u can avoid using GetComponent calls
and this way.. u automatically have the gameobject too if u need it..
gameManager.gameObject
it's weird though, my death method works when I collide with an obstacle but the PointScored method doesn't work. 🤔
Script on player that detects if I pass through obstacle trigger:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Obstacle"))
{
gameManager.PointScored();
}
}
script on GameManager object that is supposed to add points to the score:
public void PointScored()
{
currentScore = currentScore + 1;
currentScoreText.text = "Score: " + currentScore;
}
currentScore is a public int that is supposed to be displayed in the score text (all the text objects and stuff are assigned in inspector)
my score counter on screen stays at zero even when clearing an obstacle
Log currentScore after you set it in PointScored
See if it's the value you expect
You might be overwriting the UI text with something else
hmm PointScored method isn't even being called. I'll try debug logging some other stuff and tell you what I find
ok the player isn't detecting the obstacle triggers
all the obstacles have trigger colliders above them
are they all tagged correctly as "Obstacle"
it may help !code use an external paste bin site tho
📃 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's basically just jumping, ground check, obstacle collision check and obstacle trigger check
@rocky canyon
https://paste.ofcode.org/33N6M9eQPYEcWUUimJ6DqpT
DUDE I'M LITERALLY SO STUPID
I used OnTriggerEnter instead of OnTriggerEnter2D 😭
It works 😮💨
now I gotta figure out how to make my high score not reset when the scene is reloaded
how granular would any of you go when creating packages? i have separate packages:
- Utils (extension methods)
- Core (base/boiler-plate framework)
- Timer (timer class for calling events during certain phases of a timer)
I have an ObjectPool (a group of scripts), and was going to create a separate package for it, but i'm curious if i should group it with the core framework and pile most, if not, everything into that package. what say y'all?
im not him.. lmao im awful at organizing and sorting
Is there a library that adds a method to do something when the hierachy changes/ children or parents are added or removed?
EditorApplication.hierarchyChanged i believe
tyyyyyyyyyyy <3
tysm
I just want to resize a ui object when children are added/removed
what would I use for that?
the code that adds or removes from the hiearchy could also trigger that
if ur talkin about just scaling UI when more UI objects are added.. theres stuff like LayoutGroups that u could use to automatically do that
I love when i get 40 errors after a code refactor and then i fix those 40 errors and then 20 more show up 😄
why dont they all just show up together?
b/c some errors stop other errors from being found.
not until u fix some.. does it execute enough code to find the others
i think i'll end up at that point. when i finish my Stat module, that'll be its own package as well. the issue is dealing with dependencies . . .
im awful at it.. soo if u do figure out the "optimal" way to sort this stuff let me know 😅
even errors have their own hierarchy . . .
I just want the height of this parent object to be childrenCount x childrenHeight + uiSpacing x childrencount-1
ya, id use a vertical layout group for that
it'll automatically resize it however u need
ok and it doesnt inerfere with scrollrect?
ohh.. that i dont know.. i think they can work in tandem. but not sure what all that involvs
haha. this is my default channel. typically, i don't ask anything myself, but look to help others. every once in a while, i'll check general . . .
alright imma try it and if it doesnt work ill come back :) thx again @rocky canyon
you can use content size fitter. i'll expand for you . . .
AAAAAAAAAAA
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-VerticalLayoutGroup.html
https://www.youtube.com/watch?v=L-pOShqMydg
https://www.reddit.com/r/Unity3D/comments/13baq2u/how_to_combine_vertical_layout_scroll_rect_and/
https://discussions.unity.com/t/scroll-view-with-vertical-layout-group-and-buttons-height-not-set-properly-when-playing-in-unity/656092
some stuff to browse thru
well then 😄
ya, bet u got to do some nesting magic
cant have two types of scalars on the same object
or heed random's advice ^
im bad at dynamic UI.. me and CSS fight daily
how does csf work excactly?
no clue.. @cosmic dagger any thoughts?
What library do I have to import? cause I couldnt find that one :x
using UnityEditor; i believe
I'm gonna be honest I just kind of randomly change these and the checkboxes in the layout until it works then I try not to touch it
I've never actually fully understood how those interact
LMAO! me too!!
lmao
this doesnt work in c#? :<
whats up with the asterisks?
in java it auto imports every sub library if you do
import Library.*;
oh nvm i think it must inherit from : EditorWindow for that to work
soo its probably use a utility type thing
this worked
ya, thats another one to i forgot to mention ^
In C# when you use a namespace, all the types in it are available to you, so it's equivalent to Java's *
Yall why is the .point of my RaycastHit2D always slightly off? Like, when I BoxCast onto a collider, for some reason, the collision point is never the position of the collider combined with it's extents?
ah ok ty
Because of floating point inaccuracies. They're small enough to not be noticeable at all, 6 micrometers here
thats negliable
if u want u can clamp it to the nearest int
or decimal place if u wish
damn
what's the best way to go about this
In a line like this (just in case) RaycastHit2D[] hitObjects = Physics2D.BoxCastAll(startPos, boxCollider.size, 0, direction, distance * Time.deltaTime);
That distance * TIme.deltaTime looks incorrect
You only want to cast it a total distance that scales with frame rate?
Low frame rate = cast longer, fast frame rate = cast shorter
Whats an issue with that
even with such tiny inaccuracies, you can get stuck in walls and floors
You tested that hypothesis or you are assuming/ guessing?
float comparisions are usually using epsiolon comparisons so its accounts for that tiny inaccuracy
when changing the size by dragging the lower end of the object in the editor it changes the height automatically. What's the ratio for that?
Or is there a method that adjusts it automatically if the object is resized, that I can use in a script?
You can use Mathf.Approximately
based on the pivot position. You can change the pivot to change the behaviour
tested.
it's very rare
but it occasionally happens
well yes but how can I change it accurately using a script?
Tell me about what your trying to do, and how you are doing it on a high level
I could check if the position is exclusive within the boxcast
height or pivot?
If the thing I said in the message above works, there's no problem
fixing the box cast distance might have helped
I added this line when checking on the x axis (flipped x and y on the y axis): withinBounds = hit.point.y < startPos.y + boxCollider.bounds.extents.y && hit.point.y > startPos.y - boxCollider.bounds.extents.y;
nvmd got it to work, just had to change the pivot to bottom then change y position to 0 now it works as intended
ty for the tip
The inaccuracy is still there to poke at my eyes during development, but you no longer get stuck inside walls
@supple sand thanks a lot for the help :)
whats the output for 0%2? is it also 0?
hi is it possible to assign color to a raycast?
do you mean for testing, if so yes you can use Debug
you can use debug methods . . .
I have this freeze frame mechanic, but it's just awful all around. How do I make a proper one?
public void TriggerFreeze(float duration) {
StartCoroutine(Freeze(duration));
}
private IEnumerator Freeze(float duration) {
Time.timeScale = 0f;
yield return new WaitForSecondsRealtime(duration);
Time.timeScale = 1f;
}
what makes it awful?
i mean like if im using a raycast to detect if theres an enemy(shooting)is it possible to make the raycast have a certain color
Sometimes it's for how long you need it for, sometimes it feels like a lag, being double, triple or more the time you need it to freeze for
thanks:)
what are you trying to achieve?
maybe you're calling the TriggerFreeze method multiple times or with the wrong duration?
cause I can't see any problems in this script
so I got the resizing to work but the y position is set to -290 because of the scroll rect and it doesn't let me change ithttps://streamable.com/wdno67
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SizeAdapter : MonoBehaviour
{
private void OnTransformChildrenChanged()
{
RectTransform rectTransform = GetComponent<RectTransform>();
if (rectTransform.childCount % 2 == 0) rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, rectTransform.childCount / 2 * this.GetComponent<GridLayoutGroup>().cellSize.y + this.GetComponent<GridLayoutGroup>().spacing.y * (rectTransform.childCount / 2 - 1));
else rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, (rectTransform.childCount + 1) / 2 * this.GetComponent<GridLayoutGroup>().cellSize.y + this.GetComponent<GridLayoutGroup>().spacing.y * ((rectTransform.childCount+1) / 2 - 1));
rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, 0f);
}
}```
this is the script right now and and the last line gets overwritten by the rect too
Watch "Project T - Deck Builder - Windows, Mac, Linux - Unity 2022.3.21f1 DX11 2024-12-13 20-46-24" on Streamable.
any idea on what to change so it alligns the to the top left and doesnt move the first ones off screen?
Freeze (or slow down to 1/20) the game for a given amount of time/frames
what you have will effectively pause the game for 'duration' seconds
if you want to slow down time then you'll need to change Time.timeScale to a value above 0
Not sure this repo is still around: https://bitbucket.org/ddreaper/unity-ui-extensions
super usefull for UGUI
its not :(
Has a new github link i guess
Hi ! Sorry to disturb, but I'm trying to make my enemy spawner spawn enemies faster and faster, so I wrote something then wanted to test, but it didn't go as expected... (see the last picture)
I would like to make enemies appear faster and faster over time. But to prevent it from becoming exponential, I wanted to do it by making it stagnate at a certain speed stage, but it seems it didn't work ? The seconds I make the game play, there's just an infinite amount of enemy going down 😭
Update runs every frame, and you have Instantiate in both the speedSpawn == 2 condition and its else, meaning every frame it will spawn at least one thing.
you're instantiating multiple times in your code . . .
more than one of your if statements can be true, resulting in multiple instantiated objects . . .
also, its easier to read if you post all of your !code in a single file . . .
📃 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.
Aaaah I see... sorry I'm really new to coding and Unity in general, so I don't understand everything yet...
And I'll keep that in mind for next time, sorry again !
I know that its almost not readable and im really sorry for that but i was just testing something and i was wondering why doesnt it work, the script should change the color of the capsule to 1.0f and then when it hits 1.0f it changes slowly to 0.0f and again to 1.0f, but all it does is chaning the color to 1.0f and leaving it like that
https://hastebin.com/share/aconetonap.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
any advices would be usefull
first thing first, never check a float for equality
what do you mean?
dont you know what equality means?
It's literally the first item under "Don't" in the pins
oh
why is that?
and how to compare using matf.approximately
in your case >= 1.0f rather than == 1.0f
because floats are almost never exactly equal the value you think they are
Because floats are not precise. Exact numbers can't always be counted on
You might end up with 0.99999999997 instead of 1
But also in your case, you should be checking for greater than 1, since you have no control over the increments and it's unlikely to even approximately hit 1 depending on framerate
i didnt know about that
but now i know
It's called floating point precision fwiw
Or lack thereof. Floating point in computers is a hornet's nets.
I wrote an implementation of fractions for Java to avoid this stuff. I might have to port it over to CSharp
Goodbye int, say hello to outt
There's a reason they use floats for everything in Unity
if you need more precision for pure mathematics, use doubles or decimal
For sure. It's a tool for a job. You gotta use the right tool for the job.
I'm not saying floating point numbers are useless.
Just maddeningly imprecise in certain cases.
Hi! how do i make this image clickable in unity?
Seperate the clickable elements or use invisible buttons.
alright but do i need to implemt it as a tile map or image?
Splines
I assume have some polygon game objects on each item you want clickable, and use that as triggers etc
do i need polygon (just new in unity for 2 weeks)
well it'd be hard to make certain areas of it clickable using squares or circles
alright
why does line 17 have an error
using UnityEngine;
public class oppSpawner : MonoBehaviour
{
private int numOfOps = 5;
private int[] ops = new int[5];
private float[] opPositions = new float[5];
public float startingPos = -4.43f;
public GameObject spawnable;
private Vector3 spawnPos = new Vector3();
private Vector3 spawnRotation = new Vector3(180, 0, 0);
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for (int i = 0; i <= numOfOps; i++)
{
spawnPos = (startingPos, 4, 3);
opPositions[i] = startingPos + i;
ops[i] = i;
GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
}
}
// Update is called once per frame
void Update()
{
}
}
it's meant to spawn enemy spaceships in my 2d game (ignore how much I used the word op)
new Vector3(startingPos, 4, 3)
you should always start by reading the error message..
What does the error say
oh this works thx
Because spawnPos is a Vector 3, and (startingPos, 4, 3) is not
I see now
try new(x, y, z) or new Vector3(x, y, z) depending on context. :)
but I used the Vector3 keyword (I made it this now)
spawnPos = new Vector3 (startingPos, 4, 3);
oh, I misread
yes, spawnPos is a Vector3; you're just trying to assign a tuple into it
That's correct now, yes
alr ty
Err, why are fields not serialised when I extend Unity's UI Button
Did you get UI.Button or UIElements.Button
and what fields are you trying to serialize
Just the normal UI buttons
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace DefaultNamespace
{
public class HoldButton : Button
{
[SerializeField] private Image fillImage;
[SerializeField] private float holdTime = 1.0f;
Ah, that's what you mean. Button has a custom inspector. You'll need to make your own custom inspector as well to add your fields to it
Or just make it a separate script that references a button and use the normal button component
Why would Unity do my dirty like that. thanks tho
i'm honestly surprised button isn't sealed. so many other unity components are
is there a way of refrencing a project's assets via code?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class CardLoaderScript : MonoBehaviour
{
[HideInInspector] public string CardName;
[HideInInspector] public Image CardImage;
public void loadCardFromDatabase(int id)
{ //CardImage = cardImageFromAssets named id
//CardName = query cardname from database using id;
}
}```
just FYI, that's the UIElements.Image object which is not the Image component you can use on a canvas.
but otherwise, there's addressables or you could create a scriptable object that stores that data
there's also technically Resources.Load but the other two options are typically better
Im trying to get my player to rotate and walk torwards the direction there facing, im able to walk but not change the directions im facing https://hastebin.com/share/uzajaxamax.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is there no way of just telling it to "find" a sprite that's named something?
the Assets folder does not exist in the form you see in your project window inside of a build, so no. the options I listed are how you can reference an asset via code at runtime
ah I see
where do you actually do anything to rotate any of this?
currentRotation.y += horizontalMouse;
that's not rotating any object. that's just changing the value stored in your value type variable
could I save the card images in a Folder or something?
You could use the resource folder
the resources folder is generally not advisable but i did already list that as a suggestion
but shouldnt currentRotation = gameObject.transform.rotation; change it
it's a value type
so I can store images and things in the resource folder when building?
that is seriously not recommended.
why not?
That will store the object's rotation in a variable named currentRotation. Where do you change the object's rotation?
ah I see
so do i use transform.rotate instead
If you want to change the object's rotation, you're going to need to actually change the object's rotation.
You copy the value to a variable and modify the variable but you never put it back
At some point, gameObject.transform.rotation is gonna need to be on the left side of an =
Why do I not see the window option they say should exist?
do you have the package downloaded?
go to package manager in that same window
oki thx
where can I find the package, do you know by chance?
is there a way that i could get my players rotation to just be the same as my cinemachine camera?
i think you need to add it
so when you have the package manager open, there's a little plus sign at the top left
add package by name
then try this red text
👌
addressables is a built in package - you don't need to download it
it depends on the pipeline used
i myself didnt have it for example
how can i get the bounding box of a collider when its not axis aligned?
does anyone here have experience with addressables?
how so? the documentation doesn't mention anything about pipelines
Alright my bad
didnt see, thanks
foreach (var houseObject in houses)
{
var collider = houseObject.transform.gameObject.GetComponentsInChildren<Collider>().FirstOrDefault();
TriggerEffectParameters param = new TriggerEffectParameters(id: (ushort)effectIds[UnityEngine.Random.Range(0, effectIds.Length)])
{
position = collider.bounds.center,
scale = collider.bounds.size,
relevantDistance = 500f
};
param.SetRotation(houseObject.transform.rotation * Quaternion.Euler(-90, 0, 0));
EffectManager.triggerEffect(param);
}```
only axis aligned gameobjects are returning the correct bounding box
but what am i supposed to do? calculate the bounding box in local space and rotate it after?
(the top house has the interior perfectly as the bounding box, its just not seen)
i finnaly got my player to rotate with the camera but the only problem is how can i get its movements to rotate with it? the player is visually rotating but the movements are still locked https://hastebin.com/share/waxoweciqu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you probably want collider.size rather than collider.bounds.size
collider doesnt have a size
The colliders that the houses have are mesh colliders, not box colliders
and i can't really use box colliders
why are the shapes not simplified primitives?
is it possible to assign a sprite from my assets to a sprite renderer via code. Without assigning it manually in the editor beforehand?
you have to use mesh colliders?
i'm able to get perfectly the bounding box for axis aligned
yes
wdym
if this is for placement of building?
No, the buildings are already placed on the map, I need to get the area that the house covers
so i just thought of getting the bounding box, which works as shown above, for axis aligned only
and since i cant use the Renderer i cant use localBounds and rotate them later
ohh. maybe just do a transformpoint ?
I still think would be so much easier to simplify to use boxes just for measurement
inversetransformpoint you mean?
im not going from localspace to world space
the bounding box is already being measured from world space
right one of those
foreach (var houseObject in houses)
{
var collider = houseObject.transform.gameObject.GetComponentsInChildren<Collider>().FirstOrDefault();
var localCenter = houseObject.transform.InverseTransformPoint(collider.bounds.center);
TriggerEffectParameters param = new TriggerEffectParameters(id: (ushort)effectIds[UnityEngine.Random.Range(0, effectIds.Length)])
{
position = houseObject.transform.TransformPoint(localCenter),
scale = collider.bounds.size,
relevantDistance = 500f
};
param.SetRotation(houseObject.transform.rotation * Quaternion.Euler(-90, 0, 0));
EffectManager.triggerEffect(param);
}```
the center aint the issue
its the scale
yea but how exactly?
using UnityEngine;
public class oppSpawner : MonoBehaviour
{
private int numOfOps = 5;
private int[] ops = new int[5];
public float startingPos = -10.43f;
public GameObject spawnable;
private Vector3 spawnPos = new Vector3();
private Vector3 spawnRotation = new Vector3(180, 0, 0);
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for (int i = 0; i <= numOfOps; i++)
{
spawnPos = new Vector3(startingPos, 4, 3);
ops[i] = i;
GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
}
}
// Update is called once per frame
void Update()
{
}
}
why is my stuff spawning in the wrong spot
wel when I do usually BoxCollider.size usually it gives me local/transformed so maybe try throwing the TransformPoint on the size, keep the position center as the bounds.center
transformpoint transforms it from localspace to world space
my scale is already in world space
if i do this
this happens
I mean Inverse
oh shit.. well thats not right
wonky
nvm
rotation is good but size is whacked?
for the box of other buildings its just fucked
ah yeah that wont do..simplify the outline of the buildings with a box collider? 🤷♂️
i cant really change the mesh renderer from the buildings
the issue isnt even finding the center
its just that when the collider isnt axis aligned the bounding box will try to be axis aligned(?)
and will just eb the correct size but 90 d or plainly twice the size it should be
and i cannot calculate it using localbounds since i cant access the renderer component of the building
you might have to remap it yourself..
is it still same with meshcollider.sharedMesh.bounds.size ?
Should I use html for my websites and unity for my games respectively?
website for what?
It's going to be art software for the website.
Forgot to reply.
art software? you mean you're making an art program using unity?
For html it's going to be the art program.
i don't understand what you're doing? where does unity come into play (how does it relate to unity)?
...what?
I've been trying to fix the main menu for the past hour. Quite literally, the slots should be saved as slot1.json or slot2.json, or slot3.json, but no matter what i do it saves as slot4, and then it doesnt show up in the main menu (but it should). There is 100% a bug in the code, but i cant find it.
SaveManagerCode: https://pastebin.com/Z66L6U9c
give this a read: https://unity.huh.how/anonymous-methods-and-closures
Im looking for something very specific and cant find any tutorials on it, does anyone know anywhere I could check to find a tutorial on how to make a flying bird controller as my player in 3D? As in you play as a bird and you fly up by flapping your wings and control direction by where youre looking etc
I hope that makes sense!!
right on the money . . .
planning on making a game where you play as a dove for my gf since she loves birds but I think i might be in over my head 😭
when you flap your wings, increase the vertical velocity of the bird . . .
oh yeah that makes a lot of sense!!!
I didnt even think about it just being a normal player controller wiht just, flapping enabled
lol
sounds great!!
I will prpbably be coming by here a lot tomorrow and stuff when I actually start real work on the project, its currentyly 1:25 AM and I wannma go to sleep in like 30 min or so, so I'll start the coding tomorrow
wont get much done in 30 min haha
I'll do that :)
Took me a while to understand, but i got it working ty
oh my god now the confirmation dialog doesnt show up i gonna jump into a volcano
how would i go about getting the data of the point that im collecting, and deleting it for a point system?
i see
does othergameobject refer to the object that is being collided with
The basic premace is finding the object you are currently colliding with then adding a score to some global manager and deleting the object you just collided with if the object is a collectable
you could use oncollisionenter for simplicity (if using a rigidbody)
is it just me or there's not alot of 2,5D games tutorials in unity
does this mean that the script is inside of the point or the player
like you move forward, backward, left, right but you cant jump or go down
ah ok
yeah
something like that
yeah
Well i guess that could help me at some point
Wait, do you think it will look better when i make an animation for each direction of my character (WASD and diagonal directions) or just WASD
Cause that's rather important
The collisions will be rather easy
I think
i'll check it out rq
His character has only 2 movements, left and right, and when he's moving down it remembers the last direction he was walking in
Yeah
Im overthinking some things right now
why does this go off despite not clicking anything?
It's really hard to tell someone how his game would look like better when you don't know what's the game about haha
wait nvm im stupid
i was looking at the debug which always happens when the method is called...
🤠 been wondering why it isnt shooting
i didnt even have to run it
🤦♂️
ngl i dont get that pattern
So like, when game is about slaying enemies on a non moving screen, that is one singular scene for now, the background is literally static, the best would be the 8directional movement i feel like, but then its thinking how to make the hand and the arts and the weapon, you'll have to draw 1 sprite 8 times, and then what about having to draw for example 50 weapons times 8
that just feels like too much
yeah i guess it is segmenting your code but having a random function handle input only relevant to itself feels icky
to be honest me neither, im hoping if i force interfaces in often enough ill figure it out 😭
i think it made sense originally but now ive gotten a bit lost with it
making my first game with such amount of things to do wasn't the greatest choice
well, i'll try my best i guess
i thought it'll be done by 24th december but we'll see
yeah not really haha
now watch 80 tutorials
i kinda realised the time it could take
the game idea is nice, everything is nice but now do it is just harsh
and it aint even for selling like
if i make the game i'll tryhard it myself
but like when you struggle with saving a file using c# and you have to write an entire AI for each type of enemy
aight imma stop complaining and get to work
fine 🖐️
im getting this error between the last 2 lines - any idea what might be happening? I dont have any Destroy() methods in any script yet
tbh it feels like the diagonal sprites aren't really adding much work, but then i look at the animator haha
WAIT
brainstorm
green needle
aight back to depression
does this happen when you exit gameplay?
no just on shot
but i think i messed up some refernece
yup
probably missing a reference assignment then . . .
i was accidentally assigning a prefab in the scene
that i forgot to delete
don't ask me how 😭
@edgy sinew wait one more thing
it seems not right for some reason
Do you feel it or is it just me
cuz
it actually seems quite weird rn
yeah but the overall structure
ah i see it
i've noticed few mistakes rn
like you cant stop dodging
or
cant transition from left to down or up
oh i had a few broken things with the animations earlier
do i need to use the exit block
like when i go from dodge left to idle and transition it
go for the exit block or the idle state back
aight
thanks for the help though
technically its against the rules to ping ppl not actively in ur conversation but I don't mind
i just got home from installing an axel on my car working in the cold.. soo my brain is spaghetti right now
i don't know about this "L-shaped rig," but the camera is just offset from the pivot point (center of rotation/movement) . . .
KIA.. and complex enuff to wear me out.. gimme a second to read ur post and ill see what i cant do
yes, you set where you want the camera to be based on the center (pivot) point. you can move it to either shoulder, up, down, front, back, etc . . .
OTS camera..
- position is offset
- slight or zero rotation (make the players centerline closer or at center
for zooming - usually the cam moves closer to the character and/ or aligns directly behind the weapon/character
- FOV does alot to help.. 30-40 degrees-ish?
the cursor/crosshair will be a big part of it too.. (tightening up the crosshair for example when zooming ADS)
as for rotation i dont ever remember the camera rotating up and down for any TPS games ive played lately
https://www.youtube.com/watch?v=HgsIg_1IvsQ&ab_channel=LugovoisesGames oh i guess it did rotate up and down
this was the last ThirdPerson mode ive played.. ^ not my favorite b/c when u zoom in u just go str8 to first person
this is the only third person ots ive done
soo im probably not the best to ask, heh
so i guess ya, ur centerline is to the right of the player
and then it acts as normal third-person..
the way i did it was a bit magic
the actual raycast came from the center of the camera.. (ignoring the player/gun everything)
soo it would be accurate.. theres edge cases where u have to solve.. like headglitching a corner for example
u wouldnt be able to get a hit.
my projectiles came from the gun.. and would just use LookAt() to fly towards the point my raycast says it was aiming
no, that's not what i meant. i was talking about the original pic you sent. the camera is just at an offset position from the pivot point (the transform or position at where the camera rotates). this can be the center of the player or where ever you want to rotate from . . .
but i never really refined it tbh
why u want to add to ur suffering?
right hand camera.. left handed weapon?
when i have a script inside of a game object, does gameObject directly reference the object the script is in?
don't they talk about that in the video you got the bow n arrow pic from?
Camera-Gun Convergence
- raycast from camera
- align gun barrel to match raycast hit point
- fire projectile from gunmuzzle
i still anticipate edge-cases to sort out
yes, the script is attached to a GameObject, so .gameObject is the GameObject the script is attached to . . .
if (Physics.Raycast(ray, out RaycastHit hit, maxAimDistance, aimLayerMask))
{
Vector3 targetPoint = hit.point;
gunMuzzle.LookAt(targetPoint);
}```
thank you
{
// Default to aiming straight```
this is def something i'd need to tinker w/ hands-on tho
mmhmm make sure to test tho.. for different situations..
if i remember correctly when i did something like this.. i had to ignore times when the gun was less than so many units from a wall for example.. else the crosshair and raycast hit point was wildly different
i think in that case i just shot from the gun str8 forward.. but idk been a while
also, you can hover over gameObject and intellisense will display the information for you, and there's also the !docs for gameObject . . .
is this in vs
cause i tried installing the unity integrator however it doesnt seem to do much for me
yes, your IDE should have intellisense (along with auto-complete) . . .
!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
yup that was pretty much my solution as well.. if u discover a better one i'd be happy to hear
for left handed guns (which i did experiment with) i'd move my camera to also be over the left shoulder..
ur original drawing confused me a bit
using UnityEngine;
public class pointCollection : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.CompareTag("Player"))
{
print("collected");
Destroy(gameObject);
}
}
}
does this look right for a coin collection script, its not working for me
the coin
using UnityEngine;
public class oppSpawner : MonoBehaviour
{
private int numOfOps = 5;
private int[] ops = new int[5];
public float startingPos = -10.43f;
public GameObject spawnable;
private Vector3 spawnPos = new Vector3();
private Vector3 spawnRotation = new Vector3(180, 0, 0);
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for (int i = 0; i <= numOfOps; i++)
{
spawnPos = new Vector3(startingPos, 4, 3);
ops[i] = i;
GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
}
}
// Update is called once per frame
void Update()
{
}
}
why is my stuff spawning in the wrong spot
im just touching the coin nothing seems to happen
also how do you delete components off of an object?
changing startingPos doesn't seem to do anything
yes they both do
yes
oh wait
maybe not
i just tested it with a rigid body
no difference
yeah its probably a small issue
well see
i did not
it works
thank you
will do! thanks for the help
I want them to be evenly spaced out over the screen
I'm getting this error message at line 15:
"The Object you want to instantiate is null"
1 using System.Collections;
2 using System.Collections.Generic;
3 using Unity.VisualScripting;
4 using UnityEngine;
5
6 public class GameAssets : MonoBehaviour
7 {
8
9 private static GameAssets _instance;
10 public static GameAssets instance
11 {
12 get
13 {
14 if (_instance == null)
15 _instance = (Instantiate(Resources.Load("GameAssets")) as GameObject).GetComponent<GameAssets>();
16 return _instance;
17 }
18 }
19
20 public Sprite getSpriteById(int id)
21 {
22 int size = 2;
23 Sprite[] cardArtList = new Sprite[size];
24 #region indexing of cards
25 cardArtList[0] = placeHolderSprite;
26 cardArtList[1] = Umbright_Amalgam;
27 #endregion
28 return cardArtList[id];
29 }
30 public Sprite placeHolderSprite;
31 public Sprite Umbright_Amalgam;
32}```
I dont know what is causing this
easier to post !code using these links for us to read/look at . . .
📃 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.
ah thx
if the error states the object you want to instantiate is null, then it's not finding the object/asset you're trying to instantiate. if this is not the full error, post a pic of the actual error message . . .
this is the full message
Resources.Load("GameAssets") is null probably
why not just add that gameobject as a reference though
because I'm assigning a sprite to a blank sprite renderer that's on a playing card's prefab.
the sprite changes depending on the card but the prefab stays the same
Is There any way to make the resources folder accessible for players ? Or any other method to access the regular game data folder ? (I want my players to put in their own sprites)
you can let players upload sprites to a server and load the sprites via Addressables
from the server
why would I host a server? 😭 that sounds way more complicated than just accessing the files! Like I want every player to add individual sprites to his game
Not to every other players game too
Or is server like a file thing ?
resources are for static resources, they're bundled in with your game, it's not a folder you can just drop stuff into
you can let players set custom stuff themselves (not needing a server) but not via that
a quick google search yielded this
https://discussions.unity.com/t/import-custom-avater-pictures-in-game/146313
Yeah I realised when building the game XD that’s why I’m looking for options
for future reference, you basically have an XY problem here; start with what you're trying to do, the part you put in parens. that's the important part
Sorry for the confusion! That’s why I put that explanation of what I want to do in the brackets but I guess that wasn’t the cleanest way to do it
How did I not find this when googling myself thanks ill look into it tomorrow
Ah yeah that’s what you said as well lol
My fault, misread your message
Do I need to import any libraries to access the Resource folder because this is for some reason not working:
Debug.Log(Resources.Load("1").name);
you misspelled Resources in the folder name
soo the debug line works but not the actuall one:
gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Resources/1");
why did you put Resources in the path ?
that was it ty
I was trying out earlier if that would change anything
but forgot to delete it
can we tell a PolygonCollider2D to copy the shape of the current spriterenderer? Like doing a Reset (Context Menu) on it?
did unity expose the method for that?
Sorry... that page seems to be missing!
The page you are looking for might have been renamed, moved, or deleted.
i want to change music volume in realtime using slider from my options menu, so when the player drag the slider the music volume changed.
how do i change my volume value as the player is dragging a slider ?
slider has this https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.Slider.OnDrag.html how do i utilize this ?
nvm there is on value changed on the bottom of slider component 🤦♂️
Hello, Quick question. Where to add in this script for example "speed" so that I can change the speed of this script? ```cs
transform.Translate(Vector3.up * Time.deltaTime);
there's no speed there
but where i should add
you'll have to add your own coefficient
multiplied with Vector3.up * Time.deltaTime
thanks i will try this
quick question, currently as a beginner, for somehow my character is moving upward while pressing W not moving forward, how can I solve this. Had created and also implyed character inputs
wherever in the multiplication you want, since it's associative
multiplying a vector with a float is technically more expensive but it's not really gonna affect anything at this point
well, check what you're doing when you press W
you're probably not going the right direction
or your forwards direction is wrong
can't really answer much without any detail
I'll get a picture of the input
!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.
idk if this is the right code or not
I used the default Character Input Unity had provided, might could be the issue
here is a picture of the bindings
show what you're actually doing to move
so you're doing 3d right
y is up
a Vector2 is x and y
you don't need to assign the x and y manually here btw, you can just construct it directly
if you were to keep the x/y binding, you could also just Vector3 moveDirection = input; but here you need to remap it
I see
so it'd be Vector3 moveDirection = new Vector3(input.x, 0, input.y);
also pretty sure you don't need the transform.TransformDirection there
I'm following a YouTube video, basically a 1:1 copy so yeah....
I'll change it and see the result
should I delete the ```cs
moveDirection.x = input.x;
moveDirection.y = input.y;
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
K, I'll go check
here is the changed code, thanks for the teaching
public void ProcessMove(Vector2 input)
{
Vector3 moveDirection = new Vector3(input.x,0,input.y);
controller.Move(moveDirection * speed * Time.deltaTime);
}
I have this code
collision.CompareTag works if I leave it as OnTriggerEnter2D, but doesn't if It's OnCollisionEnter2D
am I doing something wrong ?
It said I need collision.gameObject.Comparetag for it to work
yes that's correct
OnTriggerEnter2D and OnCollisionEnter2D have different parameters
How do I find out if an object is not destroyed?
foreach (var interactable in _interactables.Where(it => it is not null)) interactable.enabled = false;
I have some interactables that are destroyed at runtime without notifying this script
Actually nvm I think it might be != instead of is not because of the unity stuff
Yes, you can't use modern null checking operators
their approach is incompatible with the operators, the API would have to be changed entirely
as it would break so many things, I'm not sure it will ever happen
but we can hope the next gen Unity has some changes
how to stop a player when he touch a block? or he is close to boxcolider block/object ```cs
public float speed;
bool MoveRight = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
MoveRight = !MoveRight;
}
if (MoveRight)
{
transform.Translate(speed * Vector3.up * Time.deltaTime);
}
else if (!MoveRight)
{
transform.Translate(speed * Vector3.down * Time.deltaTime);
}
}
i try use box colider but he goes through the wall
Use the Character Controller or Rigidbody component. The first gives you basic collision detection. The second simulates Rigidbody physics (the entirety of it)
You'll move through the wall if you're teleporting otherwise (that's what changing-position/translation with Transform does)
Should I abuse FindFirstObjectByType<> as a way to set reference ? What is the best way to refer to something else ?
no, just set it directly in the inspector