#💻┃code-beginner
1 messages · Page 290 of 1
yea
'ello again fellas.
Sooo be working at this for a little bit and think I have a solution that SHOULD work.
BUT, I've broken something and I really can't see where.
In the Enemy Script, the enemy is looking for a Path and a Formation, but for some reason, now they aren't getting assigned/found to the necessary variables.
Could someone lend me their eyes please and try to see what I'm missing as I just cannot see it. 😦
Enemy Script
https://hastebin.com/share/jiqofakebo.csharp
Spawn Manager Script
https://hastebin.com/share/oyalelorud.csharp
EnemyCountTracker Script
https://hastebin.com/share/balonipapo.cpp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ok can either be that localScale going on, or an Animation for that direction
Animation used i only have one direction and i used script to flip direction when moving
if I put a layer on an empty gameobject, will it still get picked up by a sphereOverlap even if it has no collider?
aight, i'll just put it on a physical one then
cheers
yes colliders = physics
are you switching sprite
you have to show me where the object goes when you flip, cause nothing in the code wrong
show the hirerchy + inspector for player
can you disable the animator during playmode and try going to wall again and flipping direction
also please don't use a phone to take screenshots
I'm making a conveyor belt and when the objects move from 1 conveyor to another they get slower or stop moving for a small period (probably move slower)
public class BaseConveyor : Building
{
[SerializeField] private float speed = 1f;
[SerializeField] private GameObject conveyorBelt;
private List<Ore> ores = new List<Ore>();
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.TryGetComponent(out Ore ore))
{
ores.Add(ore);
}
}
private void OnCollisionExit(Collision other)
{
if (other.gameObject.TryGetComponent(out Ore ore))
{
ores.Remove(ore);
}
}
private void FixedUpdate()
{
foreach (var ore in ores)
{
if (ore != null && ore.Rigidbody != null)
{
ore.Rigidbody.velocity = conveyorBelt.transform.forward * speed;
}
}
}
}```
the colliders of both conveyors are overlapping, so that shouldn't really be the problem... Right?
!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.
are there any scripts that may help me with 3D grid building (Survival based game) ive looked around and keep finding for 2D games
i take damage, and the collisions between the layers of the spikes and player are ignored for invulnerability frames, but when it comes back, the player takes 2 damage instantly, and when i play the game again the layers are completely ignored?
having these issues, i feel its all related to one thing but not sure what, i have a duplicate project with a different name (for building to another platform) and im not getting any errors from that project
its odd because this project has worked before and i've built from it
Did you recently start using asmdefs?
i've never heard of it or seen the name so i doubt it
is there a way of checking if i started using it?
Yeah, search for asmdef files in your scripts folder
nope, havent got anything relating to asmdef
im guessing this would be because i have in my script to ignore layers when taking damage, apart from if the health is 0. but when its taking 2 damage it will ignore layers, but it doesnt reactive the layers afterwards
public class EnemyCollision : MonoBehaviour
{
public GameObject GameOverUI; // selecting the game over game objects from the hierarchy
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy")) // checks for collision with specific tag
{
Debug.Log("collision");
HealthManager.health = HealthManager.health - 1;
if (HealthManager.health <= 0 ) // checks if health is 0 or less
{
GameOver(); // calls separate function for game over
}
else // player is not dead
{
StartCoroutine(GetHurt());
}
}
IEnumerator GetHurt()
{
Physics2D.IgnoreLayerCollision(8, 9 , true); // ignoring collisions between 2 layers
yield return new WaitForSeconds(2); // 2 second timer
Physics2D.IgnoreLayerCollision(8, 9 , false); // stops ignoring collisions between 2 layers
}
}
void GameOver()
{
GameOverUI.SetActive(true); // shows game over screen
Debug.Log("Player Died"); // logs in console
Time.timeScale = 0; // freezes time
}
}```
i just went to the top level of my project and searched asmdef, theres a couple there related to code assist?
Your health variable appears to be static. If you did something silly like disable domain reloading without understanding what that does, then that is your issue
Are there actually asmdef files in the top level of your Assets folder?
no, its in the assets/plugins/codeassist/editor and then theres an amsdef and amsdef.meta
Then it's not relevant. It would have to be in either Assets or Assets/Scripts
ahh okay
if i dont have my health variable static then it wont work completely
i dont even know how to disable domain reloading or whatever
im guessing i could run Physics2D.IgnoreLayerCollision(8, 9 , false); with the awake function as a work around, but it doesnt really solve it
ScoreManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager Instance { get; set; }
public TextMeshProUGUI boxesText;
[SerializeField]
private IntSO Score;
void Start()
{
Score.Value = Score.Value;
boxesText.text = "Boxes Collected: " + Score.Value;
}
private void Awake()
{
Instance = this;
}
public void IncreaseScore()
{
Score.Value++;
boxesText.text = "Boxes Collected: " + Score.Value;
}
public void SetScore()
{
Score.Value = Score.Value;
boxesText.text = "Boxes Collected: " + Score.Value;
}
public void ResetScore()
{
Score.Value = 0;
boxesText.text = "Boxes Collected: " + Score.Value;
}
}```
this is saying the type or namespace name 'TMPro' could not be found
just one of the scripts with errors
try rebooting Unity and your IDE . . .
Health should not be static. you just need to get a reference to the actual component that holds that variable. oh and if the issue is that you have domain reload disabled and your statics aren't being reset, then you'll run into further issues with that. such as your character being considered dead immediately on running the game
but also go into the editor settings in the editor and show the Enter Play Mode options
static doesn't change anything here. as long as you get a reference to the health script, you can access any field (variable) on that script . . .
unfortunately doesnt change anything
have you somehow uninstalled those packages?
that?
yes
i must've done something at some point cause there are NO packages in the project
how i managed that i have no idea
I did click on it, but doesn't get me anywhere, instead it just shows what part was wrong like something in the Collider2D
sounds like the package manifest was somehow deleted. perhaps it wasn't committed to whatever vcs you are using?
it's not disabled. but still, your health should not be static
its possible
can i reference another script by saying using <script name>?
but this is on the original computer i worked on it with
no. you should learn how to use c#, there are beginner c# courses pinned in this channel. after that, you should go through the junior programmer pathway on the unity !learn site to learn how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah i dont have time for that
well i don't have time to help you then 🤷♂️
I have a simple 3d capsule, with a Character Controller and a Capsule Collider
I have another plane below the character, with a mesh collider.
However, my capsule goes right through the mesh, what am I doing wrong?
for starters, the CharacterController is already a capsule collider so you don't really need both (unless you have a specific reason for it). but also how are you moving the CC and is the mesh collider convex or non-convex
is there a way of speeding this up? It got much slower after I added the starter assets third person controller. is it due to the game getting bigger in file size?
is it actually stuck on Application.EnterPlayMode? because if so, that could indicate an infinite loop in your code. otherwise you really just gotta deal with how long it takes to enter play mode unless you mess with the enter play mode options (do not do so without understanding how they impact your project)
also the size of your scene impacts how long it takes to enter play mode as well
no, check the pinned messages under General . . .
ah I didn't know that
that actually seemed to fix it
its not stuck it just takes a good minute and half to load in, I only have a few trees baked into the terrain my character. none of my scripts use harmful loops
if it isn't getting stuck, then how long it takes to enter play mode depends on a few things, including the size of your scene, how much work you do in the earliest parts of the first frame (like in Awake), as well as those enter play mode options i mentioned (though, again, do not mess with them without researching how they will impact your project and work flow)
oh and read/write speed of your disk also plays a part. i was doing so much waiting when i had my project on an old HDD but after moving it to an NVME SSD it does everything (including entering play mode) much quicker
oh right okay that makes sense, I'm working on my HDD atm i'll transfer it to my SSD later
well i dont know if this was the best method or whatever but i just copied and pasted the files from the 'Packages' folder of the other project into the one i was having issues with and all the errors have been resolved (:
now would be a good time to set up some sort of version control if you don't have it already so you can avoid issues like that moving forward
yeah 😂 thats true
i was actually in the process of getting it sorted recently, maybe thats how it managed to mess up, cause i was having an issue importing from cloud to another device
whatif what if, unity exposes most component classes? Will it like hurt performance?
Expose in what sense?
var points = new List<Vector3>();
AxiomPoints.Add(new Vector3(1, 0, 1));
AxiomPoints.Add(new Vector3(1, 0, -1));
AxiomPoints.Add(new Vector3(-1, 0, 1));
AxiomPoints.Add(new Vector3(-1, 0, -1));
for (var i = 0; i < AxiomPoints.Count; i++){
points.Add(AxiomPoints[i]); //instead of this line, is there a way to add all of the points in AxiomPoints outside the loop?
points.Add(new Vector3(AxiomPoints[i].x, AxiomPoints[i].y + stemLength, AxiomPoints[i].z));
} ```
axiomPoints is a list of the same type
then pass AxiomPoints into the constructor for the points list
var points = AxiomPoints; ?
no, pass it into the constructor. var points = new List<Vector3>(AxiomPoints);
thanks
I do wonder how i can input that in the console
I am still stuck on what I am doing
This suddenly popped up after working for 2 days?
(Camera does not contain a definition for main)
you probably have your own class called Camera causing a conflict
component files provided to make it easy to manipulate (or break)
Is there any easy way to tell a cinemachine brain (Make this virtual camera go live now)?
Are you asking about the source code?
Change the priority of the virtual camera
public void BlendToCamera(Cameras camera)
{
switch(camera)
{
case Cameras.Default:
_DefaultCVC.GetComponent<CinemachineVirtualCamera>().Priority = 100;
foreach (GameObject go in _Cameras)
{
if (!go.name.Equals("_DefaultCVC"))
{
go.GetComponent<CinemachineVirtualCamera>().Priority = 90;
}
}
break;
case Cameras.FreeLook:
_FreeLookCVC.GetComponent<CinemachineVirtualCamera>().Priority = 100;
foreach (GameObject go in _Cameras)
{
if (!go.name.Equals("_FreeLookCVC"))
{
go.GetComponent<CinemachineVirtualCamera>().Priority = 90;
}
}
break;
}
}
That's why I said an easy way xD
Cache the active camera, and when you want to switch it, turn the active priority to 0, and the new active camera to 1. Cache the new active camera.
Unless there's a higher priority camera enabled, the most recently enabled camera is the one that will be active
So if you just never change priority, the way to make a specific virtual camera go live is to just enable it
you should also consider not basing your logic on the name of the objects and instead use a tag or check a property on the vcam or something
[ReadOnly] public GameObject latestActive; // Keeps track to the last panel opened, close that when another panels wants to open
public GameObject LatestActive
{
set
{
MainGUI.SetActive(!value);
if(latestActive)
{
if(latestActive != value)
{
latestActive.SetActive(false);
value.SetActive(true);
latestActive = value;
}
}
else
{
value.SetActive(true);
latestActive = value;
}
}
}```this pattern can work, just need some change to use cinemachine instead
just the components? cant?
The whole script
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Cameras
{
Default,
FreeLook
}
public class CinemachineBrainAssistant : MonoBehaviour
{
/* Singleton */
public static CinemachineBrainAssistant Instance;
/* References */
[SerializeField]
private GameObject _DefaultCVC;
[SerializeField]
private GameObject _FreeLookCVC;
private List<GameObject> _Cameras;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}
private void Start()
{
_Cameras.Add(_DefaultCVC);
_Cameras.Add(_FreeLookCVC);
}
public void BlendToCamera(Cameras camera)
{
switch(camera)
{
case Cameras.Default:
_DefaultCVC.GetComponent<CinemachineVirtualCamera>().Priority = 100;
foreach (GameObject go in _Cameras)
{
if (!go.name.Equals("_DefaultCVC"))
{
go.GetComponent<CinemachineVirtualCamera>().Priority = 90;
}
}
break;
case Cameras.FreeLook:
_FreeLookCVC.GetComponent<CinemachineVirtualCamera>().Priority = 100;
foreach (GameObject go in _Cameras)
{
if (!go.name.Equals("_FreeLookCVC"))
{
go.GetComponent<CinemachineVirtualCamera>().Priority = 90;
}
}
break;
}
}
}
Is this not foldable? damn
So using the name is only a matter of me copy and pasting new ones correctly inside this script
But I understand the general concern
until you accidentally change the name of one of the objects at runtime and suddenly your code no longer works
or you spell it wrong
uh no
because the object is cached in the variable
wait
nvm
ur right
I miscoded smth
I dont want to check the name of the object
but the name of the variable
huh
How do I do that? 🤔
you don't. you have two variables, just use the one you need to use at the point you want to use it
you cache the object and use that
also consider making your variables CinemachineVirtualCamera instead of GameObject. that would eliminate the need for the GetComponent call
I did that before
so instead of all of this:
foreach (GameObject go in _Cameras)
{
if (!go.name.Equals("_FreeLookCVC"))
{
go.GetComponent<CinemachineVirtualCamera>().Priority = 90;
}
}
you would just have _FreeLookCVC.Priority = 90;
Deleted it bcs I couldnt check the name
but is smarter yeah
But how would I do the condition then?
what condition? you have the switch statement already, you know which you need to modify based on the case
as if it have something to do at line 18
Show !code for PickUp.cs
📃 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 would be this, but as you said, using the name is not good in general.
foreach (CinemachineVirtualCamera vc in _Cameras)
{
if (!vc.name.Equals("_FreeLookCVC"))
{
vc.Priority = 90;
}
}
you do not need the loop if you only have the two variables
Yeah but I will have ~20 cameras
When walking to a specific point in the world, I want to blend to cameras
then we are back to my suggestion of checking a tag or some property on the vcam (or other component on the objects) instead of relying on the names
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Counter : MonoBehaviour
{
private TMP_Text _text;
private int _amountPickedUp = 0;
private int _allPickups = 0;
public int levelNumber = 1;
private void Start()
{
_text = GetComponent<TMP_Text>();
FindAllPickups();
_text.text = _amountPickedUp.ToString(); //+ "/" + _allPickups.ToString();
}
private void FindAllPickups()
{
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Pickup");
_allPickups = gameObjects.Length;
}
public void PickedUp(int value)
{
_amountPickedUp += value;
if(_amountPickedUp >= 100)
{
RemovePickups();
GameObject.FindGameObjectWithTag("Player Manager").GetComponent<PlayerManager>().AddLife();
}
_text.text = _amountPickedUp.ToString();// + "/" + _allPickups.ToString();
if (_amountPickedUp >= _allPickups)
{
PlayerPrefs.SetString("Gems" + levelNumber.ToString(), "Clear");
}
//for (int i = 1; i < 8; i++)
{
//print("Gems" + i.ToString() + ": " + PlayerPrefs.GetString("Gems" + i.ToString()));
}
}
private void RemovePickups()
{
_amountPickedUp -= 100;
}
}
or if it's something to di wtih "_text.text = _amountPickedUp.ToString();" since it is line 18
SO I will have triggers calling the blendcamera
I could actually just pass the vc in the blendcamera function
And only care about the 2 player-sided cameras
wrong script for the error
also !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.
Didn't they do that?xD
This isn't PickUp.cs
no
And it's not in a bin site
Large Code Blocks
if (otherCollider.gameObject.tag == "Weapons")
this SHOULD work right?
A bin website:
- Takes up less space
- Can be searched with Ctrl+F
- Has line numbers
- Can be opened in another tab
ah I see, it's normalized
I know, it's just that in pickup, there nothing written in line 18 besides the }
use the CompareTag method rather than string equality when checking an object's tag
You should use CompareTag instead
https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
yes there is
The error is in PickUp.cs so that's what you need to provide. Anything else is utterly unrelated
no, I said there's nothing written besides }
- Did you actually save the code and re-run it
- Post it anyway. !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.
yes
post the damn code to a paste site
so either way would work? and why is one better
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
public int value = 1;
public GameObject pickedUpObject;
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Player") || col.gameObject.CompareTag("Player 2"))
{
if (GameObject.FindGameObjectWithTag("PickupCounter") != null)
{
GameObject.FindGameObjectWithTag("PickupCounter").GetComponent<Counter>().PickedUp(value);
}
GameObject go = Instantiate(pickedUpObject, transform.position, transform.rotation) as GameObject;
Destroy(go, 0.5f);
Destroy(gameObject);
}
}
}
CompareTag is not only a little bit faster, but it provides relevant error messages like when you misspell a tag
so I'm using cube coordinates to control the behavior of pieces on a hexagonal board, and I was wondering how that could be turned into a 3D bitboard
!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 this expected when using the website?
public void BlendToCamera(CinemachineVirtualCamera _VirtualCamera)
{
foreach(CinemachineVirtualCamera vc in _Cameras)
{
vc.Priority = 90;
}
_VirtualCamera.Priority = 100;
_Cameras.Add(_VirtualCamera);
}
Okay. Now, ensure the script is saved, clear your console, and run the game again. See what the error says
Ah am I supposed to share a link or send the code here?
Or large code link and short code inline?
I feel so stupid jnow
What website?
Nono it's fine I understand now
why are you adding the vcam to the list here? shouldn't it already be in the list?
Not yet, thought I may only affect camera's that have been interacted with up until now
so you don't plan to ever trigger the same camera more than once?
I only have the 2 player cameras added in start
Ah true
Man this game jam really wears me out
also at this point, you may as well just scrap the whole system. keep track of only the most recently activated cam, and just lower the current camera's priority, raise the new one's priority then set it as current
no need for a list or a loop so your method is o(1) instead of o(n)
ok, now the error changed from the line "18" to "17" when i saved it
thx
so, the object with the tag does not have a Counter component
Good. Now we know what line the error is on. Something on line 17 is null
Guess it's that simple```cs
private void Start()
{
_CurrentCVC = _DefaultCVC;
}
public void BlendToPlayerCamera(PlayerCameras camera)
{
switch(camera)
{
case PlayerCameras.Default:
BlendToCamera(_DefaultCVC);
break;
case PlayerCameras.FreeLook:
BlendToCamera(_FreeLookCVC);
break;
}
}
public void BlendToCamera(CinemachineVirtualCamera _VirtualCamera)
{
_CurrentCVC.Priority = 0;
_VirtualCamera.Priority = 1;
}
I am not getting an expected result, but I debugged to see that the conditions are being met (the tag is correct)
So I always know the player's cameras (you can toggle freecam with f) and the last used.
you're forgetting to assign the _VirtualCamera to _CurrentCVC so that next time this is called with a different camera the old one is set to 0 priority
yup you're my hero
what do you mean you are not getting the expected result. what expected result
Also why do I use _? Does it have to be?
Do any of the Unity samples have a wave system?
yeah realised that was vague sorry, debugging and going to elaborate
What is the expected result and what is happening instead
Visual Studio suggested it
no, the _ prefix should only be used on non-public fields per the naming conventions
What are Identifiers
void AddTriggerCollider(GameObject block, Vector3 direction)
{
GameObject colliderObject = new GameObject("TriggerCollider");
colliderObject.transform.parent = block.transform;
colliderObject.transform.localPosition = Vector3.zero;
BoxCollider collider = colliderObject.AddComponent<BoxCollider>();
collider.isTrigger = true;
collider.size = new Vector3(1f, 1f, 1f);
collider.center = direction * 0.5f;
}```
I am officially lost, i've tried to get each collider onto the side of each face but have had no luck. Is anyone able to help me understand what i need to do here
names
That's just the Microsoft convention for C#. The mostly widely recongised naming convention. You don't need to do it, it doesn't really matter
no, again that prefix should be reserved only for non-public fields
with [SerializeField]
C# standards suggest prefixing all private fields with _.
I acknowledge that the council has made a decision but given that it's a stupid-ass decision I have elected to ignore it.
Sorry for writing in multiple lines, my thinking is
rn
I think you need to be more specific
Best way to learn the convention is read through the article yourself here. If you don't understand the terminology, another way is to program next to someone who is also doing it. Other than that, it's overcomplicated for what you're doing, you aren't working in a full team I assume, so it isnt required at all
What you do is very normal and a lot of people do that in Unity
Yup atleast the only programer
Kk thanks
You know CodeMonkey? Pretty sure he didn't use _. Maybe he does now
Anyone knows why my assigned cameras in the inspector are gone after starting playmode?
I have a component that I am adding to an object. After adding it, I'm trying to modify the component's values.
LootFall lootFall = coinPrefab.AddComponent<LootFall>();
lootFall.dirtPlatform = dirtPlatformsStatic[pressedKey - 1];
LootFall contains a public GameObject dirtPlatform. When I attempt to supply it with the GameObject, the IDE has no errors, but Unity has this error:
'LootFall' does not contain a definition for 'dirtPlatform' and no accessible extension method 'dirtPlatform' accepting a first argument of type 'LootFall' could be found (are you missing a using directive or an assembly reference?)
How do I modify the value of this component?
did you make sure to re-assign them after changing the variable type?
yup
They just disappear
Might it be the fact I am setting it to Instance?
Do you have more than one CinemachineBrainAssistant in the scene? Because one of em's gonna self-terminate and it might be the one that has the fields set
the script I am trying to access is the same one but i imagined it would clone for each instance, is that correct? The debug isn't occuring and i dont know why
The place to edit the collider wont show, any fix?
Ah i got it
funnyly enough I had to apply the changes to the prefab, I guess unity reload prefabs on play
If that debug log isn't occurring, there's nothing in woodInstances whose WoodCollisionDetection's broken value is true.
First question: What type is woodInstances? The list should probably already be of type WoodCollisionDetection so you wouldn't need to use get component
Because you already have another box collider on this object. Multiple colliders on the same GameObject act as an aggregate. You shouldn't put them all on one object
wood instances is a gameobject list
Aw man
Change the list from GameObject to WoodCollisionDetection
do i not need to access the game objects before accessing their collider?
You will likely need to reassign it if it was in the inspector
sorry why exactly?
Nothing you've shown mentions their collider, but also you could just make the WoodCollisionDetection script have a reference to the collider and get it through that
- GetComponent is slow
- Your code is overly complicated because you have to keep getting the component when you want to do anything with it
- All components have
.gameObjectto reference the object it's on
okay ill try this thanks
Ha.. I forgot to hit save on the LootFall script. That's all it was.
There's basically no reason to ever reference an object as GameObject, use the component you actually want, and if you need to access any of the GameObject's methods (usually SetActive or CompareTag, most others aren't used often) then you can just get the gameObject from the component.
Going up the chain is fast. All components are on a GameObject, so they all have a readily accessible .gameObject property. But not all objects contain all components, so the process for getting something on the object is slower
if get component is slow how do I get the script 'woodcollisiondetection' from here
Make SpawnWood.woodInstance also of type WoodCollisionDetection
Oh, the one also with the counter is in there. I wonder if there's something not working over there
sorry ive only converted floats and ints, how does a gameobject convert to a script
Your error is that there exists an object with the tag "PickupCounter" that does not have the Counter script on it
You don't "convert" it
you change the type of that variable. Presumably it also shouldn't be of type GameObject
Use the type you actually want
There's almost no reason to ever have variables of type GameObject, be more specific
do I create a new variable or something?
Ah, okay, so it's not of type GameObject. That was context I didn't know. SpawnWood is fine, that's a class you likely want to use
yeah
Does every SpawnWood have a WoodCollisionDetection?
no spawnwood is a script
I know that
woodcollisiondetection is a script inside of every wood instance
which is from a prefab
Does every object with a SpawnWood script on it also have a WoodCollisionDetection script on it
every object in spawn wood which is a wood instance yes
So, put a variable on SpawnWood that holds this object's WoodCollisionDetection. Then your woodInstances can be a list of SpawnWoods instead.
Then you'd just need to do woodInstances[i].collisionDetection.broken
or whatever you decide to name the variable
but not a list of spawnwood right? you mean id do spawnwood.woodcollisiondetection[i]
cause theres only one spawnwood
Then why did you tell me that every SpawnWood has a WoodCollisionDetection on it
I'm working on some basic movements, and I'm wondering how I should implement these in terms of structure so it'll be good.
For example, I want to be able to dash when pressing WW/AA/SS/DD consecutively.
The way I implemented this is somewhat like this
foreach (KeyCode keyCode in System.Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(keyCode))
{
if (IsEligibleForDash(keyCode)) // checks only WASD
{
if (lastTapTimes.ContainsKey(keyCode) && Time.time - lastTapTimes[keyCode] < doubleTapTime)
{
StartCoroutine(PerformDash(keyCode));
}
lastTapTimes[keyCode] = Time.time;
}
}
}
IEnumerator PerformDash(KeyCode keyCode)
{
isDashing = true;
Vector3 dashDirection = GetDashDirection(keyCode); // just transform.forward / backward / etc
dashDirection -= transform.up * Mathf.Tan(dashDownwardAngle * Mathf.Deg2Rad);
float startTime = Time.time;
while (Time.time - startTime < dashDistance / dashSpeed)
{
characterController.Move(dashDirection * Time.deltaTime * dashSpeed);
yield return null;
}
isDashing = false;
}
Now I'm wondering, should this be in a separate script entirely? What if in the future I add different combos? Like dashing with a slash, it should behave differently I guess.
maybe i did but i meant there is one spawn wood script which is inside of a shop, that accesses a woodinstance and each of those has a woodcollisiondetection on it
Counter is a script, so what do i do to fix it?
How about instead of me having to get tiny windows into your context, you just post the full !code for this script and SpawnWood, and probably WoodCollisionDetection as well
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Guys, I wanna add a way for an enemy to push the player away it depending on the position of the player. Anyone got any ideas ??
Add the script to the object?
fyi a script is also a component
oh, so... should i add soemthing in there or change something? so the counter script
BREAKING SCRIPT
public class breakingScript : MonoBehaviour
{
[SerializeField] WeaponFire WeaponFire; //Reference to the weapon fire script
[SerializeField] SpawnWood SpawnWood; //Reference to the wood spawner script
List<WoodCollisionDetection> woodInstances = new List<WoodCollisionDetection>();
void Update() {
if (SpawnWood.placing && !woodInstances.Contains((WoodCollisionDetection)SpawnWood.woodInstance)) {
woodInstances.Add((WoodCollisionDetection)SpawnWood.woodInstance); //Adds new wood planks to the list
}
if (WeaponFire.weaponInstance && SpawnWood.placing) {
for (int i = 0; i <= woodInstances.Count; i++) { //Checks through all wood instances to see if any should break
if (woodInstances[i].GetComponent<WoodCollisionDetection>().broken) {
Debug.Log("SHOULD BREAK");
Destroy(woodInstances[i]); //Destroys the object of the collider that the weapon hits
}}}
//KING SECTION WOULD GO HERE
}
}
SPAWN WOOD SCRIPT
!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.
If you want to reference the Counter script on an object tagged "PickupCounter" then the object tagged "PickupCounter" should probably have a Counter script on it
It was incredibly not right. On top of not using a bin or formatting you posted your SpawnWood script five times
oh mb i just clicked ctrl v once
So i have a tag player and a raycast that checks for that tag. However i also want to check if it hits anything else, nothing specific. Is there a way to do that, or do i have to make use of tag or layer?
These shoud not be GameObject they should be the type you actually want
uhhh I have the coutner script on the object tagged pickupcounter. the rubies which you pick up is tagged "PickUp" and have the PickUp script, and the text that change numbers when you collect them is tagged "PickupCounter" with the script Counter
is prefab a data type, and instance is a gameobject and placeholder is a gameobject
i can show a pic labelling 1 to 3
From what I see of the code, placeholder should be of type Transform, and the other two should be WoodCollisionDetection
Your line of code with the error is getting a random object tagged "PickupCounter" and then getting the Counter component on it. Which is throwing the error
but i don't think this is the issue as it was working
just the new code i made
Guys, I wanna add a way for an enemy to push the player away when the player touches it depending on the position of the player. Anyone got any ideas ??
So, standard knockback?
Your issue seems to be that you're referencing an object you don't expect to be, so I'm suggesting ways to clean up your referencing so it's easier to spot the problem. You're right that this isn't directly solving the problem, but it will make it easier in the future
i also access it's sprite renderer and collider
You'd want to reference the instance/prefab as the more common type used or you could reference all of the necessary component if needed.
sorry why should i make woodinstance and woodprefab of type woodcollisiondetection
Right, keep the placeholderSprite and placeholderCollider objects as they are and get them in Start. But if you made placeholder a Transform you'd cut down the length of your lines by a bit as well as being more clear about your intentions
Because that's the script you're working with on these objects, right?
That's the component you actually want to use
should I change the tag in the script from "PickupCounter" to "Pickup"?
if not that's what you mean by that. I don't get why getting a random object tagged "PickupCounter" and then getting the "Counter" component on it is like.
General rule of thumb is to never reference as Game Object unless you aren't needing to do anything much with it.
Yh u got an idea how to add that?
no within the spawnwood script i never need the woodcollision script, just in the breakingscript
I don't get why getting a random object tagged "PickupCounter" and then getting the "Counter" component on it is like.
Because that is literally the line of code you wrote
What did you think this line did
I mean, yeah, there are tons of ways to do that. Usually the person asking would provide some details we could use. how you move objects is crucual to this
When you googled knockback, what did you find?
Right, so since you need to use woodInstance's WoodCollisionDetection in another script, this variable should be of that type. And since the variable is the most recently spawned instance of woodPrefab, that means that variable's type needs to change too
If you call Instantiate on a component, it still spawns the whole object, it just returns that type
could i not just make a different variable called woodinstancescript (or something like that), make it reference the instances' scripts, and then access it from the breakingScript
ohh okay
why
ill see if that works
why would you make a second variable that holds the exact same data
just change the type of the one you already have
hmmm... finding the gameobject with PickUpCounter to find where the counter script is located in?
cause i didn't know ab that instantiate thing
two basic approaches are manipulating the transform or using rigidbodies
GameObject.FindGameObjectWithTag("PickupCounter")
"Get me a random object in the scene tagged PickupCounter"
GetComponent<Counter>()
"Get theCountercomponent from that"
If you have any objects tagged "PickupCounter" that don't have a Counter component on them, this line can error.
If you have some objects with that tag that have that script, this code will sometimes work
oh, so I should change "FindGameObjectWithTag" into somethign else?
What object are you trying to call .PickedUp on
that how many rubies you collected
I have no idea how that sentence answers my question
tbh.... I don't know, it was a long time ago since I looked at that script and have been doing some changes for the second game
So, if you don't even know what you want to do, how are we supposed to help you figure out how to do it?
Decide what you want to happen first, then work on a way to make that happen
you kinda missed my other comment here
It feels like we are crowdsourcing this game
but maybe when the ruby gets picked up, the counter goes up based on how many you collected
like when the object with the tagname "PickUp" gets touched, the counter goes up with a higher number
Okay, so what object has the counter you want to increase
this is the counter number with "0"
Okay, so you want to reference this specific object's Counter script
yeah (here's the full screenshot)
I'm guessing the object with the PickUp script is spawned in at runtime
Otherwise you could just drag it in
drag it in?
Unity seems to display my method as missing (even when I reassign it)
Not sure why
okay I finished this now
If your PickUp objects exist in the scene, you should just make a public field and drag in this object. Since you haven't done that I assume the PickUps are spawned at runtime?
Takes a boolean, not object
Maybe that is the issue?
Dunno
Okay, so, going back to your for loop that wasn't printing the log, can you share the updated code for that loop?
isn't a boolean an object? also it still displays it in the inspector so yeah
make a public field? (the pickups and counter works in the game editing, but not in the actual game itself) what type of public field?
Bool is a primitive. I don't think it is an object
woodinstances now consists of scripts, destroy destroys an entire gameobject if im not mistaken?
everything is an object, even primitives
Ok, gotcha. Wasn't sure
Thanks
set it to some other method then set it back. i've had that happen when moving components around and just changing it to something else and then back made it work
Okay, so we can get rid of the .GetComponent from that if, it shouldn't break anything. Since the log isn't happening, then broken is not true. Put this log above your if statement:
Debug.Log($"{woodInstances[i].gameObject.name}'s broken value is {woodInstances[i].broken}",woodInstances[i]);
You'll need to do Destroy(woodInstances[i].gameObject) for that
hm, doesn't seem to work
Counter
oh okay, also the instantiate is broken rn, so i need to check that
Pretty sure UnityEvent doesn't have an editor for the type object so it doesn't know what to draw for the input. If your function takes a bool, you should pass it a bool
I mean what should i write there?
That
That's the type of public variable you'd make
and drag in your counter object
the function can take anything, but it's still weird that it appears in my toggle in dynamically and static
...huh
woodInstance = Instantiate(woodPrefab, placeholder.transform.position, Quaternion.Euler(0, 0, rotation));
woodPrefab is now of the script's type, not a gameobject, and it isn't working
as well as woodinstance
that?
What isn't working? Did you re-assign the prefab to the variable?
Yes
yes
I told you what you'd put for the variable. Counter @hushed hinge
So what isn't working about it?
I said "what am i supposed to write there" in the script because I don't know what type of public variable I'm supposed to write
it says the object i want to instantiate is null
You are supposed to write Counter
Counter
The type would be Counter as suggested
Can you show me the inspector of your SpawnWood?
also I access different components of the instance from other scripts, so can that remain the same, or do I say woodInstance.gameObject.GetComponent..... or can it remain as gameObject.componentname..
If you're doing GetComponent anywhere on the object, it can remain the same. GameObjects and components all have the same GetComponent functions
phew
eh, I'll just make a bunch of overloads until there's a solution
also, should this be put in the pickup script, or in the counter script? I just want to make sure
It of course needs a name too...
Did you make sure to drag in a prefab into WoodPrefab and not an object in the scene?
The pick up script. The Counter script does not need to reference itself
Do you want the counter script to reference a counter?
When you hit play, does the object remain assigned? Are you maybe reassigning it in code or destroying it?
wood (1) usually implies it's a clone and possibly an object in the scene
ok, that name?
But perhaps that could be the name of the prefab - strange name.
for some reason the error just disappeared
but still need to fix the breakingScript
Maybe something didn't save? Either way, we can proceed with the debug log I sent earlier
i ss'd it aboce
probably
your good at this yk, im trying it now
Soooo, had a few hours away from the PC and still can't see what the balls I'm doing wrong. lol.
@polar acorn no errors, but doesn't work. I feel like the error might be that im accessing it from a prefab, but i have no clue
and then like that?
Are there any errors?
Wait I thought broken was a bool why are these numbers?
it is a bool, I am not printing broken anymore since it didnt work, im printing the force on impact when the cannonball (weapon) hits a wood instance
Yeah, although the name is weird. You now have a reference to the Counter on these objects. You can now call whatever functions or change whatever values you want on that object
that works but not breaking the wood instance
Only when it runs, because the Enemy's can't find the Path and formation objects. It's that what is confusing me cause it was working find before I reworked a bit. And I can't see where it's broken.
ok, imma try it in-game
Can you show the runtime error?
Well, for now, we're printing broken to show that they're all false. We're going to add another log in the collision script where you try to set broken. Can you post the !code for that one, by the way? It was posted a while ago but it's way up there now
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'd rather not play guessing games.
public class breakingScript : MonoBehaviour
{
[SerializeField] WeaponFire WeaponFire; //Reference to the weapon fire script
[SerializeField] SpawnWood SpawnWood; //Reference to the wood spawner script
List<WoodCollisionDetection> woodInstances = new List<WoodCollisionDetection>();
void Update() {
if (SpawnWood.placing && !woodInstances.Contains(SpawnWood.woodInstance)) {
woodInstances.Add(SpawnWood.woodInstance); //Adds new wood planks to the list
}
if (WeaponFire.weaponInstance && SpawnWood.placing) {
for (int i = 0; i <= woodInstances.Count; i++) { //Checks through all wood instances to see if any should break
if (woodInstances[i].broken) {
Debug.Log("SHOULD BREAK");
Destroy(woodInstances[i]); //Destroys the object of the collider that the weapon hits
}}}
//KING SECTION WOULD GO HERE
}
}
I meant on the WoodCollisionDetection where you're setting broken
public bool broken;
public float breakingForce;
void OnCollisionEnter2D(Collision2D otherCollider) {
if (otherCollider.gameObject.CompareTag("Weapons")) { //Enters if the wood is hit by a weapon
Rigidbody2D rb = otherCollider.gameObject.GetComponent<Rigidbody2D>();
float weaponForce = rb.velocity.magnitude * rb.mass; //Calculates the force
Debug.Log(weaponForce);
if (weaponForce >= breakingForce) { //Enters if the weapon overpowers the wood
broken = true; //Object hit wood at enough of a force to break it
}
else {
broken = false; //Object did not hit object at enough of a force to break it
}}}
}
Unless you're wanting to simply destroy the component, make sure to call the gameObject property during the destroy call.
It's the Object not set to a reference. I know why the error is being created, I'm just not sure what I broke.
thanks, forgot to add that
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'd want to see the error to know the conflicting line to work backwards.
https://gdl.space/hobuvofide.cs
I need help please, I tried to write a jump code, but for some reason it doesn't work!
Describe what exactly doesn't work. Show any errors that you've got.
👆
from 117 line
Bear with me, don't have it open atm.
That's the problem, it doesn't show any errors at all
So what doesn't work?
When I try to press space, it just doesn't jumping
uhhh, it seems to be still not working in-game and the error is the same
Does it not detect input? Not moving your character? Not executing any lines of code? What doesn't exactly work?
Looks like you normalize the movement in Move() so the jump power is not really gonna be that high at all (line 240)
Anyone got an idea to add knockback to a player?
The character does not jump, it is not related to the input
So input is detected but the jump is either too little or not present?
Place a log to see if jump was detected
If detected, check the amount your jumping (value)
No, it just doesn't work 😅
You've got to put some effort to debug stuff
Yes bro this is the room
It is a link to a message
Where I told you the likely issue
@polar acorn any ideas? 😅
Something is null on that line.
I didn't quite understand what you meant
Yes, I put logs, wait a second
yet i don't know why right now
Do you know what normalize does?
no bro 😅
It makes the magnitude of a vector equal to 1
It's pretty simple. If not found, you'll get a null exception. If found but the component wasn't on the object, you'll get a null exception.
So the jump force you are trying to add is possibly minimized into negligence
then what should i do to fix that?
Show the updated !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You probably want to normalize all the other input, then combine the inputMove.y (or whatever it was called) with it
Consider the two possible culprits. Your if statement guards an nre from occurring with one of them. The other is still applicable.
it is here
(Sorry, I stepped away for a second)
Change your weaponForce log to this:
Debug.Log($"{gameObject.name} is colliding with {otherCollider.gameObject.name} with a force of {weaponForce}. Breaking Force is {breakingForce}");
Why are you still using find
its fine, thanks for your help
You have a public variable now. Use that
it is the updaated code, I added that public counter like you said
So why are you still using find
I did not understand what you mean
Why are you not using your public field
@ivory bobcat Ok, according to the logs it detects that I press the button but the character just doesn't jumping
Pickups.PickedUp(value);
Assuming both are present in the scene outside of runtime and properly assigned from the inspector
I asked them if they were spawned in at runtime and they said no so hopefully that's the case
debugs perfectly
This is your possible solution
Okay, and if we go back to the first log I had you write, do you see anything with the name wood (1)(Clone) being logged with a broken value of true?
CORRECT! TYSM!
But every time I turn around the character moves really weird, is this related?
characterController.Move((inputDirection * (_speed * Time.deltaTime)) + new Vector3(0.0f, moveDirection.y, 0.0f) * Time.deltaTime);
nothing else is logging
and i dont remember the first log honestly
Well. You still want the normalize.
Now diagonals will go faster
you never told me anything about i should change something in the line 18
They're also destroying this game object so perhaps if they do spawn this game object.. When they do, they can assign the public fieldcs var pickUpInstance = Instantiate... pickUpInstance.PickUps = ...
where did you find that? or did you wrote it?
I am a beginner 🥲
I told you to use a public field
I assumed you'd actually, yknow
use the public field
is that not just this @polar acorn
The whole conversation was about what object you wanted to call PickedUp on, so I figured you'd know to call it on the thing I told you you would be calling it on
I know that, you said i'm supposed to put "public Counter" yeah, but never said anything about writing soemthing in line 18
Right, so the idea was to log the collisions when they happened, and to log the list you were looping over
Do inputDirection.normalized
Just DON'T do normalized on the y one
characterController.Move((inputDirection.normalized * (_speed * Time.deltaTime)) + new Vector3(0.0f, moveDirection.y, 0.0f) * Time.deltaTime);
like this?
not sure if this is your idea but it didnt log
Yeaaaah. I think so
Yes. I told you to make a public field to use to call PickedUp on since that was what we were talking about. Are you just waiting for me to drip feed you code? The words I write are important too, not just the code. What am I even typing all this up for if you're not going to read any of it
TYSM BRO (:
I saw your field up top and assumed you ought to be using that instead of searching the entire scene for the wanted game object that might not exist or that might not have the correct component.
so debug if it's false?
@hushed hinge you see, this is employing a technique we like to call "thinking". Taking information that is available and synthesizing new information from it
No, put that log, as I wrote it, before the if
Sorry, got stuck on a phone call.
It'll log the broken state of each object in the list
If you reference it as the Component type Counter, it'll be sure to have said component whereas find can throw an nre if the object doesn't exist or if the component doesn't exist when attempting to access the pickup method.
so not in this script, the other one, with the for loop, is what you mean?
No I mean in this script. In the loop where you check each object's broken boolean
this script doesnt have a for loop
as it is within every wood instance object
What
so you do mean the other script right?
I mean on the one where you're checking broken. Not where you're setting it
Actually the longer I look at this the worse it gets
Do you even know basic C# syntax
that has a for loop but it can't detect 'otherCollider', as the wood instance detects that within the oncollisionenter method
Where would you need otherCollider in the log I told you to put there?
Wait, did I link the wrong message of mine
hang on
I might have done a dumb
Their "teachers" "taught" them the basics
np
So line 103 would be this line cs distance = Vector3.Distance(path.bezierObjectList[currentWayPointID], transform.position);where path or the list could be null and would throw an error.
Okay I might have linked you to the wrong log before, this is the one I want you to use
#💻┃code-beginner message
Literally what are you doing. Are you just guessing
Do you know how to call a function on an object
You have the counter object
call the function on it
why is there a find
why is it using the Counter class instead of the instance
Why are you getting the component from itself
why is any of this
my bad thought that was the exact same thing
Yeah, in the inspector for the Enemy script, it's not assigning the Path and Formation to the enemy. Like I said, it was working before I changed a couple of things to be able to keep track of how many enemies per wave there are, but I didn't touch any of the path and formation stuff, so I'm really confused as to where I've broken it, and can't for the life of me see what the issue is. 😕
I just looked at the red line there
bro i think I just found the issue, it was a big slip up 🤦♂️
Check which of the two are null. If the first, it's passed from Update as the variable pathToFollow. If the second, figure out why the list is null.
They wanted you to use that variable where the green was and use it where the red was
Thus the arrow....
@hushed hinge I will not be typing the code you should be using. I am going to explain this in words and you're supposed to read it and learn things. If you're just going to smash random bits of text together until you get it right and wait for me to validate it I am not going to entertain that. If you have an actual question (not "what do I write") I will answer that, but if you post another random keyboard mash and expect me to tell you if it's right I'm just no longer going to reply to them
The red line was CROSSING OUT the code. As in, remove it
So when would this field be assigned?
If you have, then that's great. I hope you've picked up some debugging steps to try in the future (particularly those String Interpolated logs with a bunch of extra info, they're great for finding where things are going wrong)
Always remember to check your assumptions, things you think are true might not actually be
They should be assigned as soon as the Enemy prefab is spawned. I'm just going through again and comparing my two versions of the scripts to see if I can spot where I've buggered it up.
I have an issue where my transform.position equals the "lootTopHeightFloatingPosition", but the while loop still continues forever.
lootTopHeightfloatingPosition = (-1.28, -9.03, 0.00)
transform.position = (-1.28, -9.03, 0.00)
public IEnumerator LootAnimationNow()
{
while (transform.position != lootTopHeightFloatingPosition)
{
Debug.Log(transform.gameObject.name + " position is " + transform.position.ToString());
Debug.Log(transform.gameObject.name + "targetPosition = " + lootTopHeightFloatingPosition.ToString());
Debug.Log(transform.gameObject.name + "speed = " + speed.ToString());
Debug.Log("Still in the while loop.");
// Move one step toward the target at our given speed.
transform.position = Vector3.MoveTowards(
transform.position,
lootTopHeightFloatingPosition,
speed * Time.deltaTime
);
// Wait one frame then resume the loop.
yield return null;
}
}
Even though the two positions end up matching, the while loop keeps going so I end up overshooting my mark.
Maybe I should have posted this in code-general.
I'm on mobile and have not looked at the other scripts yet but I'm assuming you've got something like this occurring cs var enemy = Instantiate(enemyPrefab); enemy.pathToFollow = ...
that shouldn't even be possible to overshoot. are you certain nothing else is affecting the position during this coroutine?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you said the red line meant was to remove it
private IEnumerator SpawnWaves()
{
while (currentWave < waveList.Count)
{
enemyCountTracker.IncrementWaveEnemyCount(currentWave + 1);
enemySmallID = 0;
for (int i = 0; i < waveList[currentWave].smallEnemyAmount; i++)
{
GameObject newEnemySmall = Instantiate(enemySmall, transform.position, Quaternion.identity);
Enemy enemySmallBehaviour = newEnemySmall.GetComponent<Enemy>();
enemySmallBehaviour.SpawnSetup(waveList[currentWave].path, enemySmallID, waveList[currentWave].enemySmallFormation);
enemySmallID++;
yield return new WaitForSeconds(enemySpawnInterval);
}
yield return new WaitForSeconds(waveSpawnInterval);
currentWave++;
}
}
Counter is not a word you should use there at all
And the part to remove is the part that was crossed out. Not the whole line
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Stop guessing
Learn how variables work
Learn how to call a function on a variable
It's quite literally day one programming knowledge
this is a fundamental thing from which all other knowledge depends on
This is the absolute most basic thing about c#
Consider yourself to have 0 knowledge in coding at this point if you can't figure out what you were told to do
It should have been exactly what I had here #💻┃code-beginner message
where you'd either assign the field through the inspector if the object wasn't instantiated or assign the field after the object was created.
if you don't know how to call a function on a variable holding an instance, then you cannot progress further until you do
so i found an issue in that i had an if statement (before the for loop to check for the broken bool), which required that spawnwood.placing was true, as there was a null reference error previously. However, placing is only true when the user is placing wood, but if you click the shop again (to deselect wood), placing becomes false. The issue i solved from removing that is that the player would never be firing the slingshot and placing at the same time, but now i get this:
There shouldn't be, because the lootTopHeightFloatingPosition coordinates stays the same the whole time. This is also the only coroutine on the game object.
you know something can affect an object's position without being in a coroutine, right?
Okay, so, let's see what's at line 18 of breakingScript
lines 16 to 18:
if (WeaponFire.weaponInstance && SpawnWood.woodInstance.gameObject != null) {
for (int i = 0; i <= woodInstances.Count; i++) { //Checks through all wood instances to see if any should break
Debug.Log($"{woodInstances[i].gameObject.name}'s broken value is {woodInstances[i].broken}",woodInstances[i]);
Yes. I don't think other things are affecting the position. But I am going to keep looking.
I cant find that key to send code on my keyboard
Please see #854851968446365696 and #📖┃code-of-conduct
There is some expectation for you to do your own thinking and effort
So you'll want to determine why the wave list element path was null.
Okay, so, if that last one is line 18, that means woodInstances contains a null in the list
You'll need to look at where you're adding things to the list and see what's coming in as null
Yeah, it's really driving me insane. I've gone through both versions of the Spawn Manager and Enemy scripts and they're identical apart from adding/removing enemies from the list. lol.
My bad I didnt see this, so i have the enemy hitbox and the player hitbox and if the player touches the enemy hitbox they get pushed a lil bit back. i wanted to know how to add this into my game. Ima also google it and see
Looks better but you could probably also do away with the guarding if-statement now. If you still get an null reference exception, that would mean that pickups is null and needs to be assigned from the inspector or by whoever spawned this object.
The thing we would need to know in order to help is how you move the objects (transform or rigidbody? If rigidbody, addforce or velocity, etc).
But yeah, just let us know how it goes and how we can help. Good luck
@slender nymph I missed a detail. It overshot, but it went back. The logs indicate that the position has been reached, so even if something was affecting its position, it is hitting its mark but it's still not escaping the while loop since you can see the position has been hit 5000 times.
you're probably starting the coroutine a bunch of times
My 'Wave' list is getting popuplated correctly
It's just the enemies not finding that info. 😕
How do you populate the lists: inspector or procedurally?
Procedurally. The number of 'Waves' is determined by the length of a song.
There wasn't any find that was an issue. The enemy was given null or the object no longer exists (the path)
It's likely one of the two
The Path is in the scene from Start (not instantiated).
Is the path ever destroyed?
make sure you're logging some useful information and not just the positions. you can log the condition your loop is checking as well as what object(s) are affected. you can also do it all as one log instead of having a bunch of different logs all out of order because they are collapsed
I put a break point at the start of the LootAnimationNow method, and it's only being triggered once.
WAIT!!! I think I've just spotted the issue, gimme a sec.
no more errors
Debug.Log($"{name} is moving at {speed} units per second from {transform.position:F3} to {lootTopHeightFloatingPosition:F3} which is {Vector3.Distance(transform.position, lootTopHeightFloatingPosition):F3} units away. Has reached destination? {transform.position == lootTopHeightFloatingPosition}");
add this log so we can see exactly what is happening
Yes, I am a collosal penis.
Enemy_V002 enemySmallBehaviour = newEnemySmall.GetComponent<Enemy_V002>();
This line here, I didn't update it to reference Enemy_V002.
Is everything good now?
i think the issue is the for loop, lists index start from 0 right?
i can pick up the rubies and the counter is going up
well that is certainly odd. Vector3's equality operator is overloaded to return true when they are approximately equal so it's very strange that the condition is evaluating as false. it's less good, but you could check the distance and Mathf.Approximately with 0
I am only appending from the updatewoodinstances() function using the add method
Unless that function itself has something wrong with it, i am not sure
but i dont see anything wrong with it
Try logging SpawnWood.woodInstance before adding it
See if it's ever null when you add it
good idea
So I need to modify the while loop to do a check using Mathf.Approximately instead of the transform.position? I don't think I understand.
it debugs it as it shoudl
Does it ever log null?
yes, that is the next thing to try since you are getting irregular results with the Vector3 equality operator. compute the distance between the two points and use Mathf.Approximately to check when it has reached approximately 0 (since you should never compare floats using equality operator due to floating point imprecision)
but it logs null before it is added to the list which is expected
So you've added a null to the list
Which means when you try to use the object in the list, it'll throw a null reference
Is your list supposed to contain nulls?
Hi, can someone guide me how can I record microphone audio on android within unity?
oh your right
no
Yh i can go any way, as long as the player moves when the enemy touches it, ill add the rigid body stuff but what i dont know is when deciding the direction the player would move, how owuld the program know what enemy hit the player since ill be using tags
So, you should probably add a != null to that check you make before adding it to the list
i see what it is, i add one every time there is a new value of woodinstance, and as the game starts with it being null, it adds that to the list
yeahh
Well, there are many ways. How do you tell if it touches?
OnCollisionEnter will give you the normal of the collision.
The collision struct will also include the gameObject that hit you
@slender nymph If I set it to 8 floating points I can see that it's just a hair off.
right but as i've already pointed out the equality operator for Vector3 is overloaded to account for that
Cool, so I would use oncollisionenter and pass in a collider2d. then I would get the normalised direction of the enemy and use AddForce on the player with the direction the enemy is facing. Right??
while (!Mathf.Approximately(Vector3.Distance(transform.position, lootTopHeightFloatingPosition), 0))
I'm having the same issue with this one. I suspect I'm not comparing/checking correctly. You said I shouldn't use the equality operator though, but I'm not sure how to compare this to 0 if I'm not doing it already.
that is how you compare it to 0
I changed the debug line to use MathF.
Debug.Log($"{name} is moving at {speed} units per second from {transform.position:F8} to {lootTopHeightFloatingPosition:F8} which is {Vector3.Distance(transform.position, lootTopHeightFloatingPosition):F8} units away. Has reached destination? {Mathf.Approximately(Vector3.Distance(transform.position, lootTopHeightFloatingPosition), 0)}");
Still says it hasn't reached its destination.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
what could be a cause of this error?
You could definitely do that. Don't use the normal on that case then, because it may he different than the direction the enemy faces.
Grab the transform of the object you collided with and do transform.forward in the AddForce
The normal would be the direction "away" from the face of the mesh that was actually touched on the enemy
@slender nymph I'm still researching, but maybe it's because I am setting the position using "new".
lootFall.lootTopHeightFloatingPosition = new Vector3(CurrentDirtPosition.x, CurrentDirtPosition.y + 2.2f);
lootFall.lootRestingPosition = new Vector3(CurrentDirtPosition.x, numPadKey.CurrentDirtPosition.y + -1.1f);
https://discussions.unity.com/t/vector3-equals-not-working/101394/2
EDIT: I’ll leave my original answer, snide parts about not posting code removed ;), for others in case they have that issue, but I believe your issue is that you’re using Contains to check if one vector is equal to another vector, but you can’t do that because the = operator of vectors create new vector instances. I can’t find specific documen...
i guess just check the distance and compare it to some small number. i would have thought that unity's Mathf.Approximately and Vector3 equality operator would handle these floating point imprecision issues since they are meant to
That might be the way to go, in the forum post I see this suggestion:
float diff = Mathf.Abs(myVector1.sqrMagnitude - myVector2.sqrMagnitude);
if (diff < 10)
// Close enough
ah so it looks like unity's epsilon value is 0.0001 which is just ever so slightly smaller than your value of 0.0000124
that's actually hilarious that you are prevented from using unity's tools that help prevent floating point imprecision issues . . . due to a slightly bigger floating point imprecision issue
Oh my God this was maddening. I'm glad you understand what's going on. Thank you for your help.
One message removed from a suspended account.
How can I check if a specific action is done? I would have thought similar to this. I want to check if it's the action called "Pause".
if (context.action == CharacterControllerMap.SimpleMovementActions.Pause)
what is the context of this code?
private void Pause(InputAction.CallbackContext context)
{
if (context.action == Pause) Cursor.lockState = (Cursor.lockState == CursorLockMode.Confined) ? CursorLockMode.Locked : CursorLockMode.Confined;
else Cursor.lockState = CursorLockMode.Locked;
}
so assuming you've subscribed this to the Pause action's performed event and nothing else, then you can safely assume this is reacting to the pause action
you do not need to check that it is
Yeah but I subscribed with ESC and LMB
Could do seperate ones or simplify this
But do you know how to ask what action the context called?
i honestly don't understand what you are trying to do
characterControllerMap.SimpleMovement.Pause.started += Pause;
characterControllerMap.SimpleMovement.Interact.started += Pause;
I want to toggle pause with esc
why did you subscribe the Pause method to the Interact event
If I click I want to unpause
Okay I dont do that and only have esc toggle pause, thanks- xd
Do drag and drop references not work in a build btw?
That'S the reason I did this
To check the debug log in my build
you should instead make whatever is subscribed to the Interact event check if the game is currently paused and unpause it if it is instead of trying to check what invoked the method
of course they do
what would be the point in the ability to drag a reference into the inspector if it didn't work in a build
idk what theme for this is but I get nullpointers in my build
Which I do not in the editor
So I assumed that's the problem somehow
exactly what I thought
you'll want to check the logs to see where your null reference exceptions are happening and look at that code to find out why it may be happening
What is the timing of awake and onenable?
I just put the static instances before the ones calling them, so now it should work
they are both called immediately upon instantiation, in that order.
One message removed from a suspended account.
Is IDP.Generic something bcs of the development build?
maybe this would be helpful
pretty sure that's just a generic "we don't recognize this executable" message from your overaggressive AV
I see
@fathom frigate
One message removed from a suspended account.
Ive been really struggling with forcing myself to learn gamedev/unity or even to get an basic idea that isint too complex or strange, i want to make games but how can i with theses conditions? also yes i tend to be hard on myself.
just like i have it.. on ur input vectors b4 you pass them into ur Character Controller Movement function
Start with clickers
Very simple
And good for starters in 2d
you don't force yourself that's the first thing to do
Does UI work while timescale is 0?
if u want to be successful you gotta put the time in
what would you suggest then?
if at first u dont understand just rinse and repeat..
alright.
try multiple resources.. find what learning method works for you
and start simple like mentioned..
Flappy birds is a classic to begin with
also arcade games aswell?
@rich adder too lazy to say yes or no xD Hey I would try it but I'm trying to optimize my time used for the game jam
you'll feel better/ accomplished after u finish something..
so u want someone else to optimize their time for your needs instead?
You don't have to answer
yeah i need to feel that sense because so far in life ive only failed to say.
But clicking a message and reacting takes more time than saying yes or no
lol.. perhaps
I assume it's a yes
keep failing, until it eventually stops... a little
dont ask things you can easily test, its a waste of everyones time
One message removed from a suspended account.
ill try that
soo.. say i want to build a circuit board simulator.. every component would take an in and output an out. this would be 0, 1 most likely.. (then the interaction system is seperate) how would be the best way to do this? so they're able to interact with each other?
w/o some complicated (if me/else you) conditional
right after u assign move
you can normalize it
move.Normalize();
and thentransform.TransformDirection(move);
start with something small, doesn't matter what kind of game will that be but just start small
then ur ready to use it in ur controller.Move function
no need to change that line at all.. ur just modifying the move variable a bit before u use it
Thank you, those who responded to me and giving me advice.
Welcome to this introduction to game development. We'll be starting from the beginning, so no prior knowledge of programming or the Unity game engine is required.
Unity can be downloaded here: http://unity3d.com/get-unity
Watch episode 01: https://youtu.be/9iCnjdXEfMA
If you'd like to support these videos, you can make a recurring monthly don...
this is a playlist that helped me tremendously when i started
i should possibly make a clicker like that one dude said or an arcade game.
I know Sebastian Lague has a few videos exploring the subject. the code is also open source
https://www.youtube.com/watch?v=hEDQpqhY2MA
Displaying numbers is trickier than I expected! In this video we explore how to visualize the data inside of our simulated 4-bit registers, with the help of the double dabble algorithm and some seven segment displays.
Series playlist: https://www.youtube.com/playlist?list=PLFt_AvWsXl0dPhqVsKt1Ni_46ARyiCGSq
Simulation tool (work in progress): ht...
he also starts to make a game w/ the knowledge towards the end of hte playlist
ohh sweet! i love that guy
lol
how long is it becasue i find it hard to balance life, hobbies and highschool.
you have a point
so ill be sure to look into the playlist.
its pretty straight forward tho
don't make this a top priority that's for sure it's going to take a lot of time, frustration and copying and pasting
you have a point aswell. and ive trashed alot of projects because i was just messing around and they let to nothing.
so.. ur hobbies.. they'll eat up time.. (coding is a hobby) until u learn
Ye i spent a few hours at night cause i also can't rl do stuff in th day
I did actually had an idea about a game like this as well, well an idea it was
ya, i just want to play around w/ simple circuits.. like breadboarding in unity 😄
good thing i have no other real hobbies.
just dozens of ways to do it..
We all got to start somewhere and time is needed, start with half a hour everyday and build that up
i remember blowing up a breadboard with a failed xor condition
Same
see, it'd be cheaper to do it in unity 😄
that sounds crazy that, that happened.
ghostBlock = Instantiate(buildingPrefabs[BlockID], hitPoint, Quaternion.identity);
// Another line
blockPrefab = buildingPrefabs[BlockID];
Destroy(ghostBlock);
ghostBlock = Instantiate(buildingPrefabs[BlockID], hitPoint, Quaternion.identity);
If you really want to remove an asset use DestroyImmediate (theObject, true);```
I keep getting this error when i change the block ID
thats usually the issue 😄
thats exactly whats confusing me lmao
Save and try again
ohh u are.. b/c u reset it
you basically instantiated and destroyed the prefab at the very next line
lol.. nah his code has similar wording
i think we were missreading it
he destroys ghostBlock not blockPrefab
i have no idea what to do lol
I think the excerpt is missing some data
possibly.. can u show more of the code? or is that all thats relevant?
is this maybe an old message ?
i think this might be the case
sure i'll put it in a pastebin
Maybe we're looking at the wrong spot
code-dump incoming
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i think thats all that is relevant
error doesnt give any line-num does it
Interactor:PlaceBlock () (at Assets/Scipts/Interactor.cs:268)
Interactor:Update () (at Assets/Scipts/Interactor.cs:75)
One message removed from a suspended account.
which is, one second
I think unless you know the exact line number you're going to need to show everything
this aint even the whole code..
Did you make ghost block reference your prefab?
where are the definitions
yeah
Because if you did, you'll get that error you've shown earlier
https://pastebin.com/W27FhBVL
here is whole code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
aslo please use one of the sites from !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i wont bother reuploading that'll just be spamming but for next time i'll use a different provider
yeah its hard to read on mobile 😢
a link with pure code is a godsend. no noise, no nothing; just code . . .
i do try and give just relevant code most of the time but it never helps in the long run lmao
its pretty straight forward.. here is your code :
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * speed); // Move the object using the transformed move vector```
and here is the instructions i gave you :
```cs
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
move.Normalize(); // normalize the move vector
move = transform.TransformDirection(move); // transform the move vector to match the direction of the object
controller.Move(move * Time.deltaTime * speed);
Don't reference your prefab with ghost block
only places I can find ghostBlock is Instantiating it
unless im not understanding right
Did you reference it from the inspector?
You've likely referenced a prefab from the inspector
these are just prefabs tho, I have other variables that instantiate
speaking of which!
basically working on a .net powered Paste code app 😛
still fixing the result css but yeah inspired by gdl.space
sorry not unity related 😛
One message removed from a suspended account.
One message removed from a suspended account.
oh snap, that's cool . . .
who says webapps need js frameworks 💩
yo does anyone know why my code only calculates the speed only like once per 5 frames? here is the code and a vid of the output(I'm trying to debug why my code isn't restricting the speed of the player) its a bunch but ill highlight the important bit: https://gdl.space/udutafupek.cs
btw i have bad wifi rn so i might take a while to respond sometimes
physics doesn't update every frame
if you want to be synced with the physics engine, that's what FixedUpdate is for
(you should also not be using AddForce in Update)
why shuldnt i?
because it will lead to inconsistent behavior depending on your framerate
Physics objects should be moved in FixedUpdate
The physics simulation needs to happen at a fixed timestep or you will not get consistent behavior, and no this can't be fixed with Time.deltaTime
alright i will change it to fixedupate. thanks for the help
btw you probably want to figure out a better isGrounded solution later on. The current one will count you as grounded if hit obstacle in the air with your body/face
OnCollisionEnter for grounding is not very reliable
Anybody an idea why I get a nullreference exception in my build at if(gameManager.GameIsPaused)?
private void Start()
{
if (gameManager == null) gameManager = GameManager.Instance;
}
private void Update()
{
if (gameManager.GameIsPaused)
{
UpdateCursorLockState(CursorLockState.Confined);
}
else
{
UpdateCursorLockState(CursorLockState.Locked);
}
}
why isnt it reliable?(im very new to unity/c# dev and im going to ask a lot of questions)
gameManager is null
nothing else can be null on that line
I just give you an example . Since it doesn't care which part of the collider is touching , if you jump and hit your head on platform or walk into it then it says grounded even if your feet are not touching ground
One message removed from a suspended account.
I drag and dropped it so it isn't null
One message removed from a suspended account.
code says otherwise
But why is it null in the line below then
oh i read that wrong thanks for clarifying.
because ur only using it in the if statement ?
if you said you assigned it and its not being unassigned at runtime, then you have a copy of the script with one unassigned
okay let me remove the if null and run again
thats a band-aid to a bigger problem
I wonder why it's only debugging that in the dev build and not in the editor
if you are using an instance most likely the order got changed up in build or something
if you need to start changing orders of executions , your whole design is probably not good
show the full error
also are you exporting the correct scene
should be
NullReferenceException: Object reference not set to an instance of an object
at CursorHandler.Update () [0x00001] in C:\REDACTED\UnityC\AFishFestGameURP\Assets\1_Scripts\Player\CursorHandler.cs:34
ok and
CursorHandler.cs:34 is what
public class PlayerMovement : MonoBehaviour
{
private PlayerControls playerControls;
[SerializeField] Rigidbody2D rb;
[SerializeField] private float Speed = 10;
[SerializeField] private float JumpHeight = 50;
private bool IsGrounded = false;
private void OnTriggerEnter2D(Collider2D collision) {
IsGrounded = true;
}
private void OnTriggerExit2D(Collider2D collision)
{
IsGrounded = false;
}
private void Awake()
{
playerControls = new PlayerControls();
}
private void OnEnable() {
playerControls.Enable();
}
private void OnDisable() {
playerControls.Disable();
}
void Start()
{
Application.targetFrameRate = 60;
}
void Update()
{
Vector2 Move = playerControls.Move.Move.ReadValue<Vector2>();
rb.velocity = new Vector2( Move.x * Speed, transform.position.y);
if (playerControls.Move.Jump.IsPressed() && IsGrounded)
{
rb.AddForce(new Vector2(Move.x, JumpHeight));
}
}
}
hi this is my basic player movement srcipt, do i reset the y axis somewhere? bc my player isnt jumping as high as he should with jumpforce 4500, except in some weird cases he gets shot out of the known universe
Only drag and drop
also polling every update for GameIsPaused is overkill
Yeah that's moment where I do IEnumerator and check every second or smth
But my friend is waiting for the build for 6 hours now 💀
the best way to do it is an event
GameManager invokes a static event
public static Action<bool> OnGamePaused;
since when doesn't GameManager have the special icon btw?
it does
what about inspector?
please help me with this
velocity will always override AddForce
you mean 2022?
yeah
oh thought I'd seen someone use .30f1
idk i think version control might be messing with the icon
ok so what can i do about this?
In Update, you're putting the Y position of your object into the velocity. This won't end well
switch your Jump to .velocity OR you have to only override the X velocity in the .velocity
The higher you'll be, the faster you'll be going upwards
also fix that
yeah that makes sense
ok i try
Not to interrupt what you guys are doing, but I was wondering if anyone could help me with some issues I'm running into with a basic game I'm working on
If you ask about the issues, people might help you.
I also get an error on the second line, even tho it works in the editor at runtime
if (renderManager == null) renderManager = RenderManager.Instance;
if (this.MaxPlayerDistance != renderManager.MaxPlayerDistance) this.MaxPlayerDistance = renderManager.MaxPlayerDistance;
did you try the first thing first?
Both errors still there
This is start
both are start
private void Update()
{
if(gameManager == null) return;
if (gameManager.GameIsPaused)
{
UpdateCursorLockState(CursorLockState.Confined);
}
okay, I created a 7x7 hexagon grid and have an enemy in the middle of it. I'm trying to figure out how to write a code that has the enemy move one tile per turn towards the nearest edge piece.
nvm the first one is update
did you see what i wrote? try that then make build , check if any errors. Prob not
if no errors , you know that it was running without being assigned
probably some A* type algo
Yeah I watched a video on A* and got confused. I don't understand how each tile can be considered a unique node
wdym how ? just how you said it. Take the positions turn them into "nodes" they just represent necessary data, like F cost and all that
📃 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, how can i move center of my Physics2D.overlapbox?
So I set the node to the starting tiles position, then put it in a list, then set nodes for all adjacent tiles and add them and so on?
You cannot. The center is the center, so it's always in the center of the box.
One message removed from a suspended account.
One message removed from a suspended account.
Yes, why wouldn't you?
it's 👇
#💻┃code-beginner message
One message removed from a suspended account.
One message removed from a suspended account.
thought, https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html was good enough for his use-case but apparently it didn't help
are you following a particular tutorial?
You should post the code in a text form. !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.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
well, on the site.
📃 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.
One message removed from a suspended account.
my CC works the exact same way.. groundVector is just new Vector2(horizontalAxis, 0, verticalAxis);
if(useTransformDirection)
{
// run it through the TransformDirection to make movement relative to players direction
groundVector = transform.TransformDirection(groundVector);
}
else
{
groundVector = groundVector;
}```
in the clip the first part is using TransformDirection() and the 2nd part is when I disable it.. (then my turning doesn't matter)
it just moves relative to the world (w/o my facing direction mattering)
you said you tried it but didn't work.. thats interesting.. is ur Movement code running on the same object as the CC it should be
The code seems right, you don't have any issues now, do you?
One message removed from a suspended account.
Vector2.Normalize() is unnecessary if you use GetAxisRaw(), but this, obviously, won't fix it
One message removed from a suspended account.
Actually normalizing here is not good because it'll take a very noticeable amount of time for the player to stop moving, since GetAxis is smoothed you'll have a few frames between the moment you release the keys and the vector falls back to exactly (0, 0, 0)
One message removed from a suspended account.
true, I use raw but his code wasn't
One message removed from a suspended account.
Wait, the movement works fine
Just move your camera look component to the parent
The TransformDirection works perfectly, so the issue is in the Camera, isn't it?
the camera child doesn't (and shouldn't) need to be rotating separately from the parent
perhaps the camera isn't rotating ur CC
if ur CC doesn't actually rotate then the TransformDirection isn't actually gonna work for ur usecase
not by applying it to the cc's transform atleast
One message removed from a suspended account.
your camera should be parented under the CC but u camera script need to rotate the camera up and down..
but rotate teh CC left and right
One message removed from a suspended account.
The camera GameOject should remain as a child of the player.
The camera rotation Component should be on the parent, and not the camera.