# How to create a sum vector function ?

Hi,

I’m looking to create a sum vector function
List ListVectors;
Vector3 V;
V = Sum (0 to k) ListVectors [k]

I know that we can add Vector3 but the operator + = is not applicable to vectors.
I cannot write:
Vector3 W;
while (j <10)
{
Vector3 W + = new Vector3 (1,2,3);
j ++;
}

thanks

Au contraire my friend! You certainly can write that.

You are just declaring W twice in the same scope, and you are failing to initialize W to zero before using it.

``````Vector3 W = Vector3.zero;
``````

inside your loop remove the declaration:

``````W += new Vector3(1,2,3);
``````

You are already 90% there. As Kurt pointed out, you erroneously re-defined W inside the loop. In a foreach loop, your code looks even simpler. If we are to assume that you want to add all vectors in a List, this should do it:

``````Vector3 VSum = Vector3.zero;
foreach (Vector3 v in ListVectors){
VSum += v;
}
``````

In this C # script below, I create a list of vectors. Each time I press the I key, I add the vector (2,0,2) to this list.
This list contains first null vector.
The second of this list (0,0,2) is generated at the launch of the game, before pressing the I key
problem:
on the second press, the second generated object takes the position (10,0,6) instead of
null vector + (0,0,2) + (2,0,2) = (2,0,4): the sum in this list is not respected.

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class somme_position : MonoBehaviour
{
int p = 0;

public Mesh[] myMesh = new Mesh[10];
public GameObject Objet1;
Vector3 VSum = Vector3.zero;

List<GameObject> ObjectList;

List<Vector3> ListVecteurs;

void Start()
{

ObjectList = new List<GameObject>();

ListVecteurs = new List<Vector3>();

Vector3 V1 = new Vector3(0,0,,2);

ObjectList[0].transform.position = ListVecteurs[1];

}

void Update()
{

if (Input.GetKeyDown(KeyCode.I))
{
p++;

ObjectList[p] = new GameObject("toto" + p);

foreach (Vector3 v in ListVecteurs)
{
VSum += v;
}

ObjectList[p].transform.position = VSum;//pas bonne valeur

}
}

}
``````

Where does the problem come from?
How to solve it?

thanks

On first blush (sorry, not much time) I notice that you do not initialize VSum before you sum up the vectors in the foreach loop. Since you don’t they all get added to the previous result. You should insert VSum = Vector3.zero before the foreach loop.

I did it at line 15 !

Yes, but only once. The init in line 15 is only executed once, during script start. You need to re-init before you re-do the sum, else it will remember the next time you press ‘p’ andd add to the previous result.

1 Like